@parallelworks/code 0.1.0 → 0.2.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.
Files changed (70) hide show
  1. package/README.md +138 -24
  2. package/dist/api.d.ts +3469 -0
  3. package/dist/apiClient.d.ts +26 -0
  4. package/dist/apiClient.js +5 -0
  5. package/dist/claudeApi.d.ts +27 -0
  6. package/dist/claudeApi.js +250 -0
  7. package/dist/command.d.ts +47 -0
  8. package/dist/command.js +64 -0
  9. package/dist/commandsApi.d.ts +64 -0
  10. package/dist/commandsApi.js +267 -0
  11. package/dist/createPwCodeApi.d.ts +688 -0
  12. package/dist/createPwCodeApi.js +31 -0
  13. package/dist/index.d.ts +16 -3
  14. package/dist/index.js +16 -3
  15. package/dist/locales/en/agentTranscript.js +170 -0
  16. package/dist/locales/en/agents.js +380 -0
  17. package/dist/locales/en.d.ts +531 -0
  18. package/dist/locales/en.js +8 -0
  19. package/dist/locales/es/agentTranscript.js +170 -0
  20. package/dist/locales/es/agents.js +380 -0
  21. package/dist/locales/es.d.ts +3 -0
  22. package/dist/locales/es.js +8 -0
  23. package/dist/locales/ja/agentTranscript.js +170 -0
  24. package/dist/locales/ja/agents.js +380 -0
  25. package/dist/locales/ja.d.ts +3 -0
  26. package/dist/locales/ja.js +8 -0
  27. package/dist/locales/ko/agentTranscript.js +170 -0
  28. package/dist/locales/ko/agents.js +380 -0
  29. package/dist/locales/ko.d.ts +3 -0
  30. package/dist/locales/ko.js +8 -0
  31. package/dist/locales/zh/agentTranscript.js +170 -0
  32. package/dist/locales/zh/agents.js +380 -0
  33. package/dist/locales/zh.d.ts +3 -0
  34. package/dist/locales/zh.js +8 -0
  35. package/dist/machine.d.ts +49 -0
  36. package/dist/machine.js +60 -0
  37. package/dist/messages.d.ts +17 -0
  38. package/dist/messages.js +31 -0
  39. package/dist/notices.d.ts +11 -0
  40. package/dist/notices.js +94 -0
  41. package/dist/pullRequest.d.ts +8 -0
  42. package/dist/pullRequest.js +29 -0
  43. package/dist/query.d.ts +28 -0
  44. package/dist/query.js +25 -0
  45. package/dist/session.d.ts +70 -1
  46. package/dist/session.js +101 -1
  47. package/dist/sessionEvents.d.ts +27 -0
  48. package/dist/sessionEvents.js +212 -0
  49. package/dist/sessionsApi.d.ts +105 -0
  50. package/dist/sessionsApi.js +513 -0
  51. package/dist/toolStrings.d.ts +4 -0
  52. package/dist/toolStrings.js +95 -0
  53. package/dist/transcript.d.ts +12 -1
  54. package/dist/transcript.js +40 -2
  55. package/dist/types.d.ts +20 -1
  56. package/dist/useTranscript.d.ts +4 -1
  57. package/dist/useTranscript.js +54 -11
  58. package/dist/wording.d.ts +43 -0
  59. package/dist/wording.js +101 -0
  60. package/locales/en/agentTranscript.json +162 -0
  61. package/locales/en/agents.json +366 -0
  62. package/locales/es/agentTranscript.json +162 -0
  63. package/locales/es/agents.json +366 -0
  64. package/locales/ja/agentTranscript.json +162 -0
  65. package/locales/ja/agents.json +366 -0
  66. package/locales/ko/agentTranscript.json +162 -0
  67. package/locales/ko/agents.json +366 -0
  68. package/locales/zh/agentTranscript.json +162 -0
  69. package/locales/zh/agents.json +366 -0
  70. package/package.json +23 -8
@@ -0,0 +1,513 @@
1
+ import { createQuery } from "./query.js";
2
+ import { machinesById } from "./machine.js";
3
+ import { isSession, triageSessions } from "./session.js";
4
+ import { approvalAnswerBody } from "./transcript.js";
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
6
+ import { DateTime } from "luxon";
7
+ // src/sessionsApi.ts
8
+ var SESSIONS_REFRESH_MS = 5e3;
9
+ var WAITING_REFRESH_MS = 3e4;
10
+ var PULL_REQUESTS_REFRESH_MS = 6e4;
11
+ var CLOSED_PULL_REQUESTS_REFRESH_MS = 36e5;
12
+ var SUBAGENTS_REFRESH_MS = 1e3;
13
+ /** Whether a copy cached by an earlier visit still holds everything the
14
+ * session's listed row reports. A running session's copy trails its turn. */
15
+ function cachedCopyCurrent(listed, cached) {
16
+ return !!listed && listed.status !== "running" && listed.status === cached.status && listed.messages === cached.messages && listed.updatedAt === cached.updatedAt;
17
+ }
18
+ /** Whether this visit's own read has answered: a copy cached by an earlier
19
+ * visit has not, until the read started on mounting lands. */
20
+ function useReadThisVisit(data, isValidating, mutate) {
21
+ const [cachedCopy] = useState(data);
22
+ const cached = cachedCopy !== void 0;
23
+ const [refetched, setRefetched] = useState(false);
24
+ useEffect(() => {
25
+ if (cached) {
26
+ const done = () => setRefetched(true);
27
+ mutate().then(done, done);
28
+ }
29
+ }, [cached, mutate]);
30
+ const [answered, setAnswered] = useState(!cached);
31
+ if (!answered && refetched && (data !== cachedCopy || !isValidating)) setAnswered(true);
32
+ return answered;
33
+ }
34
+ /** Each session listed from `machine` that links a pull request in `read` takes its state, as the machine stores it for every one of them. */
35
+ function patchPullRequestStates(current, machine, read) {
36
+ if (!current?.sessions) return current;
37
+ let changed = false;
38
+ const sessions = current.sessions.map((s) => {
39
+ if (s.machineId !== machine) return s;
40
+ const states = {};
41
+ for (const { url, state } of read) if (state && s.pullRequests?.includes(url) && s.pullRequestStates?.[url] !== state) states[url] = state;
42
+ if (Object.keys(states).length === 0) return s;
43
+ changed = true;
44
+ return {
45
+ ...s,
46
+ pullRequestStates: {
47
+ ...s.pullRequestStates,
48
+ ...states
49
+ }
50
+ };
51
+ });
52
+ return changed ? {
53
+ ...current,
54
+ sessions
55
+ } : current;
56
+ }
57
+ /** Every minute while any of `urls` may still change or has no state yet, hourly once all are merged or closed, and never once all are merged. */
58
+ function pullRequestsRefreshMs(data, urls) {
59
+ const known = new Map((data?.pullRequests ?? []).map(({ url, state }) => [url, state]));
60
+ const states = urls.map((url) => known.get(url));
61
+ if (states.length === 0 || states.some((s) => s !== "merged" && s !== "closed")) return PULL_REQUESTS_REFRESH_MS;
62
+ return states.every((s) => s === "merged") ? 0 : CLOSED_PULL_REQUESTS_REFRESH_MS;
63
+ }
64
+ /** Runs `run` at once, then again once it settles and `ms` passed, however
65
+ * often it is asked: a read started over one in flight would discard it. */
66
+ function useThrottled(run, ms) {
67
+ const runRef = useRef(run);
68
+ runRef.current = run;
69
+ const timer = useRef(null);
70
+ const busy = useRef(false);
71
+ const asked = useRef(false);
72
+ useEffect(() => () => {
73
+ if (timer.current !== null) clearTimeout(timer.current);
74
+ }, []);
75
+ return useCallback(() => {
76
+ if (busy.current) {
77
+ asked.current = true;
78
+ return;
79
+ }
80
+ const go = () => {
81
+ busy.current = true;
82
+ const spaced = new Promise((resolve) => {
83
+ timer.current = setTimeout(resolve, ms);
84
+ });
85
+ Promise.allSettled([runRef.current(), spaced]).then(() => {
86
+ timer.current = null;
87
+ busy.current = false;
88
+ if (asked.current) {
89
+ asked.current = false;
90
+ go();
91
+ }
92
+ });
93
+ };
94
+ go();
95
+ }, [ms]);
96
+ }
97
+ /** When this client last read the session from its machine: its fetch, or the
98
+ * moment its open feed closed, since an open feed is still reading. */
99
+ function useLastReadAt(detail, feedOpen) {
100
+ const [at, setAt] = useState(null);
101
+ useEffect(() => {
102
+ if (detail) setAt(DateTime.now());
103
+ }, [detail]);
104
+ useEffect(() => {
105
+ if (!feedOpen) return;
106
+ return () => setAt(DateTime.now());
107
+ }, [feedOpen]);
108
+ return at;
109
+ }
110
+ function patchSessionNames(current, machine, id, names) {
111
+ const session = current?.sessions?.find((s) => isSession(s, machine, id));
112
+ if (!current || !session) return current;
113
+ const renamed = {
114
+ ...session,
115
+ ...names
116
+ };
117
+ if ((session.name ?? "") === (renamed.name ?? "") && (session.autoName ?? "") === (renamed.autoName ?? "")) return current;
118
+ return {
119
+ ...current,
120
+ sessions: (current.sessions ?? []).map((s) => s === session ? renamed : s)
121
+ };
122
+ }
123
+ /** The part of a paste a message names it by. */
124
+ function pasteRefs(pastes) {
125
+ return pastes?.length ? { pastes: pastes.map((p) => ({
126
+ placeholder: p.placeholder,
127
+ id: p.id
128
+ })) } : {};
129
+ }
130
+ function utf8ToBase64(text) {
131
+ const bytes = new TextEncoder().encode(text);
132
+ let binary = "";
133
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
134
+ return btoa(binary);
135
+ }
136
+ function sameSession(a, b) {
137
+ return isSession(a, b.machineId, b.id);
138
+ }
139
+ function sessionPath(s) {
140
+ return { params: { path: {
141
+ machine: s.machineId,
142
+ id: s.id
143
+ } } };
144
+ }
145
+ function sessionsApi(client) {
146
+ const useQuery = createQuery(client);
147
+ /** Every session on every machine the reader can reach, with each machine's reachability. */
148
+ function useSessions() {
149
+ return useQuery("/api/code/sessions", void 0, { refreshInterval: SESSIONS_REFRESH_MS });
150
+ }
151
+ /** Every listing asks each machine, so an app-wide count polls slower; the list's own poll keeps it current beside the list. */
152
+ function useWaitingSessionCount(enabled) {
153
+ const { data } = useQuery("/api/code/sessions", enabled ? void 0 : null, { refreshInterval: WAITING_REFRESH_MS });
154
+ return useMemo(() => data ? triageSessions(data.sessions ?? [], machinesById(data.machines ?? [])).blocked.length : 0, [data]);
155
+ }
156
+ /** `fresh` once this visit has fetched the session: a copy cached by an earlier
157
+ * visit trails the feed, and resuming from it replays everything since. It is
158
+ * not revalidated after that, which would reseed the live transcript mid-turn.
159
+ * A cached copy the listed row says the session has moved past stays hidden
160
+ * until that fetch answers, so the newer turns don't land under the reader. */
161
+ function useSessionDetail(machine, id, listed) {
162
+ const { data, error, isLoading, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}", { params: { path: {
163
+ machine,
164
+ id
165
+ } } }, {
166
+ revalidateIfStale: false,
167
+ revalidateOnFocus: false,
168
+ revalidateOnReconnect: false
169
+ });
170
+ const [current] = useState(() => data !== void 0 && cachedCopyCurrent(listed, data));
171
+ const answered = useReadThisVisit(data, isValidating, mutate);
172
+ const hidden = !current && !answered;
173
+ return {
174
+ data: hidden ? void 0 : data,
175
+ error,
176
+ isLoading: isLoading || hidden,
177
+ mutate,
178
+ fresh: data !== void 0 && answered
179
+ };
180
+ }
181
+ /** A query of its own, so a pull request merged while the session is open
182
+ * shows without revalidating the detail. */
183
+ function usePullRequests(machine, id, urls, onRead) {
184
+ const shown = urls.join(" ");
185
+ const refreshInterval = useCallback((latest) => pullRequestsRefreshMs(latest, shown ? shown.split(" ") : []), [shown]);
186
+ const query = useQuery("/api/code/machines/{machine}/sessions/{id}/pull-requests", shown ? { params: { path: {
187
+ machine,
188
+ id
189
+ } } } : null, {
190
+ refreshInterval,
191
+ onSuccess: (data) => onRead?.(data.pullRequests ?? [])
192
+ });
193
+ const { mutate } = query;
194
+ const asked = useRef(shown);
195
+ useEffect(() => {
196
+ if (asked.current && asked.current !== shown) mutate();
197
+ asked.current = shown;
198
+ }, [shown, mutate]);
199
+ return query;
200
+ }
201
+ /** A session's pull request states, as the sessions list has them so every
202
+ * view of the session agrees, or its own read where the list has none. Each
203
+ * read goes into the list at once. */
204
+ function useSessionPullRequestStates(machine, id, urls) {
205
+ const { data: list, mutate } = useSessions();
206
+ const { data } = usePullRequests(machine, id, urls, (read) => {
207
+ if (patchPullRequestStates(list, machine, read) !== list) mutate((current) => patchPullRequestStates(current, machine, read), { revalidate: false });
208
+ });
209
+ const listed = list?.sessions?.find((s) => isSession(s, machine, id))?.pullRequestStates;
210
+ const read = data?.pullRequests;
211
+ if (!listed && !read) return;
212
+ return urls.map((url) => ({
213
+ url,
214
+ state: listed?.[url] ?? read?.find((s) => s.url === url)?.state
215
+ }));
216
+ }
217
+ /** Read out of the polled listing: a per-machine query without a refresh
218
+ * interval would freeze at whatever it first loaded. */
219
+ function useMachine(machine) {
220
+ const { data, mutate } = useSessions();
221
+ return {
222
+ machine: useMemo(() => data?.machines?.find((m) => m.id === machine), [data, machine]),
223
+ recheck: useCallback(() => void mutate(), [mutate])
224
+ };
225
+ }
226
+ /** The session's subagents as its machine lists them: none for a session its
227
+ * daemon has not loaded, or from a pw code that does not say how each stands.
228
+ * The feed says when to ask again, so nothing polls. */
229
+ function useSubagents(machine, id, enabled) {
230
+ const { data, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}/subagents", enabled ? { params: { path: {
231
+ machine,
232
+ id
233
+ } } } : null, {
234
+ revalidateOnFocus: false,
235
+ shouldRetryOnError: false
236
+ });
237
+ return {
238
+ subagents: useMemo(() => {
239
+ const listed = data?.subagents ?? [];
240
+ return listed.every((s) => s.status) ? listed : [];
241
+ }, [data]),
242
+ refresh: useThrottled(() => mutate(), SUBAGENTS_REFRESH_MS)
243
+ };
244
+ }
245
+ /** A subagent's transcript, read again on every visit: a copy an earlier visit
246
+ * cached trails the session's feed, and seeding from it would drop what
247
+ * streamed since. */
248
+ function useSubagentDetail(machine, id, subId) {
249
+ const { data, error, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}", { params: { path: {
250
+ machine,
251
+ id,
252
+ subId
253
+ } } }, {
254
+ revalidateIfStale: false,
255
+ revalidateOnFocus: false,
256
+ revalidateOnReconnect: false,
257
+ shouldRetryOnError: false
258
+ });
259
+ const answered = useReadThisVisit(data, isValidating, mutate);
260
+ const refresh = useThrottled(() => mutate(), SUBAGENTS_REFRESH_MS);
261
+ return {
262
+ data: answered ? data : void 0,
263
+ error: answered ? error : void 0,
264
+ refresh
265
+ };
266
+ }
267
+ /** Each resolves to the machine's refusal, or what was thrown when it did not answer, or null once it took the stop. */
268
+ async function stopSubagent(machine, id, subId) {
269
+ try {
270
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/stop", { params: { path: {
271
+ machine,
272
+ id,
273
+ subId
274
+ } } });
275
+ return error ?? null;
276
+ } catch (thrown) {
277
+ return thrown;
278
+ }
279
+ }
280
+ async function stopAllSubagents(machine, id) {
281
+ try {
282
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/stop-all", { params: { path: {
283
+ machine,
284
+ id
285
+ } } });
286
+ return error ?? null;
287
+ } catch (thrown) {
288
+ return thrown;
289
+ }
290
+ }
291
+ function useSessionWorktree(s) {
292
+ return useQuery("/api/code/machines/{machine}/sessions/{id}/worktree", s ? sessionPath(s) : null);
293
+ }
294
+ /** Resolves to the machine's refusal, or what leaving did once it agreed. Given
295
+ * the root the reader saw, removes that worktree too. */
296
+ async function leaveWorktree(s, removeRoot) {
297
+ const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/worktree/leave", {
298
+ ...sessionPath(s),
299
+ body: removeRoot ? {
300
+ remove: true,
301
+ worktreeRoot: removeRoot
302
+ } : {}
303
+ });
304
+ return error ? { refusal: error } : { left: data };
305
+ }
306
+ /** Each resolves to the daemon's refusal, or null once the list is patched,
307
+ * which happens at once so the row does not linger until the next poll. */
308
+ function useSessionMutations() {
309
+ const { mutate } = useSessions();
310
+ const patched = useCallback(async (s, request, change) => {
311
+ const { error } = await request;
312
+ if (error) return error;
313
+ await mutate((current) => current && {
314
+ ...current,
315
+ sessions: (current.sessions ?? []).map((x) => sameSession(x, s) ? change(x) : x)
316
+ }, { revalidate: true });
317
+ return null;
318
+ }, [mutate]);
319
+ return {
320
+ deleteSession: useCallback(async (s, removeWorktree) => {
321
+ const { error } = await client.DELETE("/api/code/machines/{machine}/sessions/{id}", removeWorktree ? { params: {
322
+ ...sessionPath(s).params,
323
+ query: {
324
+ worktree: "remove",
325
+ worktreeRoot: removeWorktree
326
+ }
327
+ } } : sessionPath(s));
328
+ if (error) return error;
329
+ await mutate((current) => current && {
330
+ ...current,
331
+ sessions: (current.sessions ?? []).filter((x) => !sameSession(x, s))
332
+ }, { revalidate: true });
333
+ return null;
334
+ }, [mutate]),
335
+ renameSession: useCallback((s, name) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/rename", {
336
+ ...sessionPath(s),
337
+ body: { name }
338
+ }), (x) => ({
339
+ ...x,
340
+ name
341
+ })), [patched]),
342
+ archiveSession: useCallback((s) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), (x) => ({
343
+ ...x,
344
+ archivedAt: DateTime.now().toISO()
345
+ })), [patched]),
346
+ archiveAfterTurn: useCallback(async (s) => {
347
+ const response = await client.POST("/api/code/machines/{machine}/sessions/{id}/archive", {
348
+ ...sessionPath(s),
349
+ body: { afterTurn: true }
350
+ });
351
+ const deferred = response.data?.deferred === true;
352
+ return {
353
+ refusal: await patched(s, Promise.resolve(response), (x) => deferred ? x : {
354
+ ...x,
355
+ archivedAt: DateTime.now().toISO()
356
+ }),
357
+ deferred
358
+ };
359
+ }, [patched]),
360
+ restoreSession: useCallback((s) => patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), ({ archivedAt: _, ...x }) => x), [patched]),
361
+ pinSession: useCallback((s, pinned) => pinned ? patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), (x) => ({
362
+ ...x,
363
+ pinnedAt: DateTime.now().toISO()
364
+ })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), ({ pinnedAt: _, ...x }) => x), [patched]),
365
+ groupSession: useCallback((s, group) => group ? patched(s, client.PUT("/api/code/machines/{machine}/sessions/{id}/group", {
366
+ ...sessionPath(s),
367
+ body: { group }
368
+ }), (x) => ({
369
+ ...x,
370
+ group
371
+ })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/group", sessionPath(s)), ({ group: _, ...x }) => x), [patched]),
372
+ stopSession: useCallback((s) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/stop", sessionPath(s)), (x) => x), [patched]),
373
+ forkSession: useCallback(async (s) => {
374
+ const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/fork", sessionPath(s));
375
+ if (error) return { refusal: error };
376
+ await mutate();
377
+ return { forked: data };
378
+ }, [mutate])
379
+ };
380
+ }
381
+ /** Starts a session on the machine, sending `prompt` as its first message when the body has one. */
382
+ function createSession(machine, body) {
383
+ return client.POST("/api/code/machines/{machine}/sessions", {
384
+ params: { path: { machine } },
385
+ body
386
+ });
387
+ }
388
+ /** A message the session takes as its next turn, or queues behind the one running. */
389
+ function sendMessage(machine, id, body) {
390
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/messages", {
391
+ params: { path: {
392
+ machine,
393
+ id
394
+ } },
395
+ body
396
+ });
397
+ }
398
+ /** Hands text to the turn that is running. */
399
+ function steer(machine, id, body) {
400
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/direction", {
401
+ params: { path: {
402
+ machine,
403
+ id
404
+ } },
405
+ body
406
+ });
407
+ }
408
+ /** Takes back a message still queued behind the running turn. */
409
+ function withdrawQueued(machine, id, turnId) {
410
+ return client.DELETE("/api/code/machines/{machine}/sessions/{id}/queued/{turnId}", { params: { path: {
411
+ machine,
412
+ id,
413
+ turnId
414
+ } } });
415
+ }
416
+ function messageSubagent(machine, id, subId, body) {
417
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/messages", {
418
+ params: { path: {
419
+ machine,
420
+ id,
421
+ subId
422
+ } },
423
+ body
424
+ });
425
+ }
426
+ function steerSubagent(machine, id, subId, body) {
427
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/direction", {
428
+ params: { path: {
429
+ machine,
430
+ id,
431
+ subId
432
+ } },
433
+ body
434
+ });
435
+ }
436
+ /** Saves an image, base64-encoded, with the session; a message names it by
437
+ * the path this resolves to. */
438
+ function saveImage(machine, id, body) {
439
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/images", {
440
+ params: { path: {
441
+ machine,
442
+ id
443
+ } },
444
+ body
445
+ });
446
+ }
447
+ /** Resolves to the daemon's refusal, or null once the answer is accepted. */
448
+ async function answerApproval(machine, sessionId, approvalId, answer) {
449
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/approvals/{approvalId}", {
450
+ params: { path: {
451
+ machine,
452
+ id: sessionId,
453
+ approvalId
454
+ } },
455
+ body: approvalAnswerBody(answer)
456
+ });
457
+ return error ?? null;
458
+ }
459
+ /** Closes a directory added for this session only; resolves to the daemon's refusal, or null once it is closed. */
460
+ async function removeSessionDirectory(machine, sessionId, path) {
461
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/commands", {
462
+ params: { path: {
463
+ machine,
464
+ id: sessionId
465
+ } },
466
+ body: {
467
+ name: "permissions",
468
+ args: `remove dir "${path}"`
469
+ }
470
+ });
471
+ return error ?? null;
472
+ }
473
+ /** Saves a paste with the session on its machine. A machine whose pw code
474
+ * predates paste uploads answers 404, and the paste stays text. */
475
+ async function uploadPaste(machine, sessionId, text, describe) {
476
+ const { data, error, response } = await client.POST("/api/code/machines/{machine}/sessions/{id}/texts", {
477
+ params: { path: {
478
+ machine,
479
+ id: sessionId
480
+ } },
481
+ body: { data: utf8ToBase64(text) }
482
+ });
483
+ if (response.status === 404) return { unsupported: true };
484
+ if (error) return { error: describe(error) };
485
+ return { paste: data };
486
+ }
487
+ return {
488
+ useSessions,
489
+ useWaitingSessionCount,
490
+ useSessionDetail,
491
+ usePullRequests,
492
+ useSessionPullRequestStates,
493
+ useMachine,
494
+ useSubagents,
495
+ useSubagentDetail,
496
+ stopSubagent,
497
+ stopAllSubagents,
498
+ useSessionWorktree,
499
+ leaveWorktree,
500
+ useSessionMutations,
501
+ createSession,
502
+ sendMessage,
503
+ steer,
504
+ withdrawQueued,
505
+ messageSubagent,
506
+ steerSubagent,
507
+ saveImage,
508
+ answerApproval,
509
+ removeSessionDirectory,
510
+ uploadPaste
511
+ };
512
+ }
513
+ export { SESSIONS_REFRESH_MS, cachedCopyCurrent, pasteRefs, patchPullRequestStates, patchSessionNames, pullRequestsRefreshMs, sessionsApi, useLastReadAt };
@@ -0,0 +1,4 @@
1
+ import type { ToolStrings } from '@parallelworks/ui/ai/headless';
2
+ /** How a tool call's result is summed up, in the reader's language, for
3
+ * `toolSummary`, `rollupSentence` and the other tool formatters. */
4
+ export declare function useToolStrings(): ToolStrings;
@@ -0,0 +1,95 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { useMemo } from "react";
3
+ // src/toolStrings.ts
4
+ /** How a tool call's result is summed up, in the reader's language, for
5
+ * `toolSummary`, `rollupSentence` and the other tool formatters. */
6
+ function useToolStrings() {
7
+ const t = usePwCodeTranslations("agentTranscript");
8
+ return useMemo(() => ({
9
+ noOutput: t("tools.noOutput"),
10
+ firstLine: (line, more) => more > 0 ? t("tools.firstLineMore", {
11
+ line,
12
+ more
13
+ }) : line,
14
+ emptyFile: t("tools.emptyFile"),
15
+ readImage: t("tools.readImage"),
16
+ readLines: (lines, more) => more > 0 ? t("tools.readLinesMore", {
17
+ lines,
18
+ more
19
+ }) : t("tools.readLines", { lines }),
20
+ noMatches: t("tools.noMatches"),
21
+ foundMatches: (matches, files) => t("tools.foundMatches", {
22
+ matches,
23
+ files
24
+ }),
25
+ foundFiles: (files) => t("tools.foundFiles", { files }),
26
+ noFilesMatched: t("tools.noFilesMatched"),
27
+ truncated: (summary) => t("tools.truncated", { summary }),
28
+ exitCode: (code, lines) => lines > 0 ? t("tools.exitCodeLines", {
29
+ code,
30
+ lines
31
+ }) : t("tools.exitCode", { code }),
32
+ httpStatus: (status, lines) => t("tools.httpStatus", {
33
+ status,
34
+ lines
35
+ }),
36
+ outputTruncated: (summary) => t("tools.outputTruncated", { summary }),
37
+ edited: (added, removed) => {
38
+ if (added > 0 && removed > 0) return t("tools.addedRemoved", {
39
+ added,
40
+ removed
41
+ });
42
+ if (added > 0) return t("tools.added", { added });
43
+ return removed > 0 ? t("tools.removed", { removed }) : "";
44
+ },
45
+ rejected: (feedback) => feedback ? t("tools.rejectedWith", { feedback }) : t("tools.rejected"),
46
+ rejectedUpdate: (path, feedback) => feedback ? t("tools.rejectedUpdateWith", {
47
+ path,
48
+ feedback
49
+ }) : t("tools.rejectedUpdate", { path }),
50
+ rejectedWrite: (path, feedback) => feedback ? t("tools.rejectedWriteWith", {
51
+ path,
52
+ feedback
53
+ }) : t("tools.rejectedWrite", { path }),
54
+ unattended: t("tools.unattended"),
55
+ userInterrupted: (tool) => t("tools.userInterrupted", { tool }),
56
+ wrote: (lines, path) => path ? t("tools.wroteTo", {
57
+ lines,
58
+ path
59
+ }) : t("tools.wrote", { lines }),
60
+ rollup: {
61
+ searched: (count) => t("tools.rollupSearched", { count }),
62
+ read: (count) => t("tools.rollupRead", { count }),
63
+ ranCommands: (count) => t("tools.rollupRanCommands", { count }),
64
+ fetched: (count) => t("tools.rollupFetched", { count }),
65
+ loadedSkills: (count) => t("tools.rollupLoadedSkills", { count }),
66
+ sentMessages: (count) => t("tools.rollupSentMessages", { count }),
67
+ calledMcpTools: (count) => t("tools.rollupCalledMcpTools", { count }),
68
+ ranTools: (count) => t("tools.rollupRanTools", { count }),
69
+ sentence: (clauses) => {
70
+ const s = clauses.join(t("tools.rollupSeparator"));
71
+ return s.charAt(0).toLocaleUpperCase() + s.slice(1);
72
+ }
73
+ },
74
+ rollupActive: {
75
+ searching: (count) => t("tools.rollupSearching", { count }),
76
+ reading: (count) => t("tools.rollupReading", { count }),
77
+ runningCommands: (count) => t("tools.rollupRunningCommands", { count }),
78
+ fetching: (count) => t("tools.rollupFetching", { count }),
79
+ loadingSkills: (count) => t("tools.rollupLoadingSkills", { count }),
80
+ sendingMessages: (count) => t("tools.rollupSendingMessages", { count }),
81
+ runningTools: (count) => t("tools.rollupRunningTools", { count })
82
+ },
83
+ rollupServer: {
84
+ called: (server, count) => t("tools.rollupCalledServer", {
85
+ server,
86
+ count
87
+ }),
88
+ calling: (server, count) => t("tools.rollupCallingServer", {
89
+ server,
90
+ count
91
+ })
92
+ }
93
+ }), [t]);
94
+ }
95
+ export { useToolStrings };
@@ -1,5 +1,5 @@
1
1
  import { type ApprovalAnswerValue, type ApprovalPart, type ChatMessage, type MessagePart, type MessagePaste, type SubagentNotice, type TodoItem, type ToolDecision } from '@parallelworks/ui/ai/headless';
2
- import type { PwCodeAllowedDirectory, PwCodeApprovalAnswer, PwCodeApprovalRequest, PwCodeGoalStatus, PwCodeHistoryItem, PwCodeImage, PwCodeSessionDetail, PwCodeSessionState, PwCodeSessionStatus, PwCodeGoalProgress, PwCodeStreamEvent, PwCodeToolDecision, PwCodeTurnEnd } from './types.js';
2
+ import type { PwCodeAllowedDirectory, PwCodeApprovalAnswer, PwCodeApprovalRequest, PwCodeGoalStatus, PwCodeHistoryItem, PwCodeImage, PwCodeSessionDetail, PwCodeSessionState, PwCodeSessionStatus, PwCodeGoalProgress, PwCodeStreamEvent, PwCodeSubagentDetail, PwCodeToolDecision, PwCodeTurnEnd } from './types.js';
3
3
  export interface TranscriptState {
4
4
  messages: ChatMessage[];
5
5
  streaming: ChatMessage | null;
@@ -65,6 +65,14 @@ export declare function initialTranscript(detail: PwCodeSessionDetail, options?:
65
65
  words?: TranscriptWords | undefined;
66
66
  imageUrl?: ImageUrl | undefined;
67
67
  }): TranscriptState;
68
+ /** A subagent's detail as the session detail its transcript seeds from. Its run
69
+ * has no turn id on the wire, so its own id names the one in flight. */
70
+ export declare function subagentSessionDetail(sub: PwCodeSubagentDetail): PwCodeSessionDetail;
71
+ /** A session frame as one subagent's transcript reads it. A turn someone
72
+ * prompted on the subagent streams under its id, and a note it was handed
73
+ * arrives as its own event; the task it was given streams nothing, so a frame
74
+ * that only says it moved on is `refetch`. Null is a frame for someone else. */
75
+ export declare function subagentFrame(ev: PwCodeStreamEvent, id: string): PwCodeStreamEvent | 'refetch' | null;
68
76
  /** The approvals the live feed is still waiting on. */
69
77
  export declare function pendingApprovals(transcript: TranscriptState): ApprovalPart[];
70
78
  /** Status as the live feed shows it; `detail.status` is only the fetch moment. */
@@ -74,6 +82,9 @@ export declare function resolveApprovalEverywhere(state: TranscriptState, id: st
74
82
  * short, so the page must not close the turn either: its open tool calls
75
83
  * would read as interrupted while they are still running. */
76
84
  export declare function appendOwnMessage(state: TranscriptState, text: string, id?: string, pastes?: MessagePaste[], previews?: PwCodeImage[]): TranscriptState;
85
+ /** A subagent runs one turn at a time, so a message sent to it starts its next:
86
+ * a turn the transcript still shows running has ended. */
87
+ export declare function appendTurnMessage(state: TranscriptState, text: string, id?: string, pastes?: MessagePaste[], previews?: PwCodeImage[]): TranscriptState;
77
88
  /** Held apart until the daemon reports the model was handed it. */
78
89
  export declare function appendSteeredMessage(state: TranscriptState, text: string, id?: string, pastes?: MessagePaste[], previews?: PwCodeImage[]): TranscriptState;
79
90
  /** The daemon queued a message this page had shown as sent, because the turn