@paddockai/react 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -18,12 +18,19 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
 
20
20
  // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
23
  PaddockProvider: () => PaddockProvider,
24
- useSession: () => useSession
24
+ useComposer: () => useComposer,
25
+ useConversation: () => useConversation,
26
+ useSession: () => useSession,
27
+ useSessionStatus: () => useSessionStatus,
28
+ useSessionToken: () => useSessionToken,
29
+ useToolCall: () => useToolCall
25
30
  });
26
- module.exports = __toCommonJS(index_exports);
31
+ module.exports = __toCommonJS(src_exports);
32
+
33
+ // src/session.ts
27
34
  var import_react = require("react");
28
35
  var import_client = require("@paddockai/client");
29
36
  var Defaults = (0, import_react.createContext)({});
@@ -43,18 +50,500 @@ ${token}`;
43
50
  return client.session(sessionId);
44
51
  }
45
52
  var serverSnapshot = () => import_client.initialState;
53
+ var settled = (s) => s.connection === "open" || s.connection === "closed" && s.connectionError !== null;
54
+ var noToken = () => Promise.reject(new Error("paddock: no session token yet"));
55
+ var idle = () => () => void 0;
46
56
  function useSession(sessionId, options) {
47
57
  const defaults = (0, import_react.useContext)(Defaults);
48
58
  const baseUrl = options.baseUrl ?? defaults.baseUrl;
49
- const handle = (0, import_react.useMemo)(() => sharedHandle(baseUrl, options.token, sessionId), [baseUrl, options.token, sessionId]);
50
- const subscribe = (0, import_react.useCallback)((onChange) => handle.subscribe(onChange), [handle]);
51
- const state = (0, import_react.useSyncExternalStore)(subscribe, () => handle.state, serverSnapshot);
52
- const send = (0, import_react.useCallback)((text) => handle.send(text), [handle]);
53
- const stop = (0, import_react.useCallback)(() => handle.stop(), [handle]);
59
+ const handle = (0, import_react.useMemo)(
60
+ () => options.token ? sharedHandle(baseUrl, options.token, sessionId) : null,
61
+ [baseUrl, options.token, sessionId]
62
+ );
63
+ const subscribe = (0, import_react.useCallback)((onChange) => handle ? handle.subscribe(onChange) : idle(), [handle]);
64
+ const live = (0, import_react.useSyncExternalStore)(subscribe, () => handle?.state ?? import_client.initialState, serverSnapshot);
65
+ const shown = (0, import_react.useRef)(null);
66
+ let state = live;
67
+ const last = shown.current;
68
+ if (last?.handle && handle && last.handle !== handle && last.sessionId === sessionId && !settled(live))
69
+ state = last.state;
70
+ else shown.current = { sessionId, handle, state: live };
71
+ const send = (0, import_react.useCallback)((text) => handle ? handle.send(text) : noToken(), [handle]);
72
+ const stop = (0, import_react.useCallback)(() => handle ? handle.stop() : noToken(), [handle]);
54
73
  return (0, import_react.useMemo)(() => ({ ...state, send, stop }), [state, send, stop]);
55
74
  }
75
+
76
+ // src/hooks.ts
77
+ var import_react2 = require("react");
78
+
79
+ // src/conversation.ts
80
+ var turnEvents = /* @__PURE__ */ new Set(["message", "turn.started", "turn.ended"]);
81
+ function delivery(seq, s) {
82
+ if (seq <= s.processedSeq) return "processed";
83
+ if (s.turn?.inputSeqs.includes(seq)) return "processing";
84
+ if (seq <= s.heldSeq) return "held";
85
+ return "waiting";
86
+ }
87
+ function retryOf(ended) {
88
+ const retry = ended?.turn.retry;
89
+ return {
90
+ retryAt: typeof retry?.at === "string" ? retry.at : null,
91
+ gaveUp: retry?.giveUp === true
92
+ };
93
+ }
94
+ function messagePart(m, toolPart) {
95
+ const raw = m;
96
+ switch (m.kind) {
97
+ case "assistant":
98
+ return { kind: "text", id: m.id, text: m.text, streaming: false };
99
+ case "streaming":
100
+ return { kind: "text", id: m.id, text: m.text, streaming: true };
101
+ case "reasoning":
102
+ return { kind: "reasoning", id: m.id, text: m.text };
103
+ case "tool_call":
104
+ case "tool_result":
105
+ return toolPart(m);
106
+ case "unknown":
107
+ return { kind: "unknown", id: m.id, harness: m.harness, type: m.type, raw: m.raw };
108
+ default: {
109
+ const rest = { ...raw };
110
+ delete rest.seq;
111
+ delete rest.turnId;
112
+ delete rest.createdAt;
113
+ return { kind: "unknown", id: m.id, harness: null, type: raw.kind, raw: rest };
114
+ }
115
+ }
116
+ }
117
+ function conversation(s, options = {}) {
118
+ const notices = new Set(options.notices ?? []);
119
+ const started = /* @__PURE__ */ new Map();
120
+ const ended = /* @__PURE__ */ new Map();
121
+ const startOrder = [];
122
+ const noticeEvents = [];
123
+ for (const e of s.events) {
124
+ if (e.type === "turn.started" && e.turnId) {
125
+ if (!started.has(e.turnId)) startOrder.push(e);
126
+ started.set(e.turnId, e);
127
+ } else if (e.type === "turn.ended" && e.turnId) ended.set(e.turnId, e);
128
+ if (notices.has(e.type) && !turnEvents.has(e.type)) noticeEvents.push(e);
129
+ }
130
+ const newerStart = /* @__PURE__ */ new Set();
131
+ for (let i = 0; i < startOrder.length - 1; i++) newerStart.add(startOrder[i]?.turnId ?? "");
132
+ const calls = /* @__PURE__ */ new Map();
133
+ const results = /* @__PURE__ */ new Map();
134
+ for (const m of s.messages) {
135
+ if (m.kind === "tool_call" && !calls.has(m.toolCall.callId)) calls.set(m.toolCall.callId, m);
136
+ if (m.kind === "tool_result" && !results.has(m.toolResult.callId)) results.set(m.toolResult.callId, m);
137
+ }
138
+ const slots = [];
139
+ const turns = /* @__PURE__ */ new Map();
140
+ const turnIdOf = (m) => m.turnId ?? `turn-of-${m.id}`;
141
+ const turnStatus = (id) => {
142
+ const end = ended.get(id);
143
+ if (end) return end.turn.outcome;
144
+ if (s.turn?.id === id) return "running";
145
+ if (newerStart.has(id)) return "discarded";
146
+ return started.has(id) ? "running" : "completed";
147
+ };
148
+ const turnItem = (id, at, first) => {
149
+ let t = turns.get(id);
150
+ if (t) return t;
151
+ const start = started.get(id);
152
+ const end = ended.get(id);
153
+ t = {
154
+ kind: "turn",
155
+ id,
156
+ origin: start?.turn.origin ?? "harness",
157
+ attempt: start?.turn.attempt ?? 1,
158
+ status: turnStatus(id),
159
+ error: end?.turn.error ?? null,
160
+ ...retryOf(end),
161
+ startedAt: start?.createdAt ?? first?.createdAt ?? "",
162
+ endedAt: end?.createdAt ?? null,
163
+ usage: end?.turn.usage ?? null,
164
+ parts: []
165
+ };
166
+ turns.set(id, t);
167
+ slots.push({ item: t, seq: start?.seq ?? at, order: slots.length });
168
+ return t;
169
+ };
170
+ for (const e of startOrder) turnItem(e.turnId ?? "", e.seq, null);
171
+ for (const e of noticeEvents)
172
+ slots.push({ item: { kind: "notice", id: `notice-${e.seq}`, event: e }, seq: e.seq, order: slots.length });
173
+ const toolParts = /* @__PURE__ */ new Map();
174
+ const toolPart = (m) => {
175
+ const callId = m.kind === "tool_call" ? m.toolCall.callId : m.kind === "tool_result" ? m.toolResult.callId : "";
176
+ const call = m.kind === "tool_call" ? m.toolCall : null;
177
+ const paired = m.kind === "tool_call" && calls.get(callId) === m;
178
+ const result = m.kind === "tool_result" ? m.toolResult : paired ? results.get(callId)?.toolResult ?? null : null;
179
+ let status;
180
+ if (result) status = result.isError ? "error" : "done";
181
+ else status = turnStatus(turnIdOf(m)) === "running" ? "running" : "interrupted";
182
+ const part = { kind: "tool", id: m.id, callId, call, result, status, children: [] };
183
+ if (paired) toolParts.set(callId, part);
184
+ return part;
185
+ };
186
+ const placed = [];
187
+ for (const m of s.messages) {
188
+ if (m.kind === "user") {
189
+ if (m.seq === null) continue;
190
+ slots.push({
191
+ item: {
192
+ kind: "user",
193
+ id: m.id,
194
+ seq: m.seq,
195
+ createdAt: m.createdAt,
196
+ text: m.text,
197
+ author: m.author,
198
+ metadata: m.metadata ?? {},
199
+ delivery: delivery(m.seq, s)
200
+ },
201
+ seq: m.seq,
202
+ order: slots.length
203
+ });
204
+ continue;
205
+ }
206
+ if (m.kind === "tool_result" && calls.has(m.toolResult.callId) && results.get(m.toolResult.callId) === m) continue;
207
+ placed.push({ message: m, part: messagePart(m, toolPart) });
208
+ }
209
+ for (const { message: m, part } of placed) {
210
+ const parent = m.parentToolUseId ? toolParts.get(m.parentToolUseId) : void 0;
211
+ if (parent && parent !== part && !within(part, parent)) {
212
+ parent.children.push(part);
213
+ continue;
214
+ }
215
+ turnItem(turnIdOf(m), m.seq ?? Number.MAX_SAFE_INTEGER, m).parts.push(part);
216
+ }
217
+ slots.sort((a, b) => a.seq - b.seq || a.order - b.order);
218
+ return slots.map((x) => x.item);
219
+ }
220
+ function within(part, target) {
221
+ if (part.kind !== "tool") return false;
222
+ return part.children.some((c) => c === target || within(c, target));
223
+ }
224
+
225
+ // src/stable.ts
226
+ function keyOf(v) {
227
+ return typeof v === "object" && v !== null ? v.id : void 0;
228
+ }
229
+ function stable(prev, next) {
230
+ if (prev === next || prev === void 0) return next;
231
+ if (Array.isArray(prev) && Array.isArray(next)) {
232
+ const byId = /* @__PURE__ */ new Map();
233
+ for (const p of prev) {
234
+ const k = keyOf(p);
235
+ if (k !== void 0) byId.set(k, p);
236
+ }
237
+ let same = prev.length === next.length;
238
+ const out = next.map((n, i) => {
239
+ const k = keyOf(n);
240
+ const v = stable(k !== void 0 ? byId.get(k) : prev[i], n);
241
+ if (v !== prev[i]) same = false;
242
+ return v;
243
+ });
244
+ return same ? prev : out;
245
+ }
246
+ if (typeof prev === "object" && typeof next === "object" && prev !== null && next !== null) {
247
+ if (Array.isArray(prev) || Array.isArray(next)) return next;
248
+ const p = prev;
249
+ const n = next;
250
+ const keys = Object.keys(n);
251
+ let same = keys.length === Object.keys(p).length;
252
+ const out = {};
253
+ for (const k of keys) {
254
+ const v = stable(p[k], n[k]);
255
+ if (v !== p[k] || !(k in p)) same = false;
256
+ out[k] = v;
257
+ }
258
+ return same ? prev : out;
259
+ }
260
+ return next;
261
+ }
262
+
263
+ // src/status.ts
264
+ var import_client2 = require("@paddockai/client");
265
+ var stoppable = /* @__PURE__ */ new Set(["running", "retrying", "blocked"]);
266
+ function refused(s) {
267
+ const e = s.connectionError;
268
+ return s.connection === "closed" && import_client2.PaddockError.is(e) && (e.status === 401 || e.status === 403 || e.code === "unauthorized" || e.code === "forbidden");
269
+ }
270
+ function hasWaiting(s) {
271
+ const floor = Math.max(s.processedSeq, s.heldSeq);
272
+ return s.messages.some(
273
+ (m) => m.kind === "user" && m.seq !== null && m.seq > floor && !s.turn?.inputSeqs.includes(m.seq)
274
+ );
275
+ }
276
+ function sessionStatus(s, mode) {
277
+ const readOnly = mode === "read_only";
278
+ return {
279
+ status: s.status,
280
+ connected: s.connection === "open",
281
+ canSend: !readOnly && !refused(s),
282
+ canStop: !readOnly && (stoppable.has(s.status) || hasWaiting(s)),
283
+ readOnly
284
+ };
285
+ }
286
+
287
+ // src/tools.ts
288
+ var str = (o, k) => typeof o?.[k] === "string" ? o[k] : "";
289
+ var firstLine = (s) => s.split("\n").find((l) => l.trim() !== "") ?? "";
290
+ function textOf(output) {
291
+ if (!output) return null;
292
+ if (typeof output.text === "string") return output.text;
293
+ if (typeof output.content === "string") return output.content;
294
+ return null;
295
+ }
296
+ function resultOnly(base, output, text) {
297
+ const title = base.kind;
298
+ if (!output) return { ...base, title };
299
+ if (base.kind === "shell") {
300
+ const exitCode = typeof output.exitCode === "number" ? output.exitCode : null;
301
+ return { ...base, title, shell: { command: "", output: str(output, "output"), exitCode } };
302
+ }
303
+ if (base.kind === "mcp") {
304
+ const content = Array.isArray(output.content) ? output.content : null;
305
+ return { ...base, title, mcp: { server: "", tool: "", arguments: null, content } };
306
+ }
307
+ return text === null ? { ...base, title } : { ...base, title, text };
308
+ }
309
+ var changeKind = (k) => k === "add" || k === "delete" ? k : "update";
310
+ function toolSummary(part) {
311
+ const { call, result, status } = part;
312
+ const kind = call?.tool ?? result?.tool ?? "unknown";
313
+ const input = call?.input;
314
+ const output = result?.output;
315
+ const base = { kind, status, call, result };
316
+ const text = result ? textOf(output) : null;
317
+ if (!input) return resultOnly(base, output, text);
318
+ switch (kind) {
319
+ case "shell": {
320
+ const command = str(input, "command");
321
+ const description = str(input, "description");
322
+ const exitCode = typeof output?.exitCode === "number" ? output.exitCode : null;
323
+ return {
324
+ ...base,
325
+ title: description || `Run ${firstLine(command)}`,
326
+ shell: { command, output: result ? str(output, "output") : null, exitCode }
327
+ };
328
+ }
329
+ case "file_read":
330
+ return { ...base, title: `Read ${str(input, "path")}`, text };
331
+ case "file_write":
332
+ return {
333
+ ...base,
334
+ title: `Write ${str(input, "path")}`,
335
+ diff: [{ path: str(input, "path"), change: "add", unified: null, before: null, after: str(input, "content") }],
336
+ text
337
+ };
338
+ case "file_edit":
339
+ return {
340
+ ...base,
341
+ title: `Edit ${str(input, "path")}`,
342
+ diff: [
343
+ {
344
+ path: str(input, "path"),
345
+ change: "update",
346
+ unified: null,
347
+ before: str(input, "oldString"),
348
+ after: str(input, "newString")
349
+ }
350
+ ],
351
+ text
352
+ };
353
+ case "file_patch": {
354
+ const changes = Array.isArray(input?.changes) ? input.changes : [];
355
+ const diff = changes.map((c) => ({
356
+ path: str(c, "path"),
357
+ change: changeKind(str(c, "kind")),
358
+ unified: typeof c.diff === "string" ? c.diff : null,
359
+ before: null,
360
+ after: null
361
+ }));
362
+ const title = diff.length === 1 ? `Patch ${diff[0]?.path ?? ""}` : `Patch ${diff.length} files`;
363
+ return { ...base, title, diff, text };
364
+ }
365
+ case "glob":
366
+ return { ...base, title: `Find ${str(input, "pattern")}`, text };
367
+ case "grep":
368
+ return { ...base, title: `Search ${str(input, "pattern")}`, text };
369
+ case "web_fetch":
370
+ return { ...base, title: `Fetch ${str(input, "url")}`, text };
371
+ case "web_search":
372
+ return { ...base, title: `Search the web ${str(input, "query")}`, text };
373
+ case "mcp": {
374
+ const server = str(input, "server");
375
+ const tool = str(input, "tool");
376
+ const content = Array.isArray(output?.content) ? output.content : null;
377
+ return { ...base, title: `${server} \xB7 ${tool}`, mcp: { server, tool, arguments: input?.arguments, content } };
378
+ }
379
+ case "subagent":
380
+ return { ...base, title: str(input, "description") || call?.rawName || kind, text };
381
+ case "skill":
382
+ return { ...base, title: str(input, "name") || call?.rawName || kind, text };
383
+ default:
384
+ return { ...base, title: call?.rawName || kind };
385
+ }
386
+ }
387
+
388
+ // src/hooks.ts
389
+ function useConversation(session, options = {}) {
390
+ const { messages, events, turn, processedSeq, heldSeq } = session;
391
+ const noticeKey = (options.notices ?? []).join("\n");
392
+ const previous = (0, import_react2.useRef)(void 0);
393
+ return (0, import_react2.useMemo)(() => {
394
+ const notices = noticeKey ? noticeKey.split("\n") : [];
395
+ const next = stable(previous.current, conversation({ messages, events, turn, processedSeq, heldSeq }, { notices }));
396
+ previous.current = next;
397
+ return next;
398
+ }, [messages, events, turn, processedSeq, heldSeq, noticeKey]);
399
+ }
400
+ function useSessionStatus(session, options = {}) {
401
+ const { status, connection, connectionError, messages, turn, processedSeq, heldSeq } = session;
402
+ const mode = options.mode;
403
+ const previous = (0, import_react2.useRef)(void 0);
404
+ return (0, import_react2.useMemo)(() => {
405
+ const next = stable(
406
+ previous.current,
407
+ sessionStatus({ status, connection, connectionError, messages, turn, processedSeq, heldSeq }, mode)
408
+ );
409
+ previous.current = next;
410
+ return next;
411
+ }, [status, connection, connectionError, messages, turn, processedSeq, heldSeq, mode]);
412
+ }
413
+ function useToolCall(part) {
414
+ const { call, result, status } = part;
415
+ return (0, import_react2.useMemo)(() => toolSummary({ call, result, status }), [call, result, status]);
416
+ }
417
+ var asError = (e) => e instanceof Error ? e : new Error(String(e));
418
+ function useComposer(session, options = {}) {
419
+ const status = useSessionStatus(session, { mode: options.mode ?? null });
420
+ const [value, setValue] = (0, import_react2.useState)("");
421
+ const [pending, setPending] = (0, import_react2.useState)(false);
422
+ const [error, setError] = (0, import_react2.useState)(null);
423
+ const onError = (0, import_react2.useRef)(options.onError);
424
+ onError.current = options.onError;
425
+ const busy = (0, import_react2.useRef)(false);
426
+ const latest = (0, import_react2.useRef)(value);
427
+ latest.current = value;
428
+ const { send } = session;
429
+ const sessionStop = session.stop;
430
+ const text = value.trim();
431
+ const canSend = status.canSend && text !== "" && !pending;
432
+ const canStop = status.canStop;
433
+ const fail = (0, import_react2.useCallback)((e) => {
434
+ const err = asError(e);
435
+ setError(err);
436
+ onError.current?.(err);
437
+ }, []);
438
+ const submit = (0, import_react2.useCallback)(async () => {
439
+ const sent = latest.current.trim();
440
+ if (!canSend || busy.current || sent === "") return;
441
+ busy.current = true;
442
+ setPending(true);
443
+ setError(null);
444
+ try {
445
+ await send(sent);
446
+ setValue((v) => v.trim() === sent ? "" : v);
447
+ } catch (e) {
448
+ fail(e);
449
+ } finally {
450
+ busy.current = false;
451
+ setPending(false);
452
+ }
453
+ }, [canSend, send, fail]);
454
+ const stop = (0, import_react2.useCallback)(async () => {
455
+ if (!canStop) return;
456
+ try {
457
+ await sessionStop();
458
+ } catch (e) {
459
+ fail(e);
460
+ }
461
+ }, [canStop, sessionStop, fail]);
462
+ const inputProps = (0, import_react2.useMemo)(
463
+ () => ({
464
+ value,
465
+ onChange: (event) => setValue(event.target.value),
466
+ onKeyDown: (event) => {
467
+ if (event.key !== "Enter" || event.shiftKey || event.nativeEvent?.isComposing || event.keyCode === 229) return;
468
+ event.preventDefault();
469
+ void submit();
470
+ }
471
+ }),
472
+ [value, submit]
473
+ );
474
+ return { value, setValue, submit, stop, pending, error, canSend, canStop, inputProps };
475
+ }
476
+
477
+ // src/token.ts
478
+ var import_react3 = require("react");
479
+ var retryMs = 15e3;
480
+ var maxLeadMs = 5 * 6e4;
481
+ function useSessionToken(fetchToken) {
482
+ const fetcher = (0, import_react3.useRef)(fetchToken);
483
+ fetcher.current = fetchToken;
484
+ const [held, setHeld] = (0, import_react3.useState)(null);
485
+ const [expired, setExpired] = (0, import_react3.useState)(false);
486
+ const [error, setError] = (0, import_react3.useState)(null);
487
+ const [attempt, setAttempt] = (0, import_react3.useState)(0);
488
+ const run = (0, import_react3.useRef)(0);
489
+ const load = (0, import_react3.useCallback)(() => {
490
+ const id = ++run.current;
491
+ void (async () => {
492
+ try {
493
+ const t = await fetcher.current();
494
+ if (id !== run.current) return;
495
+ const expiry = Date.parse(t.expiresAt);
496
+ if (!(expiry > Date.now())) throw new Error(`paddock: the fetched token expired at ${t.expiresAt}`);
497
+ setHeld({ token: t.token, expiresAt: t.expiresAt, mode: t.mode, fetchedAt: Date.now() });
498
+ setExpired(false);
499
+ setError(null);
500
+ setAttempt(0);
501
+ } catch (e) {
502
+ if (id !== run.current) return;
503
+ setError(e instanceof Error ? e : new Error(String(e)));
504
+ setAttempt((n) => n + 1);
505
+ }
506
+ })();
507
+ }, []);
508
+ (0, import_react3.useEffect)(() => {
509
+ load();
510
+ return () => {
511
+ run.current++;
512
+ };
513
+ }, [load]);
514
+ (0, import_react3.useEffect)(() => {
515
+ if (attempt === 0) return;
516
+ const timer = setTimeout(load, retryMs);
517
+ return () => clearTimeout(timer);
518
+ }, [attempt, load]);
519
+ (0, import_react3.useEffect)(() => {
520
+ if (!held) return;
521
+ const expiry = Date.parse(held.expiresAt);
522
+ const lead = Math.min((expiry - held.fetchedAt) / 5, maxLeadMs);
523
+ const now = Date.now();
524
+ const refreshTimer = setTimeout(load, Math.max(0, expiry - lead - now));
525
+ const expiryTimer = setTimeout(() => setExpired(true), Math.max(0, expiry - now));
526
+ return () => {
527
+ clearTimeout(refreshTimer);
528
+ clearTimeout(expiryTimer);
529
+ };
530
+ }, [held, load]);
531
+ const live = held && !expired ? held : null;
532
+ return {
533
+ token: live?.token ?? null,
534
+ expiresAt: live?.expiresAt ?? null,
535
+ mode: live?.mode ?? null,
536
+ error,
537
+ refresh: load
538
+ };
539
+ }
56
540
  // Annotate the CommonJS export names for ESM import in node:
57
541
  0 && (module.exports = {
58
542
  PaddockProvider,
59
- useSession
543
+ useComposer,
544
+ useConversation,
545
+ useSession,
546
+ useSessionStatus,
547
+ useSessionToken,
548
+ useToolCall
60
549
  });