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