@parallelworks/code 0.2.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 (83) hide show
  1. package/README.md +43 -10
  2. package/dist/ago.d.ts +8 -0
  3. package/dist/ago.js +26 -0
  4. package/dist/api.d.ts +78 -0
  5. package/dist/base64.d.ts +3 -0
  6. package/dist/base64.js +15 -0
  7. package/dist/chatHandoff.d.ts +12 -0
  8. package/dist/chatHandoff.js +27 -0
  9. package/dist/claudeAccounts.d.ts +112 -0
  10. package/dist/claudeAccounts.js +234 -0
  11. package/dist/claudeSignIn.d.ts +62 -0
  12. package/dist/claudeSignIn.js +239 -0
  13. package/dist/contextRow.d.ts +25 -0
  14. package/dist/contextRow.js +16 -0
  15. package/dist/createPwCodeApi.d.ts +8 -0
  16. package/dist/createPwCodeApi.js +2 -0
  17. package/dist/howSessionsAppear.d.ts +12 -0
  18. package/dist/howSessionsAppear.js +24 -0
  19. package/dist/index.d.ts +24 -1
  20. package/dist/index.js +24 -2
  21. package/dist/locales/en/agentTranscript.js +2 -10
  22. package/dist/locales/en/agents.js +5 -5
  23. package/dist/locales/en.d.ts +5 -13
  24. package/dist/locales/es/agentTranscript.js +2 -10
  25. package/dist/locales/es/agents.js +5 -5
  26. package/dist/locales/ja/agentTranscript.js +2 -10
  27. package/dist/locales/ja/agents.js +5 -5
  28. package/dist/locales/ko/agentTranscript.js +2 -10
  29. package/dist/locales/ko/agents.js +5 -5
  30. package/dist/locales/zh/agentTranscript.js +2 -10
  31. package/dist/locales/zh/agents.js +5 -5
  32. package/dist/machine.d.ts +2 -0
  33. package/dist/models.d.ts +47 -0
  34. package/dist/models.js +49 -0
  35. package/dist/notices.d.ts +2 -1
  36. package/dist/notices.js +29 -3
  37. package/dist/pullRequestList.d.ts +52 -0
  38. package/dist/pullRequestList.js +106 -0
  39. package/dist/session.d.ts +5 -0
  40. package/dist/sessionActions.d.ts +105 -0
  41. package/dist/sessionActions.js +178 -0
  42. package/dist/sessionGroups.d.ts +49 -0
  43. package/dist/sessionGroups.js +72 -0
  44. package/dist/sessionHeader.d.ts +14 -0
  45. package/dist/sessionHeader.js +16 -0
  46. package/dist/sessionList.d.ts +134 -0
  47. package/dist/sessionList.js +271 -0
  48. package/dist/sessionsApi.js +2 -4
  49. package/dist/settingsApi.d.ts +36 -0
  50. package/dist/settingsApi.js +151 -0
  51. package/dist/startSession.d.ts +138 -0
  52. package/dist/startSession.js +234 -0
  53. package/dist/terminalHandoffPanel.d.ts +30 -0
  54. package/dist/terminalHandoffPanel.js +33 -0
  55. package/dist/transcript.d.ts +2 -0
  56. package/dist/transcript.js +15 -12
  57. package/dist/usageLimit.d.ts +8 -0
  58. package/dist/usageLimit.js +13 -0
  59. package/dist/useAwayRecap.d.ts +30 -0
  60. package/dist/useAwayRecap.js +75 -0
  61. package/dist/useComposer.d.ts +121 -0
  62. package/dist/useComposer.js +244 -0
  63. package/dist/useComposerImages.d.ts +66 -0
  64. package/dist/useComposerImages.js +195 -0
  65. package/dist/useConversation.d.ts +190 -0
  66. package/dist/useConversation.js +287 -0
  67. package/dist/useSubagent.d.ts +58 -0
  68. package/dist/useSubagent.js +149 -0
  69. package/dist/workingDirectories.d.ts +32 -0
  70. package/dist/workingDirectories.js +71 -0
  71. package/dist/worktreeChoice.d.ts +31 -0
  72. package/dist/worktreeChoice.js +38 -0
  73. package/locales/en/agentTranscript.json +2 -10
  74. package/locales/en/agents.json +5 -5
  75. package/locales/es/agentTranscript.json +2 -10
  76. package/locales/es/agents.json +5 -5
  77. package/locales/ja/agentTranscript.json +2 -10
  78. package/locales/ja/agents.json +5 -5
  79. package/locales/ko/agentTranscript.json +2 -10
  80. package/locales/ko/agents.json +5 -5
  81. package/locales/zh/agentTranscript.json +2 -10
  82. package/locales/zh/agents.json +5 -5
  83. package/package.json +3 -3
@@ -0,0 +1,244 @@
1
+ import { shellCommand } from "./command.js";
2
+ import { isMachineDown } from "./machine.js";
3
+ import { usePwCodeTranslations } from "./messages.js";
4
+ import { bashRunning, liveSessionStatus, pendingApprovals, turnRunning } from "./transcript.js";
5
+ import { composerState, sessionLabel } from "./wording.js";
6
+ import { useCallback, useEffect, useRef, useState } from "react";
7
+ // src/useComposer.ts
8
+ /** Per person, since someone else can sign in where the history is kept, and
9
+ * without `/auth`, which can carry a key. */
10
+ function promptHistory(username) {
11
+ return {
12
+ name: `agents:${username}`,
13
+ skip: (text) => /^\/auth(\s|$)/.test(text)
14
+ };
15
+ }
16
+ function useCommandOutputs() {
17
+ const [outputs, setOutputs] = useState([]);
18
+ const seq = useRef(0);
19
+ return {
20
+ outputs,
21
+ add: useCallback((command, text) => {
22
+ seq.current += 1;
23
+ const id = seq.current;
24
+ setOutputs((prev) => [...prev, {
25
+ id,
26
+ command,
27
+ text
28
+ }]);
29
+ }, []),
30
+ dismiss: useCallback((id) => setOutputs((prev) => prev.filter((o) => o.id !== id)), []),
31
+ clear: useCallback(() => setOutputs([]), [])
32
+ };
33
+ }
34
+ /** What the reader can do from an open session's composer, and how the
35
+ * session stands for it: what is typed goes out as a message, a direction to
36
+ * the running turn, a command or a `!` shell run, and the composer locks
37
+ * while the machine is unreachable, the session is archived or live
38
+ * elsewhere, or it waits on an approval. */
39
+ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo, feed, staleFor, images, handleLocally, notify, onCleared, onArchived }) {
40
+ const t = usePwCodeTranslations("agents");
41
+ const { session, detail, transcript, goal, sending, refetch, warn, showError, reached, deliver, noteShellRun } = conversation;
42
+ const [shellRun, setShellRun] = useState(null);
43
+ const delivering = useRef(null);
44
+ const { palette, loading: paletteLoading, load: loadPalette } = api.usePalette(machine, sessionId);
45
+ const openPalette = useCallback(() => void loadPalette().catch(() => {}), [loadPalette]);
46
+ const commandOutputs = useCommandOutputs();
47
+ const running = turnRunning(transcript);
48
+ const checkingGoal = !!goal?.checking;
49
+ const onShellRun = useCallback((command, output, stop) => {
50
+ commandOutputs.clear();
51
+ noteShellRun(command, output);
52
+ if (stop) warn(t("detail.shellStopped", { reason: stop }));
53
+ }, [
54
+ commandOutputs.clear,
55
+ noteShellRun,
56
+ t,
57
+ warn
58
+ ]);
59
+ const { archiveSession, archiveAfterTurn, stopSession } = api.useSessionMutations();
60
+ /** Resolves to the machine's refusal. A session archived once its turn ends stays open, and the machine says so in the transcript. */
61
+ const archiveTyped = useCallback(async (s, waits) => {
62
+ const { refusal, deferred } = waits ? await archiveAfterTurn(s) : {
63
+ refusal: await archiveSession(s),
64
+ deferred: false
65
+ };
66
+ if (!refusal && !deferred) {
67
+ notify(t("detail.archived", { name: sessionLabel(s, t) }));
68
+ onArchived();
69
+ }
70
+ return refusal;
71
+ }, [
72
+ archiveAfterTurn,
73
+ archiveSession,
74
+ notify,
75
+ onArchived,
76
+ t
77
+ ]);
78
+ const takeImages = images?.take;
79
+ const send = useCallback(async (typed, pastes) => {
80
+ const command = shellCommand(typed);
81
+ if (command && running) {
82
+ warn(t("detail.shellWhileRunning"));
83
+ return false;
84
+ }
85
+ if (handleLocally?.(typed)) return true;
86
+ if (command) setShellRun(command);
87
+ let refused = false;
88
+ const refuse = (error) => {
89
+ refused = true;
90
+ showError(error);
91
+ };
92
+ const text = await api.resolveTyped(typed, {
93
+ machine,
94
+ sessionId,
95
+ palette,
96
+ loadPalette,
97
+ planOnMachine: (path) => t("detail.planOnMachine", { path }),
98
+ onOutput: commandOutputs.add,
99
+ onShellRun,
100
+ onCompacted: () => void refetch(),
101
+ onCleared,
102
+ onArchive: async () => {
103
+ const waits = machineInfo?.archiveAfterTurn === true;
104
+ if (running && !waits) {
105
+ refused = true;
106
+ warn(t("detail.archiveWhileRunning"));
107
+ return;
108
+ }
109
+ const refusal = session && await archiveTyped(session, waits);
110
+ if (refusal) refuse(refusal);
111
+ },
112
+ onRefused: refuse
113
+ }).catch((error) => {
114
+ refuse(error);
115
+ return null;
116
+ }).finally(() => setShellRun(null));
117
+ if (text === null) return !refused;
118
+ commandOutputs.clear();
119
+ const { saved, settle } = takeImages ? await takeImages() : {
120
+ saved: [],
121
+ settle: () => {}
122
+ };
123
+ const refs = saved.map((i) => i.ref);
124
+ const message = [text, ...refs.map((i) => i.placeholder).filter((p) => !text.includes(p))].filter(Boolean).join(" ");
125
+ const delivery = deliver(message, {
126
+ steer: text === typed,
127
+ pastes,
128
+ images: refs,
129
+ previews: saved.map((i) => i.preview)
130
+ });
131
+ delivering.current = delivery;
132
+ const refusal = await delivery;
133
+ settle(!refusal);
134
+ if (refusal) warn(refusal.text, refusal.unreachable);
135
+ else reached();
136
+ return !refusal;
137
+ }, [
138
+ api,
139
+ archiveTyped,
140
+ commandOutputs.add,
141
+ commandOutputs.clear,
142
+ deliver,
143
+ handleLocally,
144
+ loadPalette,
145
+ machine,
146
+ machineInfo?.archiveAfterTurn,
147
+ onCleared,
148
+ onShellRun,
149
+ palette,
150
+ reached,
151
+ refetch,
152
+ running,
153
+ session,
154
+ sessionId,
155
+ showError,
156
+ t,
157
+ takeImages,
158
+ warn
159
+ ]);
160
+ const [stopping, setStopping] = useState(false);
161
+ const stop = useCallback(async () => {
162
+ if (!session) return;
163
+ setStopping(true);
164
+ await delivering.current;
165
+ const refusal = await stopSession(session);
166
+ setStopping(false);
167
+ if (refusal) showError(refusal);
168
+ }, [
169
+ showError,
170
+ session,
171
+ stopSession
172
+ ]);
173
+ const status = detail ? liveSessionStatus(detail.status, transcript, goal) : null;
174
+ const approvals = transcript ? pendingApprovals(transcript).map((p) => ({ kind: p.approvalKind })) : detail?.approvals;
175
+ const unreachable = isMachineDown(machineInfo) && !feed.connected;
176
+ const liveElsewhere = status === "live_elsewhere";
177
+ const reconnecting = !!detail && feed.disconnected && !unreachable && !liveElsewhere;
178
+ const archived = !!session?.archivedAt;
179
+ const machineName = machineInfo?.name ?? machine;
180
+ useEffect(() => {
181
+ if (!unreachable && !feed.disconnected) reached();
182
+ }, [
183
+ unreachable,
184
+ feed.disconnected,
185
+ reached
186
+ ]);
187
+ const working = status === "running" && !unreachable;
188
+ const background = api.useBackgroundCommands({
189
+ machine,
190
+ sessionId,
191
+ running: working && bashRunning(transcript),
192
+ onError: showError
193
+ });
194
+ const state = composerState({
195
+ unreachable,
196
+ archived,
197
+ machineName,
198
+ staleFor,
199
+ status,
200
+ liveHost: detail?.liveHost,
201
+ approvals,
202
+ shellRun: shellRun ?? void 0,
203
+ t
204
+ });
205
+ return {
206
+ /** Sends what was typed; false hands it back to the composer. */
207
+ send,
208
+ turn: {
209
+ running: (running || checkingGoal) && !unreachable,
210
+ stop,
211
+ stopping
212
+ },
213
+ composer: {
214
+ ...state,
215
+ disabled: sending || !!images?.taking || state.locked
216
+ },
217
+ /** Why nothing can be sent to the session at all, which a subagent's composer shows too. */
218
+ sessionLock: unreachable || archived || liveElsewhere ? state : null,
219
+ shellRun,
220
+ outputs: commandOutputs.outputs,
221
+ dismissOutput: commandOutputs.dismiss,
222
+ palette,
223
+ paletteLoading,
224
+ /** Opens the command menu, which asks for the session's palette again. */
225
+ openPalette,
226
+ loadPalette,
227
+ status,
228
+ approvals,
229
+ unreachable,
230
+ reconnecting,
231
+ archived,
232
+ machineName,
233
+ /** A turn is under way on a machine that answers. */
234
+ working,
235
+ checkingGoal,
236
+ /** The session rests between turns and can be reached. */
237
+ idle: status === "idle" && !unreachable && !archived && !feed.disconnected,
238
+ /** Ends the transcript while the machine cannot be reached. */
239
+ endNote: unreachable ? t("detail.transcriptEnds", { machine: machineName }) : void 0,
240
+ /** The offer to move the Bash commands the turn waits on to the background. */
241
+ background
242
+ };
243
+ }
244
+ export { promptHistory, useCommandOutputs, usePwCodeComposer };
@@ -0,0 +1,66 @@
1
+ import type { PwCodeApi } from './createPwCodeApi.js';
2
+ import type { PwCodeImage, PwCodeImageRef } from './types.js';
3
+ export type PwCodeImageType = PwCodeImageRef['mime'];
4
+ export declare const IMAGE_TYPES: readonly PwCodeImageType[];
5
+ export declare const IMAGE_MAX_BYTES: number;
6
+ export declare const IMAGE_MAX_SIDE = 8000;
7
+ /** The terminal refuses to read an image file past this, rather than decode it. */
8
+ export declare const IMAGE_READ_MAX_BYTES: number;
9
+ /** Thrown by a host's `encode` for an image it cannot fit within `IMAGE_MAX_BYTES`. */
10
+ export declare class PwCodeImageTooLarge extends Error {
11
+ }
12
+ /** An image a reader picked, as the host holds it: its type and size are read before anything else. */
13
+ export interface PwCodeImageFile {
14
+ readonly type: string;
15
+ readonly size: number;
16
+ }
17
+ export interface PwCodeComposerImage {
18
+ key: string;
19
+ placeholder: string;
20
+ previewUrl: string;
21
+ saved: boolean;
22
+ }
23
+ /** The ref goes to the machine; the preview stays with the reader, so it never rides in a request. */
24
+ export interface PwCodeSavedImage {
25
+ ref: PwCodeImageRef;
26
+ preview: PwCodeImage;
27
+ }
28
+ export interface PwCodeTakenImages {
29
+ saved: PwCodeSavedImage[];
30
+ settle: (sent: boolean) => void;
31
+ }
32
+ /** Numbers past every placeholder the texts name, as the terminal does. */
33
+ export declare function nextImageSeq(texts: Iterable<string | null | undefined> | undefined, after: number): number;
34
+ /** Images stay with the reader until there is a session to save them with. */
35
+ export declare function useComposerImages<F extends PwCodeImageFile>({ api, machine, sessionId, messages, onError, describeError, encode, preview, release, }: {
36
+ api: Pick<PwCodeApi, 'saveImage'>;
37
+ machine?: string | undefined;
38
+ sessionId?: string | undefined;
39
+ /** The live transcript: the fetched history misses what the terminal sent since. */
40
+ messages: readonly {
41
+ content?: string | null | undefined;
42
+ }[] | undefined;
43
+ onError: (text: string) => void;
44
+ /** Words a refusal or failure for the reader. */
45
+ describeError: (error: unknown) => string;
46
+ /** Base64 of the image fitted within `IMAGE_MAX_BYTES` and `IMAGE_MAX_SIDE`,
47
+ * in the type it was written in. Throws `PwCodeImageTooLarge` for one that
48
+ * will not fit. */
49
+ encode: (file: F, type: PwCodeImageType) => Promise<{
50
+ data: string;
51
+ mime: PwCodeImageType;
52
+ }>;
53
+ /** A URL the host draws the image from until `release` frees it. */
54
+ preview: (file: F) => string;
55
+ release?: ((url: string) => void) | undefined;
56
+ }): {
57
+ images: PwCodeComposerImage[];
58
+ /** Whether a message is waiting on images still being saved. */
59
+ taking: boolean;
60
+ add: (files: readonly F[]) => void;
61
+ remove: (key: string) => void;
62
+ /** Empties the composer and resolves to the saved images; settling with false puts them back. */
63
+ take: () => Promise<PwCodeTakenImages>;
64
+ /** Saves the images added before there was a session; null once one failed, which `onError` was told. */
65
+ saveTo: (machine: string, sessionId: string) => Promise<PwCodeImageRef[] | null>;
66
+ };
@@ -0,0 +1,195 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { IMAGE_PLACEHOLDER } from "./wording.js";
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+ // src/useComposerImages.ts
5
+ var IMAGE_TYPES = [
6
+ "image/png",
7
+ "image/jpeg",
8
+ "image/gif",
9
+ "image/webp"
10
+ ];
11
+ var IMAGE_MAX_BYTES = 5242880;
12
+ var IMAGE_MAX_SIDE = 8e3;
13
+ /** The terminal refuses to read an image file past this, rather than decode it. */
14
+ var IMAGE_READ_MAX_BYTES = 26214400;
15
+ /** Thrown by a host's `encode` for an image it cannot fit within `IMAGE_MAX_BYTES`. */
16
+ var PwCodeImageTooLarge = class extends Error {};
17
+ /** Numbers past every placeholder the texts name, as the terminal does. */
18
+ function nextImageSeq(texts, after) {
19
+ let seq = after;
20
+ for (const text of texts ?? []) for (const match of text?.matchAll(IMAGE_PLACEHOLDER) ?? []) {
21
+ const n = Number(match[1]);
22
+ if (Number.isSafeInteger(n)) seq = Math.max(seq, n);
23
+ }
24
+ return seq + 1;
25
+ }
26
+ /** Images stay with the reader until there is a session to save them with. */
27
+ function useComposerImages({ api, machine, sessionId, messages, onError, describeError, encode, preview, release }) {
28
+ const t = usePwCodeTranslations("agents");
29
+ const [images, setImages] = useState([]);
30
+ const [taking, setTaking] = useState(false);
31
+ const imagesRef = useRef(images);
32
+ imagesRef.current = images;
33
+ const messagesRef = useRef(messages);
34
+ messagesRef.current = messages;
35
+ const host = useRef({
36
+ api,
37
+ describeError,
38
+ encode,
39
+ preview,
40
+ release
41
+ });
42
+ host.current = {
43
+ api,
44
+ describeError,
45
+ encode,
46
+ preview,
47
+ release
48
+ };
49
+ const lastSeq = useRef(0);
50
+ const uploads = useRef(/* @__PURE__ */ new Map());
51
+ const staged = useRef(/* @__PURE__ */ new Map());
52
+ const releasePreview = useCallback((url) => {
53
+ host.current.release?.(url);
54
+ }, []);
55
+ const upload = useCallback(async (machine, sessionId, placeholder, file, seq, mime) => {
56
+ const encoded = await host.current.encode(file, mime);
57
+ const { data, error } = await host.current.api.saveImage(machine, sessionId, {
58
+ seq,
59
+ mime: encoded.mime,
60
+ data: encoded.data
61
+ });
62
+ if (error || !data) throw error;
63
+ return {
64
+ ref: {
65
+ placeholder,
66
+ path: data.path,
67
+ mime: encoded.mime
68
+ },
69
+ preview: {
70
+ mime: encoded.mime,
71
+ data: encoded.data
72
+ }
73
+ };
74
+ }, []);
75
+ const mounted = useRef(false);
76
+ useEffect(() => {
77
+ mounted.current = true;
78
+ return () => {
79
+ mounted.current = false;
80
+ for (const image of imagesRef.current) releasePreview(image.previewUrl);
81
+ };
82
+ }, [releasePreview]);
83
+ /** True when the image was still waiting to go with a message. */
84
+ const discard = useCallback((image) => {
85
+ releasePreview(image.previewUrl);
86
+ setImages((current) => current.filter((i) => i.key !== image.key));
87
+ staged.current.delete(image.key);
88
+ return uploads.current.delete(image.key);
89
+ }, [releasePreview]);
90
+ const reportError = useCallback((error) => onError(error instanceof PwCodeImageTooLarge ? t("detail.imageTooLarge") : host.current.describeError(error)), [onError, t]);
91
+ const add = useCallback((files) => {
92
+ for (const file of files) {
93
+ const mime = IMAGE_TYPES.find((type) => type === file.type);
94
+ if (!mime) {
95
+ onError(t("detail.imageUnsupported"));
96
+ continue;
97
+ }
98
+ if (file.size > 26214400) {
99
+ onError(t("detail.imageTooLarge"));
100
+ continue;
101
+ }
102
+ const seq = nextImageSeq(messagesRef.current?.map((m) => m.content), lastSeq.current);
103
+ lastSeq.current = seq;
104
+ const placeholder = `[Image #${seq}]`;
105
+ const image = {
106
+ key: placeholder,
107
+ placeholder,
108
+ previewUrl: host.current.preview(file),
109
+ saved: !sessionId
110
+ };
111
+ setImages((current) => [...current, image]);
112
+ if (!machine || !sessionId) {
113
+ staged.current.set(image.key, {
114
+ file,
115
+ seq,
116
+ mime
117
+ });
118
+ continue;
119
+ }
120
+ uploads.current.set(image.key, upload(machine, sessionId, placeholder, file, seq, mime).then((saved) => {
121
+ setImages((current) => current.map((i) => i.key === image.key ? {
122
+ ...i,
123
+ saved: true
124
+ } : i));
125
+ return saved;
126
+ }, (error) => {
127
+ if (discard(image)) reportError(error);
128
+ return null;
129
+ }));
130
+ }
131
+ }, [
132
+ discard,
133
+ machine,
134
+ onError,
135
+ reportError,
136
+ sessionId,
137
+ t,
138
+ upload
139
+ ]);
140
+ const saveTo = useCallback(async (machine, sessionId) => {
141
+ setTaking(true);
142
+ try {
143
+ const results = await Promise.allSettled(Array.from(staged.current, ([placeholder, pending]) => upload(machine, sessionId, placeholder, pending.file, pending.seq, pending.mime)));
144
+ const refs = [];
145
+ for (const result of results) {
146
+ if (result.status === "rejected") {
147
+ reportError(result.reason);
148
+ return null;
149
+ }
150
+ refs.push(result.value.ref);
151
+ }
152
+ return refs;
153
+ } finally {
154
+ setTaking(false);
155
+ }
156
+ }, [reportError, upload]);
157
+ return {
158
+ images,
159
+ taking,
160
+ add,
161
+ remove: useCallback((key) => {
162
+ const image = imagesRef.current.find((i) => i.key === key);
163
+ if (image) discard(image);
164
+ }, [discard]),
165
+ take: useCallback(async () => {
166
+ const taken = imagesRef.current;
167
+ if (taken.length === 0) return {
168
+ saved: [],
169
+ settle: () => {}
170
+ };
171
+ setImages([]);
172
+ setTaking(true);
173
+ const results = await Promise.all(taken.map((i) => uploads.current.get(i.key)));
174
+ setTaking(false);
175
+ return {
176
+ saved: results.filter((image) => image !== null && image !== void 0),
177
+ settle: (sent) => {
178
+ if (!sent && mounted.current) {
179
+ setImages((current) => [...taken.filter((_, index) => results[index]).map((image) => ({
180
+ ...image,
181
+ saved: true
182
+ })), ...current]);
183
+ return;
184
+ }
185
+ for (const image of taken) {
186
+ releasePreview(image.previewUrl);
187
+ uploads.current.delete(image.key);
188
+ }
189
+ }
190
+ };
191
+ }, [releasePreview]),
192
+ saveTo
193
+ };
194
+ }
195
+ export { IMAGE_MAX_BYTES, IMAGE_MAX_SIDE, IMAGE_READ_MAX_BYTES, IMAGE_TYPES, PwCodeImageTooLarge, nextImageSeq, useComposerImages };
@@ -0,0 +1,190 @@
1
+ import type { ApprovalAnswerValue, ChatMessage, MessagePaste } from '@parallelworks/ui/ai/headless';
2
+ import type { KeyedMutator } from 'swr';
3
+ import type { PwCodeResult, Schemas } from './apiClient.js';
4
+ import type { PwCodeApi } from './createPwCodeApi.js';
5
+ import { type GoalNotice, type TranscriptState } from './transcript.js';
6
+ import type { PwCodeImage, PwCodeImageRef, PwCodeSessionState } from './types.js';
7
+ import { type PwCodeSteerResult } from './useTranscript.js';
8
+ type Session = Schemas['AgentSession'];
9
+ type SessionDetail = Schemas['AgentSessionDetail'];
10
+ type SessionsResponse = Schemas['AgentSessionsResponse'];
11
+ type StreamEvent = Schemas['AgentStreamEvent'];
12
+ /** A word for the reader above the composer, until they dismiss it. */
13
+ export interface PwCodeNotice {
14
+ text: string;
15
+ warn: boolean;
16
+ /** Said because the machine could not be reached, so it goes once the machine answers. */
17
+ unreachable?: boolean | undefined;
18
+ }
19
+ /** How a main or subagent conversation stands in a list of them. */
20
+ export type PwCodeConversationState = 'approval' | 'running' | 'idle';
21
+ /** A transcript's messages as a view draws them: those it holds, then the one
22
+ * streaming, then those still waiting to be taken. */
23
+ export declare function transcriptMessages(transcript: TranscriptState | null): {
24
+ messages: ChatMessage[];
25
+ queued: ChatMessage[];
26
+ all: ChatMessage[];
27
+ };
28
+ /** A direction that got no answer may have landed, so it reads as lost, never as refused. */
29
+ export declare function directionOutcome(request: () => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>, lost: string, describeError: (error: unknown) => string): Promise<PwCodeSteerResult>;
30
+ /** An open session's conversation: its live transcript, sends routed to the
31
+ * machine, approvals, the notice above the composer, and its subagents. The
32
+ * host reads the listing and the session (`api.useSessions`,
33
+ * `api.useSessionDetail`) and opens the feed with `api.useSessionEvents`,
34
+ * handing it `onEvent` and, once the detail is this visit's own, `cursor`. */
35
+ export declare function usePwCodeConversation({ api, machine, sessionId, sessions, detail: read, describeError, notify, onCleared, onMoved, goalNotice, }: {
36
+ api: PwCodeApi;
37
+ machine: string;
38
+ sessionId: string;
39
+ /** The listing, as `api.useSessions` reads it. */
40
+ sessions: {
41
+ data: SessionsResponse | undefined;
42
+ mutate: KeyedMutator<SessionsResponse>;
43
+ };
44
+ /** The session, as `api.useSessionDetail` reads it. */
45
+ detail: {
46
+ data: SessionDetail | undefined;
47
+ mutate: () => Promise<unknown>;
48
+ };
49
+ /** Words a refusal or failure for the reader. */
50
+ describeError: (error: unknown) => string;
51
+ /** Tells the reader something in passing, such as in a toast. */
52
+ notify: (text: string) => void;
53
+ /** Shows the session that a clear made elsewhere started in place of this one. */
54
+ onCleared: (newId: string) => void;
55
+ /** Shows the copy of this session the listing now has from a shared store. */
56
+ onMoved: (copy: Session) => void;
57
+ goalNotice?: GoalNotice;
58
+ }): {
59
+ messages: ChatMessage[];
60
+ queued: ChatMessage[];
61
+ all: ChatMessage[];
62
+ /** The session as the listing has it, or as its fetch does until then. */
63
+ session: {
64
+ allocation?: string;
65
+ approvals?: import("./api.js").components["schemas"]["ApprovalRequest"][] | null;
66
+ archivedAt?: string;
67
+ autoName?: string;
68
+ branch?: string;
69
+ createdAt: string;
70
+ effort?: string;
71
+ group?: string;
72
+ id: string;
73
+ inputTokens?: number;
74
+ lastError?: string;
75
+ liveHost?: string;
76
+ machineId: string;
77
+ messages: number;
78
+ model: string;
79
+ name?: string;
80
+ outputTokens?: number;
81
+ permissionMode?: string;
82
+ pinnedAt?: string;
83
+ preview: string;
84
+ pullRequestStates?: {
85
+ [key: string]: string;
86
+ };
87
+ pullRequests?: string[] | null;
88
+ remoteControl?: boolean;
89
+ status: "idle" | "running" | "awaiting_approval" | "live_elsewhere";
90
+ turnStartedAt?: string;
91
+ updatedAt: string;
92
+ workspace: string;
93
+ } | undefined;
94
+ detail: {
95
+ addDirs?: import("./api.js").components["schemas"]["AddedDirectory"][] | null;
96
+ allocation?: string;
97
+ allowedDirs?: import("./api.js").components["schemas"]["AllowedDirectory"][] | null;
98
+ approvals?: import("./api.js").components["schemas"]["ApprovalRequest"][] | null;
99
+ archivedAt?: string;
100
+ autoName?: string;
101
+ branch?: string;
102
+ claudeAccount?: string;
103
+ createdAt: string;
104
+ effort?: string;
105
+ goal?: import("./api.js").components["schemas"]["GoalStatus"];
106
+ group?: string;
107
+ history: import("./api.js").components["schemas"]["HistoryItem"][] | null;
108
+ id: string;
109
+ inputTokens?: number;
110
+ lastError?: string;
111
+ lastSeq?: number;
112
+ liveHost?: string;
113
+ machineId: string;
114
+ messages: number;
115
+ model: string;
116
+ name?: string;
117
+ outputTokens?: number;
118
+ permissionMode?: string;
119
+ pinnedAt?: string;
120
+ preview: string;
121
+ pullRequestStates?: {
122
+ [key: string]: string;
123
+ };
124
+ pullRequests?: string[] | null;
125
+ remoteControl?: boolean;
126
+ status: "idle" | "running" | "awaiting_approval" | "live_elsewhere";
127
+ turnId?: string;
128
+ turnStartedAt?: string;
129
+ updatedAt: string;
130
+ usageLimitResumeAt?: string;
131
+ waitingForUsageLimit?: boolean;
132
+ workspace: string;
133
+ workspaceUntrusted?: boolean;
134
+ } | undefined;
135
+ /** The session's state as its last state frame said, until which the detail stands. */
136
+ liveState: PwCodeSessionState | null;
137
+ goal: import("./types.js").PwCodeGoalStatus | undefined;
138
+ addDirs: import("./types.js").PwCodeAddedDirectory[] | null | undefined;
139
+ allowedDirs: import("./types.js").PwCodeAllowedDirectory[] | null | undefined;
140
+ refetch: () => Promise<unknown>;
141
+ transcript: TranscriptState | null;
142
+ sending: boolean;
143
+ /** Hands each frame of the session's feed to the transcript and the subagent views. */
144
+ onEvent: (ev: StreamEvent) => void;
145
+ /** Where the feed resumes from. */
146
+ cursor: () => number;
147
+ /** Hands every frame of the feed to `listener` until the returned call, as a subagent's view reads it. */
148
+ subscribe: (listener: (ev: StreamEvent) => void) => () => void;
149
+ notice: PwCodeNotice | null;
150
+ dismissNotice: () => void;
151
+ warn: (text: string, unreachable?: boolean) => void;
152
+ showError: (error: unknown) => void;
153
+ /** Takes back a notice that the machine could not be reached, once it answers. */
154
+ reached: () => void;
155
+ deliver: (text: string, options: {
156
+ steer?: boolean;
157
+ pastes?: MessagePaste[] | undefined;
158
+ images?: PwCodeImageRef[] | undefined;
159
+ previews?: PwCodeImage[] | undefined;
160
+ }) => Promise<{
161
+ text: string;
162
+ unreachable: boolean;
163
+ } | null>;
164
+ noteShellRun: (command: string, output: string) => void;
165
+ canRemoveQueued: (id: string) => boolean;
166
+ removeQueued: (id: string) => Promise<void>;
167
+ /** Whether a queued message goes into the running turn's next step or waits for its reply. */
168
+ queueDelivery: (id: string) => 'nextStep' | 'afterReply';
169
+ answerApproval: (approvalId: string, answer: ApprovalAnswerValue) => Promise<void>;
170
+ subagents: {
171
+ agentType?: string;
172
+ awaitingApproval?: boolean;
173
+ background?: boolean;
174
+ color?: string;
175
+ current?: boolean;
176
+ description?: string;
177
+ endedAt?: string;
178
+ id: string;
179
+ model?: string;
180
+ startedAt?: string;
181
+ status: "running" | "done" | "failed" | "stopped";
182
+ usage?: import("./api.js").components["schemas"]["SubagentUsage"];
183
+ }[];
184
+ refreshSubagents: () => void;
185
+ stopSubagent: (id: string) => Promise<void>;
186
+ stopAllSubagents: () => Promise<void>;
187
+ mainState: PwCodeConversationState;
188
+ };
189
+ export type PwCodeConversation = ReturnType<typeof usePwCodeConversation>;
190
+ export {};