@parallelworks/code 0.1.0 → 0.3.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 (118) hide show
  1. package/README.md +171 -24
  2. package/dist/ago.d.ts +8 -0
  3. package/dist/ago.js +26 -0
  4. package/dist/api.d.ts +3547 -0
  5. package/dist/apiClient.d.ts +26 -0
  6. package/dist/apiClient.js +5 -0
  7. package/dist/base64.d.ts +3 -0
  8. package/dist/base64.js +15 -0
  9. package/dist/chatHandoff.d.ts +12 -0
  10. package/dist/chatHandoff.js +27 -0
  11. package/dist/claudeAccounts.d.ts +112 -0
  12. package/dist/claudeAccounts.js +234 -0
  13. package/dist/claudeApi.d.ts +27 -0
  14. package/dist/claudeApi.js +250 -0
  15. package/dist/claudeSignIn.d.ts +62 -0
  16. package/dist/claudeSignIn.js +239 -0
  17. package/dist/command.d.ts +47 -0
  18. package/dist/command.js +64 -0
  19. package/dist/commandsApi.d.ts +64 -0
  20. package/dist/commandsApi.js +267 -0
  21. package/dist/contextRow.d.ts +25 -0
  22. package/dist/contextRow.js +16 -0
  23. package/dist/createPwCodeApi.d.ts +696 -0
  24. package/dist/createPwCodeApi.js +33 -0
  25. package/dist/howSessionsAppear.d.ts +12 -0
  26. package/dist/howSessionsAppear.js +24 -0
  27. package/dist/index.d.ts +39 -3
  28. package/dist/index.js +38 -3
  29. package/dist/locales/en/agentTranscript.js +162 -0
  30. package/dist/locales/en/agents.js +380 -0
  31. package/dist/locales/en.d.ts +523 -0
  32. package/dist/locales/en.js +8 -0
  33. package/dist/locales/es/agentTranscript.js +162 -0
  34. package/dist/locales/es/agents.js +380 -0
  35. package/dist/locales/es.d.ts +3 -0
  36. package/dist/locales/es.js +8 -0
  37. package/dist/locales/ja/agentTranscript.js +162 -0
  38. package/dist/locales/ja/agents.js +380 -0
  39. package/dist/locales/ja.d.ts +3 -0
  40. package/dist/locales/ja.js +8 -0
  41. package/dist/locales/ko/agentTranscript.js +162 -0
  42. package/dist/locales/ko/agents.js +380 -0
  43. package/dist/locales/ko.d.ts +3 -0
  44. package/dist/locales/ko.js +8 -0
  45. package/dist/locales/zh/agentTranscript.js +162 -0
  46. package/dist/locales/zh/agents.js +380 -0
  47. package/dist/locales/zh.d.ts +3 -0
  48. package/dist/locales/zh.js +8 -0
  49. package/dist/machine.d.ts +51 -0
  50. package/dist/machine.js +60 -0
  51. package/dist/messages.d.ts +17 -0
  52. package/dist/messages.js +31 -0
  53. package/dist/models.d.ts +47 -0
  54. package/dist/models.js +49 -0
  55. package/dist/notices.d.ts +12 -0
  56. package/dist/notices.js +120 -0
  57. package/dist/pullRequest.d.ts +8 -0
  58. package/dist/pullRequest.js +29 -0
  59. package/dist/pullRequestList.d.ts +52 -0
  60. package/dist/pullRequestList.js +106 -0
  61. package/dist/query.d.ts +28 -0
  62. package/dist/query.js +25 -0
  63. package/dist/session.d.ts +75 -1
  64. package/dist/session.js +101 -1
  65. package/dist/sessionActions.d.ts +105 -0
  66. package/dist/sessionActions.js +178 -0
  67. package/dist/sessionEvents.d.ts +27 -0
  68. package/dist/sessionEvents.js +212 -0
  69. package/dist/sessionGroups.d.ts +49 -0
  70. package/dist/sessionGroups.js +72 -0
  71. package/dist/sessionHeader.d.ts +14 -0
  72. package/dist/sessionHeader.js +16 -0
  73. package/dist/sessionList.d.ts +134 -0
  74. package/dist/sessionList.js +271 -0
  75. package/dist/sessionsApi.d.ts +105 -0
  76. package/dist/sessionsApi.js +511 -0
  77. package/dist/settingsApi.d.ts +36 -0
  78. package/dist/settingsApi.js +151 -0
  79. package/dist/startSession.d.ts +138 -0
  80. package/dist/startSession.js +234 -0
  81. package/dist/terminalHandoffPanel.d.ts +30 -0
  82. package/dist/terminalHandoffPanel.js +33 -0
  83. package/dist/toolStrings.d.ts +4 -0
  84. package/dist/toolStrings.js +95 -0
  85. package/dist/transcript.d.ts +14 -1
  86. package/dist/transcript.js +55 -14
  87. package/dist/types.d.ts +20 -1
  88. package/dist/usageLimit.d.ts +8 -0
  89. package/dist/usageLimit.js +13 -0
  90. package/dist/useAwayRecap.d.ts +30 -0
  91. package/dist/useAwayRecap.js +75 -0
  92. package/dist/useComposer.d.ts +121 -0
  93. package/dist/useComposer.js +244 -0
  94. package/dist/useComposerImages.d.ts +66 -0
  95. package/dist/useComposerImages.js +195 -0
  96. package/dist/useConversation.d.ts +190 -0
  97. package/dist/useConversation.js +287 -0
  98. package/dist/useSubagent.d.ts +58 -0
  99. package/dist/useSubagent.js +149 -0
  100. package/dist/useTranscript.d.ts +4 -1
  101. package/dist/useTranscript.js +54 -11
  102. package/dist/wording.d.ts +43 -0
  103. package/dist/wording.js +101 -0
  104. package/dist/workingDirectories.d.ts +32 -0
  105. package/dist/workingDirectories.js +71 -0
  106. package/dist/worktreeChoice.d.ts +31 -0
  107. package/dist/worktreeChoice.js +38 -0
  108. package/locales/en/agentTranscript.json +154 -0
  109. package/locales/en/agents.json +366 -0
  110. package/locales/es/agentTranscript.json +154 -0
  111. package/locales/es/agents.json +366 -0
  112. package/locales/ja/agentTranscript.json +154 -0
  113. package/locales/ja/agents.json +366 -0
  114. package/locales/ko/agentTranscript.json +154 -0
  115. package/locales/ko/agents.json +366 -0
  116. package/locales/zh/agentTranscript.json +154 -0
  117. package/locales/zh/agents.json +366 -0
  118. package/package.json +24 -9
@@ -0,0 +1,511 @@
1
+ import { bytesToBase64 } from "./base64.js";
2
+ import { createQuery } from "./query.js";
3
+ import { machinesById } from "./machine.js";
4
+ import { isSession, triageSessions } from "./session.js";
5
+ import { approvalAnswerBody } from "./transcript.js";
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
+ import { DateTime } from "luxon";
8
+ // src/sessionsApi.ts
9
+ var SESSIONS_REFRESH_MS = 5e3;
10
+ var WAITING_REFRESH_MS = 3e4;
11
+ var PULL_REQUESTS_REFRESH_MS = 6e4;
12
+ var CLOSED_PULL_REQUESTS_REFRESH_MS = 36e5;
13
+ var SUBAGENTS_REFRESH_MS = 1e3;
14
+ /** Whether a copy cached by an earlier visit still holds everything the
15
+ * session's listed row reports. A running session's copy trails its turn. */
16
+ function cachedCopyCurrent(listed, cached) {
17
+ return !!listed && listed.status !== "running" && listed.status === cached.status && listed.messages === cached.messages && listed.updatedAt === cached.updatedAt;
18
+ }
19
+ /** Whether this visit's own read has answered: a copy cached by an earlier
20
+ * visit has not, until the read started on mounting lands. */
21
+ function useReadThisVisit(data, isValidating, mutate) {
22
+ const [cachedCopy] = useState(data);
23
+ const cached = cachedCopy !== void 0;
24
+ const [refetched, setRefetched] = useState(false);
25
+ useEffect(() => {
26
+ if (cached) {
27
+ const done = () => setRefetched(true);
28
+ mutate().then(done, done);
29
+ }
30
+ }, [cached, mutate]);
31
+ const [answered, setAnswered] = useState(!cached);
32
+ if (!answered && refetched && (data !== cachedCopy || !isValidating)) setAnswered(true);
33
+ return answered;
34
+ }
35
+ /** 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. */
36
+ function patchPullRequestStates(current, machine, read) {
37
+ if (!current?.sessions) return current;
38
+ let changed = false;
39
+ const sessions = current.sessions.map((s) => {
40
+ if (s.machineId !== machine) return s;
41
+ const states = {};
42
+ for (const { url, state } of read) if (state && s.pullRequests?.includes(url) && s.pullRequestStates?.[url] !== state) states[url] = state;
43
+ if (Object.keys(states).length === 0) return s;
44
+ changed = true;
45
+ return {
46
+ ...s,
47
+ pullRequestStates: {
48
+ ...s.pullRequestStates,
49
+ ...states
50
+ }
51
+ };
52
+ });
53
+ return changed ? {
54
+ ...current,
55
+ sessions
56
+ } : current;
57
+ }
58
+ /** 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. */
59
+ function pullRequestsRefreshMs(data, urls) {
60
+ const known = new Map((data?.pullRequests ?? []).map(({ url, state }) => [url, state]));
61
+ const states = urls.map((url) => known.get(url));
62
+ if (states.length === 0 || states.some((s) => s !== "merged" && s !== "closed")) return PULL_REQUESTS_REFRESH_MS;
63
+ return states.every((s) => s === "merged") ? 0 : CLOSED_PULL_REQUESTS_REFRESH_MS;
64
+ }
65
+ /** Runs `run` at once, then again once it settles and `ms` passed, however
66
+ * often it is asked: a read started over one in flight would discard it. */
67
+ function useThrottled(run, ms) {
68
+ const runRef = useRef(run);
69
+ runRef.current = run;
70
+ const timer = useRef(null);
71
+ const busy = useRef(false);
72
+ const asked = useRef(false);
73
+ useEffect(() => () => {
74
+ if (timer.current !== null) clearTimeout(timer.current);
75
+ }, []);
76
+ return useCallback(() => {
77
+ if (busy.current) {
78
+ asked.current = true;
79
+ return;
80
+ }
81
+ const go = () => {
82
+ busy.current = true;
83
+ const spaced = new Promise((resolve) => {
84
+ timer.current = setTimeout(resolve, ms);
85
+ });
86
+ Promise.allSettled([runRef.current(), spaced]).then(() => {
87
+ timer.current = null;
88
+ busy.current = false;
89
+ if (asked.current) {
90
+ asked.current = false;
91
+ go();
92
+ }
93
+ });
94
+ };
95
+ go();
96
+ }, [ms]);
97
+ }
98
+ /** When this client last read the session from its machine: its fetch, or the
99
+ * moment its open feed closed, since an open feed is still reading. */
100
+ function useLastReadAt(detail, feedOpen) {
101
+ const [at, setAt] = useState(null);
102
+ useEffect(() => {
103
+ if (detail) setAt(DateTime.now());
104
+ }, [detail]);
105
+ useEffect(() => {
106
+ if (!feedOpen) return;
107
+ return () => setAt(DateTime.now());
108
+ }, [feedOpen]);
109
+ return at;
110
+ }
111
+ function patchSessionNames(current, machine, id, names) {
112
+ const session = current?.sessions?.find((s) => isSession(s, machine, id));
113
+ if (!current || !session) return current;
114
+ const renamed = {
115
+ ...session,
116
+ ...names
117
+ };
118
+ if ((session.name ?? "") === (renamed.name ?? "") && (session.autoName ?? "") === (renamed.autoName ?? "")) return current;
119
+ return {
120
+ ...current,
121
+ sessions: (current.sessions ?? []).map((s) => s === session ? renamed : s)
122
+ };
123
+ }
124
+ /** The part of a paste a message names it by. */
125
+ function pasteRefs(pastes) {
126
+ return pastes?.length ? { pastes: pastes.map((p) => ({
127
+ placeholder: p.placeholder,
128
+ id: p.id
129
+ })) } : {};
130
+ }
131
+ function utf8ToBase64(text) {
132
+ return bytesToBase64(new TextEncoder().encode(text));
133
+ }
134
+ function sameSession(a, b) {
135
+ return isSession(a, b.machineId, b.id);
136
+ }
137
+ function sessionPath(s) {
138
+ return { params: { path: {
139
+ machine: s.machineId,
140
+ id: s.id
141
+ } } };
142
+ }
143
+ function sessionsApi(client) {
144
+ const useQuery = createQuery(client);
145
+ /** Every session on every machine the reader can reach, with each machine's reachability. */
146
+ function useSessions() {
147
+ return useQuery("/api/code/sessions", void 0, { refreshInterval: SESSIONS_REFRESH_MS });
148
+ }
149
+ /** Every listing asks each machine, so an app-wide count polls slower; the list's own poll keeps it current beside the list. */
150
+ function useWaitingSessionCount(enabled) {
151
+ const { data } = useQuery("/api/code/sessions", enabled ? void 0 : null, { refreshInterval: WAITING_REFRESH_MS });
152
+ return useMemo(() => data ? triageSessions(data.sessions ?? [], machinesById(data.machines ?? [])).blocked.length : 0, [data]);
153
+ }
154
+ /** `fresh` once this visit has fetched the session: a copy cached by an earlier
155
+ * visit trails the feed, and resuming from it replays everything since. It is
156
+ * not revalidated after that, which would reseed the live transcript mid-turn.
157
+ * A cached copy the listed row says the session has moved past stays hidden
158
+ * until that fetch answers, so the newer turns don't land under the reader. */
159
+ function useSessionDetail(machine, id, listed) {
160
+ const { data, error, isLoading, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}", { params: { path: {
161
+ machine,
162
+ id
163
+ } } }, {
164
+ revalidateIfStale: false,
165
+ revalidateOnFocus: false,
166
+ revalidateOnReconnect: false
167
+ });
168
+ const [current] = useState(() => data !== void 0 && cachedCopyCurrent(listed, data));
169
+ const answered = useReadThisVisit(data, isValidating, mutate);
170
+ const hidden = !current && !answered;
171
+ return {
172
+ data: hidden ? void 0 : data,
173
+ error,
174
+ isLoading: isLoading || hidden,
175
+ mutate,
176
+ fresh: data !== void 0 && answered
177
+ };
178
+ }
179
+ /** A query of its own, so a pull request merged while the session is open
180
+ * shows without revalidating the detail. */
181
+ function usePullRequests(machine, id, urls, onRead) {
182
+ const shown = urls.join(" ");
183
+ const refreshInterval = useCallback((latest) => pullRequestsRefreshMs(latest, shown ? shown.split(" ") : []), [shown]);
184
+ const query = useQuery("/api/code/machines/{machine}/sessions/{id}/pull-requests", shown ? { params: { path: {
185
+ machine,
186
+ id
187
+ } } } : null, {
188
+ refreshInterval,
189
+ onSuccess: (data) => onRead?.(data.pullRequests ?? [])
190
+ });
191
+ const { mutate } = query;
192
+ const asked = useRef(shown);
193
+ useEffect(() => {
194
+ if (asked.current && asked.current !== shown) mutate();
195
+ asked.current = shown;
196
+ }, [shown, mutate]);
197
+ return query;
198
+ }
199
+ /** A session's pull request states, as the sessions list has them so every
200
+ * view of the session agrees, or its own read where the list has none. Each
201
+ * read goes into the list at once. */
202
+ function useSessionPullRequestStates(machine, id, urls) {
203
+ const { data: list, mutate } = useSessions();
204
+ const { data } = usePullRequests(machine, id, urls, (read) => {
205
+ if (patchPullRequestStates(list, machine, read) !== list) mutate((current) => patchPullRequestStates(current, machine, read), { revalidate: false });
206
+ });
207
+ const listed = list?.sessions?.find((s) => isSession(s, machine, id))?.pullRequestStates;
208
+ const read = data?.pullRequests;
209
+ if (!listed && !read) return;
210
+ return urls.map((url) => ({
211
+ url,
212
+ state: listed?.[url] ?? read?.find((s) => s.url === url)?.state
213
+ }));
214
+ }
215
+ /** Read out of the polled listing: a per-machine query without a refresh
216
+ * interval would freeze at whatever it first loaded. */
217
+ function useMachine(machine) {
218
+ const { data, mutate } = useSessions();
219
+ return {
220
+ machine: useMemo(() => data?.machines?.find((m) => m.id === machine), [data, machine]),
221
+ recheck: useCallback(() => void mutate(), [mutate])
222
+ };
223
+ }
224
+ /** The session's subagents as its machine lists them: none for a session its
225
+ * daemon has not loaded, or from a pw code that does not say how each stands.
226
+ * The feed says when to ask again, so nothing polls. */
227
+ function useSubagents(machine, id, enabled) {
228
+ const { data, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}/subagents", enabled ? { params: { path: {
229
+ machine,
230
+ id
231
+ } } } : null, {
232
+ revalidateOnFocus: false,
233
+ shouldRetryOnError: false
234
+ });
235
+ return {
236
+ subagents: useMemo(() => {
237
+ const listed = data?.subagents ?? [];
238
+ return listed.every((s) => s.status) ? listed : [];
239
+ }, [data]),
240
+ refresh: useThrottled(() => mutate(), SUBAGENTS_REFRESH_MS)
241
+ };
242
+ }
243
+ /** A subagent's transcript, read again on every visit: a copy an earlier visit
244
+ * cached trails the session's feed, and seeding from it would drop what
245
+ * streamed since. */
246
+ function useSubagentDetail(machine, id, subId) {
247
+ const { data, error, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}", { params: { path: {
248
+ machine,
249
+ id,
250
+ subId
251
+ } } }, {
252
+ revalidateIfStale: false,
253
+ revalidateOnFocus: false,
254
+ revalidateOnReconnect: false,
255
+ shouldRetryOnError: false
256
+ });
257
+ const answered = useReadThisVisit(data, isValidating, mutate);
258
+ const refresh = useThrottled(() => mutate(), SUBAGENTS_REFRESH_MS);
259
+ return {
260
+ data: answered ? data : void 0,
261
+ error: answered ? error : void 0,
262
+ refresh
263
+ };
264
+ }
265
+ /** Each resolves to the machine's refusal, or what was thrown when it did not answer, or null once it took the stop. */
266
+ async function stopSubagent(machine, id, subId) {
267
+ try {
268
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/stop", { params: { path: {
269
+ machine,
270
+ id,
271
+ subId
272
+ } } });
273
+ return error ?? null;
274
+ } catch (thrown) {
275
+ return thrown;
276
+ }
277
+ }
278
+ async function stopAllSubagents(machine, id) {
279
+ try {
280
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/stop-all", { params: { path: {
281
+ machine,
282
+ id
283
+ } } });
284
+ return error ?? null;
285
+ } catch (thrown) {
286
+ return thrown;
287
+ }
288
+ }
289
+ function useSessionWorktree(s) {
290
+ return useQuery("/api/code/machines/{machine}/sessions/{id}/worktree", s ? sessionPath(s) : null);
291
+ }
292
+ /** Resolves to the machine's refusal, or what leaving did once it agreed. Given
293
+ * the root the reader saw, removes that worktree too. */
294
+ async function leaveWorktree(s, removeRoot) {
295
+ const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/worktree/leave", {
296
+ ...sessionPath(s),
297
+ body: removeRoot ? {
298
+ remove: true,
299
+ worktreeRoot: removeRoot
300
+ } : {}
301
+ });
302
+ return error ? { refusal: error } : { left: data };
303
+ }
304
+ /** Each resolves to the daemon's refusal, or null once the list is patched,
305
+ * which happens at once so the row does not linger until the next poll. */
306
+ function useSessionMutations() {
307
+ const { mutate } = useSessions();
308
+ const patched = useCallback(async (s, request, change) => {
309
+ const { error } = await request;
310
+ if (error) return error;
311
+ await mutate((current) => current && {
312
+ ...current,
313
+ sessions: (current.sessions ?? []).map((x) => sameSession(x, s) ? change(x) : x)
314
+ }, { revalidate: true });
315
+ return null;
316
+ }, [mutate]);
317
+ return {
318
+ deleteSession: useCallback(async (s, removeWorktree) => {
319
+ const { error } = await client.DELETE("/api/code/machines/{machine}/sessions/{id}", removeWorktree ? { params: {
320
+ ...sessionPath(s).params,
321
+ query: {
322
+ worktree: "remove",
323
+ worktreeRoot: removeWorktree
324
+ }
325
+ } } : sessionPath(s));
326
+ if (error) return error;
327
+ await mutate((current) => current && {
328
+ ...current,
329
+ sessions: (current.sessions ?? []).filter((x) => !sameSession(x, s))
330
+ }, { revalidate: true });
331
+ return null;
332
+ }, [mutate]),
333
+ renameSession: useCallback((s, name) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/rename", {
334
+ ...sessionPath(s),
335
+ body: { name }
336
+ }), (x) => ({
337
+ ...x,
338
+ name
339
+ })), [patched]),
340
+ archiveSession: useCallback((s) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), (x) => ({
341
+ ...x,
342
+ archivedAt: DateTime.now().toISO()
343
+ })), [patched]),
344
+ archiveAfterTurn: useCallback(async (s) => {
345
+ const response = await client.POST("/api/code/machines/{machine}/sessions/{id}/archive", {
346
+ ...sessionPath(s),
347
+ body: { afterTurn: true }
348
+ });
349
+ const deferred = response.data?.deferred === true;
350
+ return {
351
+ refusal: await patched(s, Promise.resolve(response), (x) => deferred ? x : {
352
+ ...x,
353
+ archivedAt: DateTime.now().toISO()
354
+ }),
355
+ deferred
356
+ };
357
+ }, [patched]),
358
+ restoreSession: useCallback((s) => patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), ({ archivedAt: _, ...x }) => x), [patched]),
359
+ pinSession: useCallback((s, pinned) => pinned ? patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), (x) => ({
360
+ ...x,
361
+ pinnedAt: DateTime.now().toISO()
362
+ })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), ({ pinnedAt: _, ...x }) => x), [patched]),
363
+ groupSession: useCallback((s, group) => group ? patched(s, client.PUT("/api/code/machines/{machine}/sessions/{id}/group", {
364
+ ...sessionPath(s),
365
+ body: { group }
366
+ }), (x) => ({
367
+ ...x,
368
+ group
369
+ })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/group", sessionPath(s)), ({ group: _, ...x }) => x), [patched]),
370
+ stopSession: useCallback((s) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/stop", sessionPath(s)), (x) => x), [patched]),
371
+ forkSession: useCallback(async (s) => {
372
+ const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/fork", sessionPath(s));
373
+ if (error) return { refusal: error };
374
+ await mutate();
375
+ return { forked: data };
376
+ }, [mutate])
377
+ };
378
+ }
379
+ /** Starts a session on the machine, sending `prompt` as its first message when the body has one. */
380
+ function createSession(machine, body) {
381
+ return client.POST("/api/code/machines/{machine}/sessions", {
382
+ params: { path: { machine } },
383
+ body
384
+ });
385
+ }
386
+ /** A message the session takes as its next turn, or queues behind the one running. */
387
+ function sendMessage(machine, id, body) {
388
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/messages", {
389
+ params: { path: {
390
+ machine,
391
+ id
392
+ } },
393
+ body
394
+ });
395
+ }
396
+ /** Hands text to the turn that is running. */
397
+ function steer(machine, id, body) {
398
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/direction", {
399
+ params: { path: {
400
+ machine,
401
+ id
402
+ } },
403
+ body
404
+ });
405
+ }
406
+ /** Takes back a message still queued behind the running turn. */
407
+ function withdrawQueued(machine, id, turnId) {
408
+ return client.DELETE("/api/code/machines/{machine}/sessions/{id}/queued/{turnId}", { params: { path: {
409
+ machine,
410
+ id,
411
+ turnId
412
+ } } });
413
+ }
414
+ function messageSubagent(machine, id, subId, body) {
415
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/messages", {
416
+ params: { path: {
417
+ machine,
418
+ id,
419
+ subId
420
+ } },
421
+ body
422
+ });
423
+ }
424
+ function steerSubagent(machine, id, subId, body) {
425
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/direction", {
426
+ params: { path: {
427
+ machine,
428
+ id,
429
+ subId
430
+ } },
431
+ body
432
+ });
433
+ }
434
+ /** Saves an image, base64-encoded, with the session; a message names it by
435
+ * the path this resolves to. */
436
+ function saveImage(machine, id, body) {
437
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/images", {
438
+ params: { path: {
439
+ machine,
440
+ id
441
+ } },
442
+ body
443
+ });
444
+ }
445
+ /** Resolves to the daemon's refusal, or null once the answer is accepted. */
446
+ async function answerApproval(machine, sessionId, approvalId, answer) {
447
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/approvals/{approvalId}", {
448
+ params: { path: {
449
+ machine,
450
+ id: sessionId,
451
+ approvalId
452
+ } },
453
+ body: approvalAnswerBody(answer)
454
+ });
455
+ return error ?? null;
456
+ }
457
+ /** Closes a directory added for this session only; resolves to the daemon's refusal, or null once it is closed. */
458
+ async function removeSessionDirectory(machine, sessionId, path) {
459
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/commands", {
460
+ params: { path: {
461
+ machine,
462
+ id: sessionId
463
+ } },
464
+ body: {
465
+ name: "permissions",
466
+ args: `remove dir "${path}"`
467
+ }
468
+ });
469
+ return error ?? null;
470
+ }
471
+ /** Saves a paste with the session on its machine. A machine whose pw code
472
+ * predates paste uploads answers 404, and the paste stays text. */
473
+ async function uploadPaste(machine, sessionId, text, describe) {
474
+ const { data, error, response } = await client.POST("/api/code/machines/{machine}/sessions/{id}/texts", {
475
+ params: { path: {
476
+ machine,
477
+ id: sessionId
478
+ } },
479
+ body: { data: utf8ToBase64(text) }
480
+ });
481
+ if (response.status === 404) return { unsupported: true };
482
+ if (error) return { error: describe(error) };
483
+ return { paste: data };
484
+ }
485
+ return {
486
+ useSessions,
487
+ useWaitingSessionCount,
488
+ useSessionDetail,
489
+ usePullRequests,
490
+ useSessionPullRequestStates,
491
+ useMachine,
492
+ useSubagents,
493
+ useSubagentDetail,
494
+ stopSubagent,
495
+ stopAllSubagents,
496
+ useSessionWorktree,
497
+ leaveWorktree,
498
+ useSessionMutations,
499
+ createSession,
500
+ sendMessage,
501
+ steer,
502
+ withdrawQueued,
503
+ messageSubagent,
504
+ steerSubagent,
505
+ saveImage,
506
+ answerApproval,
507
+ removeSessionDirectory,
508
+ uploadPaste
509
+ };
510
+ }
511
+ export { SESSIONS_REFRESH_MS, cachedCopyCurrent, pasteRefs, patchPullRequestStates, patchSessionNames, pullRequestsRefreshMs, sessionsApi, useLastReadAt };
@@ -0,0 +1,36 @@
1
+ import type { BoundSetting, PermissionMode } from '@parallelworks/ui/ai/headless';
2
+ import type { PwCodeClient, PwCodeResult, Schemas } from './apiClient.js';
3
+ type SettingsBody = Schemas['AgentSessionSettingsBody'];
4
+ export interface PwCodeSessionSettingsOptions {
5
+ machine: string;
6
+ sessionId: string;
7
+ model: string | undefined;
8
+ effort?: string | undefined;
9
+ allocation: string | undefined;
10
+ claudeAccount?: string | undefined;
11
+ /** Billed by a switch to a model the platform bills, while the session has had no allocation of its own. */
12
+ nativeAllocation?: string | null | undefined;
13
+ locked: boolean;
14
+ live: boolean;
15
+ onPatched: () => void;
16
+ onError: (error: unknown) => void;
17
+ /** Called as a mode is picked, before the machine answers. */
18
+ onModePicked?: ((mode: PermissionMode) => void) | undefined;
19
+ /** Called as an effort level is picked, before the machine answers. */
20
+ onEffortPicked?: ((effort: string) => void) | undefined;
21
+ /** Called once the machine takes an account; it refuses one it cannot use, such as one signed out. */
22
+ onAccountSaved?: ((account: string) => void) | undefined;
23
+ }
24
+ export interface PwCodeSessionSettings {
25
+ model: BoundSetting;
26
+ effort: BoundSetting;
27
+ allocation: BoundSetting;
28
+ account: BoundSetting;
29
+ setMode: (mode: PermissionMode) => void;
30
+ saving: boolean;
31
+ }
32
+ export declare function settingsApi(client: PwCodeClient): {
33
+ updateSessionSettings: (machine: string, id: string, body: SettingsBody) => Promise<PwCodeResult<Schemas['SessionState']>>;
34
+ useSessionSettings: ({ machine, sessionId, model, effort, allocation, claudeAccount, nativeAllocation, locked, live, onPatched, onError, onModePicked, onEffortPicked, onAccountSaved, }: PwCodeSessionSettingsOptions) => PwCodeSessionSettings;
35
+ };
36
+ export {};
@@ -0,0 +1,151 @@
1
+ import { useCallback, useRef, useState } from "react";
2
+ // src/settingsApi.ts
3
+ var isClaude = (model) => !!model?.startsWith("claude-code/");
4
+ function settingsApi(client) {
5
+ /** Changes what a live session runs as, answering with its new state. */
6
+ function updateSessionSettings(machine, id, body) {
7
+ return client.PATCH("/api/code/machines/{machine}/sessions/{id}/settings", {
8
+ params: { path: {
9
+ machine,
10
+ id
11
+ } },
12
+ body
13
+ });
14
+ }
15
+ /** The session's own model, effort, allocation, account and permission
16
+ * mode, for pickers that show and change them. A pick shows at once and
17
+ * goes back if the machine refuses it. A session that cannot take a change
18
+ * (not live yet, or unreachable) shows its pickers disabled rather than
19
+ * dropping a pick. */
20
+ function useSessionSettings({ machine, sessionId, model, effort, allocation, claudeAccount, nativeAllocation, locked, live, onPatched, onError, onModePicked, onEffortPicked, onAccountSaved }) {
21
+ const [inFlight, setInFlight] = useState(0);
22
+ const saving = inFlight > 0;
23
+ const platformAllocation = useRef(allocation || "");
24
+ if (!isClaude(model) && allocation) platformAllocation.current = allocation;
25
+ const [picked, setPicked] = useState(null);
26
+ const reported = [
27
+ model,
28
+ effort,
29
+ allocation,
30
+ claudeAccount
31
+ ].join("|");
32
+ const pick = picked?.over === reported ? picked : null;
33
+ const pickNext = (change) => setPicked((previous) => ({
34
+ ...previous?.over === reported ? previous : {},
35
+ ...change,
36
+ over: reported
37
+ }));
38
+ const patch = useCallback(async (body) => {
39
+ setInFlight((count) => count + 1);
40
+ let error;
41
+ try {
42
+ error = (await updateSessionSettings(machine, sessionId, body)).error;
43
+ } catch (thrown) {
44
+ error = thrown;
45
+ }
46
+ setInFlight((count) => count - 1);
47
+ if (error) {
48
+ setPicked(null);
49
+ onError(error);
50
+ return false;
51
+ }
52
+ onPatched();
53
+ return true;
54
+ }, [
55
+ machine,
56
+ sessionId,
57
+ onError,
58
+ onPatched
59
+ ]);
60
+ const shownModel = pick?.model ?? model;
61
+ const shownAllocation = pick?.allocation ?? allocation;
62
+ const disabled = !live || locked || saving;
63
+ const modelSetting = {
64
+ value: shownModel,
65
+ disabled,
66
+ onChange: (next) => {
67
+ const nextAllocation = isClaude(next) ? "" : shownAllocation || platformAllocation.current || nativeAllocation || "";
68
+ pickNext({
69
+ model: next,
70
+ allocation: nextAllocation
71
+ });
72
+ patch({
73
+ model: next,
74
+ ...nextAllocation || isClaude(next) ? { allocation: nextAllocation } : {}
75
+ });
76
+ }
77
+ };
78
+ const allocationSetting = {
79
+ value: shownAllocation,
80
+ disabled,
81
+ onChange: (next) => {
82
+ if (!shownModel) return;
83
+ pickNext({
84
+ model: shownModel,
85
+ allocation: next
86
+ });
87
+ patch({
88
+ model: shownModel,
89
+ allocation: next
90
+ });
91
+ }
92
+ };
93
+ const effortQueue = useRef({
94
+ sending: false,
95
+ next: null
96
+ });
97
+ const [sendingEffort, setSendingEffort] = useState(null);
98
+ const sendEffort = async (level) => {
99
+ const queue = effortQueue.current;
100
+ queue.next = level;
101
+ if (queue.sending) return;
102
+ queue.sending = true;
103
+ try {
104
+ while (queue.next !== null) {
105
+ const sending = queue.next;
106
+ queue.next = null;
107
+ await patch({ effort: sending });
108
+ }
109
+ } finally {
110
+ queue.sending = false;
111
+ setSendingEffort(null);
112
+ }
113
+ };
114
+ const effortSetting = {
115
+ value: sendingEffort ?? pick?.effort ?? effort ?? "",
116
+ disabled: !live || locked,
117
+ onChange: (next) => {
118
+ pickNext({ effort: next });
119
+ setSendingEffort(next);
120
+ onEffortPicked?.(next);
121
+ sendEffort(next);
122
+ }
123
+ };
124
+ const setMode = useCallback((mode) => {
125
+ onModePicked?.(mode);
126
+ patch({ permissionMode: mode });
127
+ }, [patch, onModePicked]);
128
+ return {
129
+ model: modelSetting,
130
+ effort: effortSetting,
131
+ allocation: allocationSetting,
132
+ account: {
133
+ value: pick?.claudeAccount ?? claudeAccount,
134
+ disabled,
135
+ onChange: (next) => {
136
+ pickNext({ claudeAccount: next });
137
+ patch({ claudeAccount: next }).then((saved) => {
138
+ if (saved) onAccountSaved?.(next);
139
+ });
140
+ }
141
+ },
142
+ setMode,
143
+ saving
144
+ };
145
+ }
146
+ return {
147
+ updateSessionSettings,
148
+ useSessionSettings
149
+ };
150
+ }
151
+ export { settingsApi };