reifyui 0.4.2 → 0.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reifyui",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "The open-source rendering & interaction layer for agentic applications. Stream and render any agent's output as polished, application-native UI \u2014 model-agnostic, framework-agnostic, design-system-native. The foundation for building generative-UI and agent products.",
5
5
  "keywords": [
6
6
  "react",
@@ -41,6 +41,11 @@
41
41
  "import": "./dist/slides.js",
42
42
  "require": "./dist/slides.cjs"
43
43
  },
44
+ "./harness": {
45
+ "types": "./dist/harness.d.ts",
46
+ "import": "./dist/harness.js",
47
+ "require": "./dist/harness.cjs"
48
+ },
44
49
  "./styles/*": "./styles/*",
45
50
  "./package.json": "./package.json"
46
51
  },
@@ -0,0 +1,88 @@
1
+ // reifyui/harness — the HarnessRouter transport for apps served by the HarnessRouter console.
2
+ //
3
+ // Hand-authored, like the rest of this package's types: the implementation is plain ESM.
4
+ import type { ResponseHandlers } from '../index';
5
+
6
+ export interface KitConfig {
7
+ /** What GET /v1/harnesses reports in `kit` for the harness this kit launched. */
8
+ kitId: string;
9
+ /** The console's API proxy. Same-origin, so the console session authenticates every call. */
10
+ base: string;
11
+ }
12
+ export function configureKit(config: Partial<KitConfig>): KitConfig;
13
+ export function kitConfig(): KitConfig;
14
+
15
+ /** An Error from `hr` carries the HTTP status, so callers can branch on 409 / 404. */
16
+ export interface HarnessError extends Error { status?: number }
17
+ export function hr(path: string, init?: RequestInit): Promise<any>;
18
+
19
+ export interface Harness {
20
+ id: string;
21
+ name: string;
22
+ base?: string;
23
+ defaultModel?: string;
24
+ /** The starter kit that launched this harness, or null for a hand-made one. */
25
+ kit?: string | null;
26
+ additionalHeaders?: Record<string, string>;
27
+ [key: string]: unknown;
28
+ }
29
+ export function listHarnesses(): Promise<Harness[]>;
30
+ /** Null when the kit was never launched — a real answer the caller must render. */
31
+ export function kitHarness(): Promise<Harness | null>;
32
+
33
+ export interface Session {
34
+ id: string;
35
+ title?: string;
36
+ status?: string;
37
+ turn_status?: string;
38
+ created_at?: string | number;
39
+ updated_at?: string | number;
40
+ [key: string]: unknown;
41
+ }
42
+ export function listSessions(opts?: { limit?: number }): Promise<{ sessions: Session[]; cursor: string | null }>;
43
+ export function sessionDetail(sid: string): Promise<Session>;
44
+ export function patchSession(sid: string, patch: { title: string }): Promise<unknown>;
45
+ export function deleteSession(sid: string): Promise<unknown>;
46
+
47
+ /** Reads the LIVE workspace, so a file appears the moment the agent writes it. Null if absent. */
48
+ export function readFile(sid: string, path: string): Promise<string | null>;
49
+ export function readJsonFile<T = unknown>(sid: string, path: string): Promise<T | null>;
50
+ /** Refused 409 `session_busy` while that session has a turn running. Re-arm; never drop. */
51
+ export function writeFile(sid: string, path: string, content: string): Promise<unknown>;
52
+ export function containerFileUrl(containerId: string, fileId: string): string;
53
+
54
+ export interface Turn {
55
+ user?: string;
56
+ assistant?: string;
57
+ status?: string;
58
+ tools?: Array<{ name: string; arguments?: unknown; result?: unknown }>;
59
+ [key: string]: unknown;
60
+ }
61
+ export function sessionTurns(sid: string, opts?: { limit?: number }): Promise<Turn[]>;
62
+ export function getResponse(rid: string): Promise<any>;
63
+ export function createResponse(
64
+ body: Record<string, unknown>,
65
+ opts?: { idempotencyKey?: string; stream?: boolean },
66
+ ): Promise<any>;
67
+ export function cancelResponse(rid: string): Promise<unknown>;
68
+ export function cancelSession(sid: string): Promise<unknown>;
69
+
70
+ /** ResponseHandlers already carries onSession — a brand-new document learns its own id there. */
71
+ export type StreamTurnHandlers = ResponseHandlers;
72
+ export function streamTurn(args: {
73
+ sessionId?: string;
74
+ harnessId?: string;
75
+ input: unknown;
76
+ /** Framing goes here, never in `input`: the transcript must show the person's own words. */
77
+ instructions?: string;
78
+ handlers?: StreamTurnHandlers;
79
+ }): Promise<{ ok?: boolean; sessionId?: string; connecting?: boolean }>;
80
+
81
+ export interface ChatMessage {
82
+ role: 'user' | 'assistant';
83
+ text?: string;
84
+ blocks?: Array<Record<string, unknown>>;
85
+ status?: string;
86
+ }
87
+ export function turnsToMessages(turns: Turn[]): ChatMessage[];
88
+ export function lastAssistantText(turns: Turn[]): string;
@@ -0,0 +1,266 @@
1
+ // The HarnessRouter transport, for apps served by the HarnessRouter console.
2
+ //
3
+ // A "kit" is a single-page app the console serves at /kits/<id>, same-origin with its API proxy.
4
+ // That origin is the whole authentication story: the console already signed the person in, the
5
+ // browser carries that session on every request, and the proxy attaches the internal key
6
+ // server-side. There is no token here, no login screen, and nothing to refresh.
7
+ //
8
+ // The model these functions speak:
9
+ //
10
+ // a document = a session on the kit's Harness (the session list IS the document list)
11
+ // its content = a file in that session's workspace
12
+ // talking to it= POST /responses with that session id
13
+ //
14
+ // Every route below is one the gateway actually implements. Keeping them in one file is the
15
+ // point: the first kit shipped five separate bugs that were all the same bug — a call carried
16
+ // over from a hosted product to an endpoint that does not exist here. A second kit copying this
17
+ // file would inherit the next five. Functions only, no hooks: a hook encodes page structure, and
18
+ // that genuinely differs per kit.
19
+ import { createResponsesDispatcher, readSSEStream } from '../stream/responses.js';
20
+
21
+ let CONFIG = { kitId: '', base: '/api/harness/v1' };
22
+
23
+ /** Call once at boot. kitId is what /v1/harnesses reports in `kit` for the harness this kit launched. */
24
+ export function configureKit({ kitId, base } = {}) {
25
+ CONFIG = { kitId: kitId || CONFIG.kitId, base: base || CONFIG.base };
26
+ _harness = null;
27
+ return CONFIG;
28
+ }
29
+
30
+ export function kitConfig() { return { ...CONFIG }; }
31
+
32
+ async function readError(res) {
33
+ try {
34
+ const body = await res.json();
35
+ const d = body?.error?.message ?? body?.detail;
36
+ return typeof d === 'string' ? d : `request failed (${res.status})`;
37
+ } catch {
38
+ return `request failed (${res.status})`;
39
+ }
40
+ }
41
+
42
+ /** One request. Throws an Error carrying `.status` so callers can branch on 409 / 404. */
43
+ export async function hr(path, init = {}) {
44
+ const res = await fetch(`${CONFIG.base}${path}`, { cache: 'no-store', ...init });
45
+ if (!res.ok) {
46
+ const err = new Error(await readError(res));
47
+ err.status = res.status;
48
+ throw err;
49
+ }
50
+ return res.status === 204 ? null : res.json();
51
+ }
52
+
53
+ function jsonInit(method, body, headers) {
54
+ return {
55
+ method,
56
+ headers: { 'content-type': 'application/json', ...(headers || {}) },
57
+ body: JSON.stringify(body),
58
+ };
59
+ }
60
+
61
+ // ── harnesses ──────────────────────────────────────────────────────────────
62
+ export async function listHarnesses() {
63
+ const { harnesses = [] } = await hr('/harnesses');
64
+ return harnesses;
65
+ }
66
+
67
+ let _harness = null;
68
+
69
+ /** The Harness this kit launched, or null when the kit was never launched.
70
+ *
71
+ * Null is a real answer and callers must render it. Swallowing it into an empty list shows an
72
+ * empty "no documents yet" screen to someone whose actual problem is that nothing is running. */
73
+ export async function kitHarness() {
74
+ if (_harness) return _harness;
75
+ const harnesses = await listHarnesses();
76
+ _harness = harnesses.find((h) => h.kit === CONFIG.kitId) || null;
77
+ return _harness;
78
+ }
79
+
80
+ // ── sessions (= documents) ─────────────────────────────────────────────────
81
+ /** The kit's documents, newest first. The filter is `harness` — an unknown query param is
82
+ * ignored rather than refused, so the wrong name silently returns every session in the org. */
83
+ export async function listSessions({ limit = 100 } = {}) {
84
+ const h = await kitHarness();
85
+ if (!h) return { sessions: [], cursor: null };
86
+ const body = await hr(`/sessions?harness=${encodeURIComponent(h.id)}&limit=${limit}`);
87
+ return { sessions: body?.sessions ?? body?.data ?? [], cursor: body?.cursor ?? null };
88
+ }
89
+
90
+ export function sessionDetail(sid) {
91
+ return hr(`/sessions/${encodeURIComponent(sid)}`);
92
+ }
93
+
94
+ /** Rename. This also rewrites the trace manifest the session LIST renders from, and marks the
95
+ * title as chosen so the next turn stops regenerating it from the latest user message. */
96
+ export function patchSession(sid, { title }) {
97
+ return hr(`/sessions/${encodeURIComponent(sid)}`, jsonInit('PATCH', { title }));
98
+ }
99
+
100
+ /** Delete a document and the conversation underneath it. The route is /traces/{id}: there is no
101
+ * DELETE on the session path, and this one removes the trace, the durable workspace tarball and
102
+ * tombstones the session. */
103
+ export function deleteSession(sid) {
104
+ return hr(`/traces/${encodeURIComponent(sid)}`, { method: 'DELETE' });
105
+ }
106
+
107
+ // ── workspace files ────────────────────────────────────────────────────────
108
+ /** Read one file by path, from the LIVE workspace — so a file appears the moment the agent
109
+ * writes it, mid-turn. Returns null when it does not exist yet.
110
+ *
111
+ * Do not reach for the file LISTING to detect a file: that answers from the end-of-turn
112
+ * checkpoint tarball and shows a spinner over a file already on disk. */
113
+ export async function readFile(sid, path) {
114
+ const r = await fetch(`${CONFIG.base}/sessions/${encodeURIComponent(sid)}/files/${path}`,
115
+ { cache: 'no-store' });
116
+ if (!r.ok) return null;
117
+ return r.text();
118
+ }
119
+
120
+ export async function readJsonFile(sid, path) {
121
+ const text = await readFile(sid, path);
122
+ if (text == null) return null;
123
+ try { return JSON.parse(text); } catch { return null; }
124
+ }
125
+
126
+ /** Write a workspace file. Refused 409 `session_busy` while that session has a turn running —
127
+ * the agent owns its workspace until it finishes. Blocking is honest; both sides silently
128
+ * racing is not. Callers must re-arm rather than drop the write. */
129
+ export function writeFile(sid, path, content) {
130
+ return hr(`/sessions/${encodeURIComponent(sid)}/files/${path}`, jsonInit('PUT', { content }));
131
+ }
132
+
133
+ /** A URL that serves one artifact's bytes. Same-origin, so it works in <img src> directly. */
134
+ export function containerFileUrl(containerId, fileId) {
135
+ return `${CONFIG.base}/containers/${encodeURIComponent(containerId)}`
136
+ + `/files/${encodeURIComponent(fileId)}/content`;
137
+ }
138
+
139
+ // ── turns and responses ────────────────────────────────────────────────────
140
+ /** The conversation so far, oldest first. Replays from the trace WHILE a turn is in flight, so
141
+ * it is also how a reopened tab watches a running turn without a stream. */
142
+ export async function sessionTurns(sid, { limit } = {}) {
143
+ const q = limit ? `?limit=${limit}` : '';
144
+ const body = await hr(`/sessions/${encodeURIComponent(sid)}/turns${q}`).catch(() => null);
145
+ return body?.turns ?? [];
146
+ }
147
+
148
+ export function getResponse(rid) {
149
+ return hr(`/responses/${encodeURIComponent(rid)}`);
150
+ }
151
+
152
+ /** Start a turn.
153
+ *
154
+ * idempotencyKey is not optional decoration for a background dispatch: without it a retry after
155
+ * a flaky reply starts a SECOND turn on a session that may already be running one, and two
156
+ * concurrent turns on one session destroy that session's workspace (each turn wipes and
157
+ * restores it, so the last writer wins with an empty tree). With the key, a duplicate replays
158
+ * the first response instead of running again. */
159
+ export function createResponse(body, { idempotencyKey, stream } = {}) {
160
+ const headers = {};
161
+ if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;
162
+ if (stream) headers.accept = 'text/event-stream';
163
+ return hr('/responses', jsonInit('POST', body, headers));
164
+ }
165
+
166
+ /** Cancel one turn. Preferred over cancelling the session: it only kills the sandbox when it can
167
+ * prove this response owns the live turn, and otherwise lets the turn self-terminate. */
168
+ export function cancelResponse(rid) {
169
+ return hr(`/responses/${encodeURIComponent(rid)}/cancel`, { method: 'POST' });
170
+ }
171
+
172
+ export function cancelSession(sid) {
173
+ return hr(`/sessions/${encodeURIComponent(sid)}/cancel`, { method: 'POST' });
174
+ }
175
+
176
+ // ── streaming one turn ─────────────────────────────────────────────────────
177
+ /** Pull a session id out of whatever frame carries it, without caring which one that is. */
178
+ function sessionIdOf(evt) {
179
+ return evt?.metadata?.session_id || evt?.response?.metadata?.session_id
180
+ || evt?.session_id || evt?.response?.session_id || null;
181
+ }
182
+
183
+ /** Run one streaming turn against the kit's own harness.
184
+ *
185
+ * `sessionId` may be empty for a brand-new document: nothing but a turn creates a session, so
186
+ * the id arrives in the stream and is reported through onSession before the frame is dispatched.
187
+ *
188
+ * Framing belongs in `instructions`, never in `input`. The gateway captures the user text before
189
+ * it prepends instructions, so the transcript, the console task list and the trace all show the
190
+ * person's own sentence instead of our scaffolding.
191
+ *
192
+ * handlers: the ReifyUI dispatcher's (onTextDelta, onReasoningDelta, onToolCall, onToolResult,
193
+ * onDone, onError) plus onSession(sessionId).
194
+ *
195
+ * Returns {ok, sessionId}, or {connecting:true} when the gateway is still coming up (503).
196
+ */
197
+ export async function streamTurn({ sessionId, harnessId, input, instructions, handlers = {} }) {
198
+ let hid = harnessId;
199
+ if (!hid) {
200
+ const h = await kitHarness();
201
+ if (!h) throw new Error('This kit has not been launched yet.');
202
+ hid = h.id;
203
+ }
204
+ const existing = sessionId ? String(sessionId) : '';
205
+ const res = await fetch(`${CONFIG.base}/responses`, {
206
+ method: 'POST',
207
+ cache: 'no-store',
208
+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
209
+ body: JSON.stringify({
210
+ input,
211
+ ...(instructions ? { instructions } : {}),
212
+ metadata: { harness_id: hid, ...(existing ? { session_id: existing } : {}) },
213
+ stream: true,
214
+ }),
215
+ });
216
+ if (res.status === 503) return { connecting: true };
217
+ if (!res.ok || !res.body) {
218
+ const t = await res.text().catch(() => '');
219
+ throw new Error(`turn failed: ${res.status} ${t.slice(0, 160)}`);
220
+ }
221
+
222
+ let sawError = false;
223
+ let sid = existing;
224
+ const d = createResponsesDispatcher({
225
+ ...handlers,
226
+ onError: (msg) => { sawError = true; handlers.onError?.(msg); },
227
+ });
228
+ await readSSEStream(res.body, (data) => {
229
+ let evt;
230
+ try { evt = JSON.parse(data); } catch { return; } // malformed frame
231
+ const found = sessionIdOf(evt);
232
+ if (found && found !== sid) { sid = found; handlers.onSession?.(found); }
233
+ d.dispatch(evt);
234
+ });
235
+ return { ok: !sawError, sessionId: sid };
236
+ }
237
+
238
+ // ── replaying history ──────────────────────────────────────────────────────
239
+ const TURN_STATUS = {
240
+ failed: 'failed', error: 'failed', cancelled: 'cancelled',
241
+ incomplete: 'incomplete', max_turns: 'incomplete', timeout: 'incomplete',
242
+ };
243
+
244
+ /** Gateway turns -> ChatMessages' message shape. */
245
+ export function turnsToMessages(turns) {
246
+ const out = [];
247
+ for (const t of turns || []) {
248
+ if (t.user) out.push({ role: 'user', text: t.user });
249
+ const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));
250
+ const blocks = [];
251
+ if (steps.length) blocks.push({ kind: 'tools', reasoning: '', steps });
252
+ if (t.assistant) blocks.push({ kind: 'text', text: t.assistant });
253
+ const status = TURN_STATUS[t.status] || 'done';
254
+ if (blocks.length || status !== 'done') out.push({ role: 'assistant', blocks, status });
255
+ }
256
+ return out;
257
+ }
258
+
259
+ /** The assistant text of a session's last turn — what a document page shows when there is no
260
+ * document yet and the agent has stopped. The real explanation is usually in there. */
261
+ export function lastAssistantText(turns) {
262
+ for (let i = (turns || []).length - 1; i >= 0; i--) {
263
+ if (turns[i]?.assistant) return String(turns[i].assistant);
264
+ }
265
+ return '';
266
+ }
package/src/index.d.ts CHANGED
@@ -229,6 +229,87 @@ export const GoogleButton: ComponentType<Record<string, unknown>>;
229
229
  export const GOOGLE_ENABLED: boolean;
230
230
 
231
231
  // ── AI spreadsheet grid ──────────────────────────────────────────────────────
232
- export const SheetGrid: ComponentType<Record<string, unknown>>;
233
- export function sheetToDelimited(sheet: unknown, delimiter?: string): string;
234
- export function sheetToAoA(sheet: unknown): unknown[][];
232
+ export interface SheetColumn {
233
+ id: string;
234
+ name: string;
235
+ type: string;
236
+ width?: number;
237
+ options?: Array<string | { label?: string; value?: unknown; color?: string }>;
238
+ [key: string]: unknown;
239
+ }
240
+ export interface SheetRow { id: string; height?: number; [key: string]: unknown }
241
+ export interface SheetCell { value?: unknown; status?: string; error?: string | null; [key: string]: unknown }
242
+ export interface Sheet {
243
+ meta?: { title?: string; [key: string]: unknown };
244
+ columns?: SheetColumn[];
245
+ rows?: SheetRow[];
246
+ cells?: Record<string, SheetCell>;
247
+ [key: string]: unknown;
248
+ }
249
+
250
+ /** One entry in the grid's column vocabulary. A host adds a column kind by adding a descriptor
251
+ * — the grid has no hardcoded knowledge of any type beyond its own defaults. */
252
+ export interface SheetColumnType {
253
+ type: string;
254
+ label: string;
255
+ /** The app fills these cells: status dot, tint, and run affordances. */
256
+ computed?: boolean;
257
+ /** Defaults to !computed. */
258
+ editable?: boolean;
259
+ /** The column key holding this type's config; dropped when the type changes. */
260
+ configKey?: string;
261
+ /** An extra header sub-label, e.g. which kind of compute this is. */
262
+ badge?: (column: SheetColumn) => string | undefined;
263
+ }
264
+
265
+ export interface SheetCellRenderContext {
266
+ cell: SheetCell;
267
+ column: SheetColumn;
268
+ row: SheetRow;
269
+ rowIndex: number;
270
+ sheet: Sheet;
271
+ computed: boolean;
272
+ width?: number;
273
+ height?: number;
274
+ editing: boolean;
275
+ readOnly: boolean;
276
+ setCell: (value: unknown) => void;
277
+ runCell: (() => void) | null;
278
+ }
279
+
280
+ export interface SheetColumnConfigContext {
281
+ column: SheetColumn;
282
+ columns: SheetColumn[];
283
+ /** The type currently selected in the popover, which may differ from column.type. */
284
+ type: string;
285
+ /** Commit the column patch and close the popover. */
286
+ applyPatch: (patch: Record<string, unknown>) => void;
287
+ deleteColumn: () => void;
288
+ close: () => void;
289
+ }
290
+
291
+ export interface SheetGridProps {
292
+ sheet: Sheet;
293
+ onChange?: (next: Sheet) => void;
294
+ onRunCell?: (rowId: string, colId: string) => void;
295
+ onRunColumn?: (colId: string) => void;
296
+ readOnly?: boolean;
297
+ fetchBlobUrl?: (path: string) => Promise<string>;
298
+ onOpenResource?: (ref: Record<string, unknown>) => void;
299
+ peerMarks?: Record<string, { name: string; color: string }>;
300
+ onActiveCell?: (cellKey: string | null) => void;
301
+ columnTypes?: SheetColumnType[];
302
+ /** Replace a cell's body. Return undefined to fall through to the built-in rendering. */
303
+ renderCell?: (ctx: SheetCellRenderContext) => ReactNode | undefined;
304
+ /** Replace the column popover's body. Return undefined to fall through. */
305
+ renderColumnConfig?: (ctx: SheetColumnConfigContext) => ReactNode | undefined;
306
+ }
307
+ export const SheetGrid: ComponentType<SheetGridProps>;
308
+
309
+ /** cellText says what one cell is worth in a flat file — without it, a cell holding an object
310
+ * exports as raw JSON. */
311
+ export interface SheetExportOptions {
312
+ cellText?: (cell: SheetCell | undefined, column: SheetColumn) => string | number | boolean;
313
+ }
314
+ export function sheetToDelimited(sheet: Sheet, delimiter?: string, options?: SheetExportOptions): string;
315
+ export function sheetToAoA(sheet: Sheet, options?: SheetExportOptions): unknown[][];