@parallelworks/code 0.2.0 → 0.4.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 (126) hide show
  1. package/README.md +602 -84
  2. package/dist/accountApi.d.ts +31 -0
  3. package/dist/accountApi.js +182 -0
  4. package/dist/agentSwitcher.d.ts +109 -0
  5. package/dist/agentSwitcher.js +165 -0
  6. package/dist/ago.d.ts +8 -0
  7. package/dist/ago.js +26 -0
  8. package/dist/allocations.d.ts +41 -0
  9. package/dist/allocations.js +76 -0
  10. package/dist/api.d.ts +1213 -66
  11. package/dist/base64.d.ts +3 -0
  12. package/dist/base64.js +15 -0
  13. package/dist/chatHandoff.d.ts +12 -0
  14. package/dist/chatHandoff.js +27 -0
  15. package/dist/chatStrings.d.ts +188 -0
  16. package/dist/chatStrings.js +217 -0
  17. package/dist/claudeAccounts.d.ts +149 -0
  18. package/dist/claudeAccounts.js +328 -0
  19. package/dist/claudeApi.js +1 -1
  20. package/dist/claudeSignIn.d.ts +80 -0
  21. package/dist/claudeSignIn.js +249 -0
  22. package/dist/commandsApi.d.ts +11 -1
  23. package/dist/commandsApi.js +24 -5
  24. package/dist/contextRow.d.ts +25 -0
  25. package/dist/contextRow.js +16 -0
  26. package/dist/createPwCodeApi.d.ts +52 -5
  27. package/dist/createPwCodeApi.js +20 -2
  28. package/dist/directories.d.ts +161 -0
  29. package/dist/directories.js +301 -0
  30. package/dist/goal.d.ts +89 -0
  31. package/dist/goal.js +164 -0
  32. package/dist/howSessionsAppear.d.ts +12 -0
  33. package/dist/howSessionsAppear.js +24 -0
  34. package/dist/imageFit.d.ts +23 -0
  35. package/dist/imageFit.js +27 -0
  36. package/dist/images.d.ts +28 -0
  37. package/dist/images.js +38 -6
  38. package/dist/index.d.ts +41 -3
  39. package/dist/index.js +40 -4
  40. package/dist/loadError.d.ts +8 -0
  41. package/dist/loadError.js +19 -0
  42. package/dist/locales/en/agentTranscript.js +75 -22
  43. package/dist/locales/en/agents.js +76 -14
  44. package/dist/locales/en.d.ts +129 -21
  45. package/dist/locales/es/agentTranscript.js +75 -22
  46. package/dist/locales/es/agents.js +76 -14
  47. package/dist/locales/ja/agentTranscript.js +78 -25
  48. package/dist/locales/ja/agents.js +49 -124
  49. package/dist/locales/ko/agentTranscript.js +75 -22
  50. package/dist/locales/ko/agents.js +76 -14
  51. package/dist/locales/zh/agentTranscript.js +73 -20
  52. package/dist/locales/zh/agents.js +76 -14
  53. package/dist/machine.d.ts +4 -0
  54. package/dist/modelPicker.d.ts +79 -0
  55. package/dist/modelPicker.js +107 -0
  56. package/dist/models.d.ts +47 -0
  57. package/dist/models.js +49 -0
  58. package/dist/notices.d.ts +2 -1
  59. package/dist/notices.js +75 -21
  60. package/dist/platformDefaults.d.ts +22 -0
  61. package/dist/platformDefaults.js +30 -0
  62. package/dist/preferences.d.ts +78 -0
  63. package/dist/preferences.js +128 -0
  64. package/dist/pullRequestList.d.ts +60 -0
  65. package/dist/pullRequestList.js +125 -0
  66. package/dist/query.d.ts +6 -2
  67. package/dist/query.js +85 -10
  68. package/dist/session.d.ts +10 -2
  69. package/dist/session.js +12 -8
  70. package/dist/sessionActions.d.ts +115 -0
  71. package/dist/sessionActions.js +186 -0
  72. package/dist/sessionEvents.d.ts +8 -3
  73. package/dist/sessionEvents.js +10 -5
  74. package/dist/sessionGroups.d.ts +50 -0
  75. package/dist/sessionGroups.js +73 -0
  76. package/dist/sessionHeader.d.ts +14 -0
  77. package/dist/sessionHeader.js +16 -0
  78. package/dist/sessionList.d.ts +182 -0
  79. package/dist/sessionList.js +333 -0
  80. package/dist/sessionScreen.d.ts +193 -0
  81. package/dist/sessionScreen.js +213 -0
  82. package/dist/sessionsApi.d.ts +13 -3
  83. package/dist/sessionsApi.js +90 -33
  84. package/dist/settingsApi.d.ts +38 -0
  85. package/dist/settingsApi.js +151 -0
  86. package/dist/startPage.d.ts +153 -0
  87. package/dist/startPage.js +174 -0
  88. package/dist/startSession.d.ts +172 -0
  89. package/dist/startSession.js +256 -0
  90. package/dist/terminalHandoffPanel.d.ts +30 -0
  91. package/dist/terminalHandoffPanel.js +33 -0
  92. package/dist/transcript.d.ts +2 -0
  93. package/dist/transcript.js +62 -26
  94. package/dist/types.d.ts +11 -1
  95. package/dist/usageLimit.d.ts +8 -0
  96. package/dist/usageLimit.js +13 -0
  97. package/dist/useAwayRecap.d.ts +30 -0
  98. package/dist/useAwayRecap.js +75 -0
  99. package/dist/useComposer.d.ts +145 -0
  100. package/dist/useComposer.js +295 -0
  101. package/dist/useComposerImages.d.ts +71 -0
  102. package/dist/useComposerImages.js +218 -0
  103. package/dist/useComposerPastes.d.ts +70 -0
  104. package/dist/useComposerPastes.js +130 -0
  105. package/dist/useConversation.d.ts +199 -0
  106. package/dist/useConversation.js +314 -0
  107. package/dist/useSubagent.d.ts +104 -0
  108. package/dist/useSubagent.js +212 -0
  109. package/dist/useTranscript.d.ts +23 -3
  110. package/dist/useTranscript.js +76 -19
  111. package/dist/wording.js +2 -2
  112. package/dist/workingDirectories.d.ts +63 -0
  113. package/dist/workingDirectories.js +95 -0
  114. package/dist/worktreeChoice.d.ts +31 -0
  115. package/dist/worktreeChoice.js +38 -0
  116. package/locales/en/agentTranscript.json +69 -21
  117. package/locales/en/agents.json +73 -13
  118. package/locales/es/agentTranscript.json +69 -21
  119. package/locales/es/agents.json +73 -13
  120. package/locales/ja/agentTranscript.json +72 -24
  121. package/locales/ja/agents.json +73 -13
  122. package/locales/ko/agentTranscript.json +69 -21
  123. package/locales/ko/agents.json +73 -13
  124. package/locales/zh/agentTranscript.json +67 -19
  125. package/locales/zh/agents.json +73 -13
  126. package/package.json +6 -3
@@ -0,0 +1,75 @@
1
+ import { useCallback, useEffect, useRef } from "react";
2
+ import { DateTime } from "luxon";
3
+ // src/useAwayRecap.ts
4
+ var recapAfterTurnMs = 12e4;
5
+ var recapAfterLeavingMs = 2e3;
6
+ function nowMs() {
7
+ return DateTime.now().toMillis();
8
+ }
9
+ /** Has the session recapped while the reader is away from it, as pw code
10
+ * does while its terminal is out of focus, so the recap is waiting when they
11
+ * come back. The machine declines while its recaps are off. */
12
+ function useAwayRecap({ api, machine, sessionId, turnEndSeq, idle, drafting, presence }) {
13
+ const idleRef = useRef(idle);
14
+ idleRef.current = idle;
15
+ const draftingRef = useRef(drafting);
16
+ draftingRef.current = drafting;
17
+ const presenceRef = useRef(presence);
18
+ presenceRef.current = presence;
19
+ const apiRef = useRef(api);
20
+ apiRef.current = api;
21
+ const turnEndedAt = useRef(null);
22
+ const counted = useRef(void 0);
23
+ const leftAt = useRef(null);
24
+ const timer = useRef(void 0);
25
+ const request = useRef(null);
26
+ const ask = useCallback(async () => {
27
+ if (request.current || !presenceRef.current.away() || !idleRef.current || draftingRef.current()) return;
28
+ const controller = new AbortController();
29
+ request.current = controller;
30
+ await apiRef.current.requestRecap(machine, sessionId, controller.signal).catch(() => void 0);
31
+ if (request.current === controller) request.current = null;
32
+ }, [machine, sessionId]);
33
+ const arm = useCallback(() => {
34
+ clearTimeout(timer.current);
35
+ const ended = turnEndedAt.current;
36
+ const left = leftAt.current;
37
+ if (ended === null || left === null) return;
38
+ const now = nowMs();
39
+ const wait = Math.max(ended + recapAfterTurnMs - now, left + recapAfterLeavingMs - now);
40
+ timer.current = setTimeout(() => void ask(), wait);
41
+ }, [ask]);
42
+ useEffect(() => {
43
+ const away = () => presenceRef.current.away();
44
+ leftAt.current = away() ? nowMs() : null;
45
+ const leave = () => {
46
+ if (leftAt.current === null && away()) {
47
+ leftAt.current = nowMs();
48
+ arm();
49
+ }
50
+ };
51
+ const back = () => {
52
+ if (!away()) {
53
+ leftAt.current = null;
54
+ clearTimeout(timer.current);
55
+ }
56
+ };
57
+ const unwatch = presenceRef.current.watch({
58
+ leave,
59
+ back
60
+ });
61
+ return () => {
62
+ unwatch();
63
+ clearTimeout(timer.current);
64
+ request.current?.abort();
65
+ request.current = null;
66
+ };
67
+ }, [arm]);
68
+ useEffect(() => {
69
+ if (turnEndSeq === void 0 || turnEndSeq === counted.current) return;
70
+ counted.current = turnEndSeq;
71
+ turnEndedAt.current = nowMs();
72
+ arm();
73
+ }, [turnEndSeq, arm]);
74
+ }
75
+ export { recapAfterLeavingMs, recapAfterTurnMs, useAwayRecap };
@@ -0,0 +1,145 @@
1
+ import type { MessagePaste } from '@parallelworks/ui/ai/headless';
2
+ import type { Schemas } from './apiClient.js';
3
+ import type { PwCodeApi } from './createPwCodeApi.js';
4
+ import type { PwCodeConversation } from './useConversation.js';
5
+ import { type PwCodeSavedImage, type PwCodeTakenImages } from './useComposerImages.js';
6
+ /** The composer's history of sent prompts, as `@parallelworks/ui/ai`'s
7
+ * `ComposerHistory` takes it. */
8
+ export interface PwCodeComposerHistory {
9
+ /** Composers with the same name share one history. */
10
+ name: string;
11
+ /** Text to forget, such as a command carrying a secret. */
12
+ skip?: ((text: string) => boolean) | undefined;
13
+ }
14
+ /** Per person, since someone else can sign in where the history is kept, and
15
+ * without `/auth`, which can carry a key. */
16
+ export declare function promptHistory(username: string): PwCodeComposerHistory;
17
+ /** What a command printed, shown below the transcript under the command as typed. */
18
+ export interface PwCodeCommandOutput {
19
+ id: number;
20
+ command: string;
21
+ text: string;
22
+ }
23
+ export declare function useCommandOutputs(): {
24
+ outputs: PwCodeCommandOutput[];
25
+ add: (command: string, text: string) => void;
26
+ dismiss: (id: number) => void;
27
+ clear: () => void;
28
+ };
29
+ /** What the reader can do from an open session's composer, and how the
30
+ * session stands for it: what is typed goes out as a message, a direction to
31
+ * the running turn, a command or a `!` shell run, and the composer locks
32
+ * while the machine is unreachable, the session is archived or live
33
+ * elsewhere, or it waits on an approval. */
34
+ export declare function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo, feed, staleFor, images, handleLocally, notify, onCleared, onArchived, }: {
35
+ api: PwCodeApi;
36
+ machine: string;
37
+ sessionId: string;
38
+ /** What `usePwCodeConversation` returned for the session. */
39
+ conversation: PwCodeConversation;
40
+ /** The session's machine, as `api.useMachine` reads it. */
41
+ machineInfo: Schemas['AgentMachine'] | undefined;
42
+ /** The session's feed, as `api.useSessionEvents` reports it. */
43
+ feed: {
44
+ connected: boolean;
45
+ disconnected: boolean;
46
+ };
47
+ /** How long ago the transcript was last read, already abbreviated: see `useLastReadAt`. */
48
+ staleFor: string;
49
+ /** The images waiting to go with the next message, as `useComposerImages` holds them. */
50
+ images?: {
51
+ take: () => Promise<PwCodeTakenImages>;
52
+ restore: (saved: readonly PwCodeSavedImage[]) => void;
53
+ taking: boolean;
54
+ } | undefined;
55
+ /** Typed text the host acts on itself, such as a command that opens one of
56
+ * its own panels; true takes it, sending nothing. */
57
+ handleLocally?: ((typed: string) => boolean) | undefined;
58
+ /** Tells the reader something in passing, such as in a toast. */
59
+ notify: (text: string) => void;
60
+ /** Shows the session `/clear` started in place of this one. */
61
+ onCleared: (newId: string) => void;
62
+ /** Leaves the session `/archive` archived. */
63
+ onArchived: () => void;
64
+ }): {
65
+ /** Sends what was typed; false hands it back to the composer. */
66
+ send: (typed: string, pastes?: MessagePaste[]) => Promise<boolean>;
67
+ turn: {
68
+ running: boolean;
69
+ stop: () => Promise<void>;
70
+ stopping: boolean;
71
+ };
72
+ composer: {
73
+ placeholder: string;
74
+ hint: string;
75
+ locked: boolean;
76
+ disabled: boolean;
77
+ };
78
+ /** The composer's `recall`: ↑ in it, or Edit under the queue, takes back what waits. */
79
+ recall: {
80
+ available: boolean;
81
+ take: () => Promise<{
82
+ text: string;
83
+ pastes: MessagePaste[] | undefined;
84
+ }[]>;
85
+ };
86
+ /** Why nothing can be sent to the session at all, which a subagent's composer shows too. */
87
+ sessionLock: {
88
+ placeholder: string;
89
+ hint: string;
90
+ locked: boolean;
91
+ } | null;
92
+ shellRun: string | null;
93
+ outputs: PwCodeCommandOutput[];
94
+ dismissOutput: (id: number) => void;
95
+ palette: {
96
+ commands: import("./api.js").components["schemas"]["AgentSlashCommand"][] | null;
97
+ mcpPrompts: import("./api.js").components["schemas"]["AgentSlashCommand"][] | null;
98
+ prompts: string[] | null;
99
+ } | null;
100
+ paletteLoading: boolean;
101
+ /** Opens the command menu, which asks for the session's palette again. */
102
+ openPalette: () => undefined;
103
+ loadPalette: () => Promise<{
104
+ commands: import("./api.js").components["schemas"]["AgentSlashCommand"][] | null;
105
+ mcpPrompts: import("./api.js").components["schemas"]["AgentSlashCommand"][] | null;
106
+ prompts: string[] | null;
107
+ } | null>;
108
+ status: import("./types.js").PwCodeSessionStatus | null;
109
+ approvals: {
110
+ kind: "ask" | "confirm" | "plan";
111
+ }[] | null | undefined;
112
+ unreachable: boolean;
113
+ reconnecting: boolean;
114
+ archived: boolean;
115
+ machineName: string;
116
+ /** A turn is under way on a machine that answers. */
117
+ working: boolean;
118
+ checkingGoal: boolean;
119
+ /** The session rests between turns and can be reached. */
120
+ idle: boolean;
121
+ /** Ends the transcript while the machine cannot be reached. */
122
+ endNote: string | undefined;
123
+ /** The offer to move the Bash commands the turn waits on to the background. */
124
+ background: {
125
+ offered: boolean;
126
+ moving: boolean;
127
+ move: () => Promise<void>;
128
+ };
129
+ };
130
+ export type PwCodeComposer = ReturnType<typeof usePwCodeComposer>;
131
+ /** Stops a composer's turn as `@parallelworks/ui/ai`'s session view does,
132
+ * for a host that draws its own composer: while what waits can come back
133
+ * (`recall.available`), `takeBack`, the composer's own take-back into its
134
+ * box, runs first, so none of it starts a turn once this one stops; then
135
+ * the turn stops, even when taking back failed. Resolves to what taking
136
+ * back threw, which the session view only logs.
137
+ * Takes `usePwCodeComposer`'s or `usePwCodeSubagent`'s result. */
138
+ export declare function stopTurn(composer: {
139
+ recall: {
140
+ available: boolean;
141
+ };
142
+ turn: {
143
+ stop: () => Promise<void>;
144
+ };
145
+ }, takeBack: () => Promise<unknown>): Promise<unknown>;
@@ -0,0 +1,295 @@
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 { withoutAppendedImages } from "./useComposerImages.js";
6
+ import { composerState, sessionLabel } from "./wording.js";
7
+ import { useCallback, useEffect, useRef, useState } from "react";
8
+ // src/useComposer.ts
9
+ /** Per person, since someone else can sign in where the history is kept, and
10
+ * without `/auth`, which can carry a key. */
11
+ function promptHistory(username) {
12
+ return {
13
+ name: `agents:${username}`,
14
+ skip: (text) => /^\/auth(\s|$)/.test(text)
15
+ };
16
+ }
17
+ /** Typed text steers a running turn; what a command resolved to runs as a turn of its own, and comes back as typed. */
18
+ function resolvedDelivery(text, typed) {
19
+ return text === typed ? { steer: true } : {
20
+ steer: false,
21
+ typed
22
+ };
23
+ }
24
+ function useCommandOutputs() {
25
+ const [outputs, setOutputs] = useState([]);
26
+ const seq = useRef(0);
27
+ return {
28
+ outputs,
29
+ add: useCallback((command, text) => {
30
+ seq.current += 1;
31
+ const id = seq.current;
32
+ setOutputs((prev) => [...prev, {
33
+ id,
34
+ command,
35
+ text
36
+ }]);
37
+ }, []),
38
+ dismiss: useCallback((id) => setOutputs((prev) => prev.filter((o) => o.id !== id)), []),
39
+ clear: useCallback(() => setOutputs([]), [])
40
+ };
41
+ }
42
+ /** What the reader can do from an open session's composer, and how the
43
+ * session stands for it: what is typed goes out as a message, a direction to
44
+ * the running turn, a command or a `!` shell run, and the composer locks
45
+ * while the machine is unreachable, the session is archived or live
46
+ * elsewhere, or it waits on an approval. */
47
+ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo, feed, staleFor, images, handleLocally, notify, onCleared, onArchived }) {
48
+ const t = usePwCodeTranslations("agents");
49
+ const { session, detail, transcript, goal, sending, refetch, warn, showError, reached, deliver, noteShellRun, queued, canRemoveQueued, takeBackPending } = conversation;
50
+ const [shellRun, setShellRun] = useState(null);
51
+ const delivering = useRef(null);
52
+ const { palette, loading: paletteLoading, load: loadPalette } = api.usePalette(machine, sessionId);
53
+ const openPalette = useCallback(() => void loadPalette().catch(() => {}), [loadPalette]);
54
+ const commandOutputs = useCommandOutputs();
55
+ const running = turnRunning(transcript);
56
+ const checkingGoal = !!goal?.checking;
57
+ const onShellRun = useCallback((command, output, stop) => {
58
+ commandOutputs.clear();
59
+ noteShellRun(command, output);
60
+ if (stop) warn(t("detail.shellStopped", { reason: stop }));
61
+ }, [
62
+ commandOutputs.clear,
63
+ noteShellRun,
64
+ t,
65
+ warn
66
+ ]);
67
+ const { archiveSession, archiveAfterTurn, stopSession } = api.useSessionMutations();
68
+ /** Resolves to the machine's refusal. A session archived once its turn ends stays open, and the machine says so in the transcript. */
69
+ const archiveTyped = useCallback(async (s, waits) => {
70
+ const { refusal, deferred } = waits ? await archiveAfterTurn(s) : {
71
+ refusal: await archiveSession(s),
72
+ deferred: false
73
+ };
74
+ if (!refusal && !deferred) {
75
+ notify(t("detail.archived", { name: sessionLabel(s, t) }));
76
+ onArchived();
77
+ }
78
+ return refusal;
79
+ }, [
80
+ archiveAfterTurn,
81
+ archiveSession,
82
+ notify,
83
+ onArchived,
84
+ t
85
+ ]);
86
+ const takeImages = images?.take;
87
+ const send = useCallback(async (typed, pastes) => {
88
+ const command = shellCommand(typed);
89
+ if (command && running) {
90
+ warn(t("detail.shellWhileRunning"));
91
+ return false;
92
+ }
93
+ if (handleLocally?.(typed)) return true;
94
+ if (command) setShellRun(command);
95
+ let refused = false;
96
+ const refuse = (error) => {
97
+ refused = true;
98
+ showError(error);
99
+ };
100
+ const text = await api.resolveTyped(typed, {
101
+ machine,
102
+ sessionId,
103
+ palette,
104
+ loadPalette,
105
+ planOnMachine: (path) => t("detail.planOnMachine", { path }),
106
+ onOutput: commandOutputs.add,
107
+ onShellRun,
108
+ onCompacted: () => void refetch(),
109
+ onCleared,
110
+ onArchive: async () => {
111
+ const waits = machineInfo?.archiveAfterTurn === true;
112
+ if (running && !waits) {
113
+ refused = true;
114
+ warn(t("detail.archiveWhileRunning"));
115
+ return;
116
+ }
117
+ const refusal = session && await archiveTyped(session, waits);
118
+ if (refusal) refuse(refusal);
119
+ },
120
+ onRefused: refuse
121
+ }).catch((error) => {
122
+ refuse(error);
123
+ return null;
124
+ }).finally(() => setShellRun(null));
125
+ if (text === null) return !refused;
126
+ commandOutputs.clear();
127
+ const { saved, settle } = takeImages ? await takeImages() : {
128
+ saved: [],
129
+ settle: () => {}
130
+ };
131
+ const refs = saved.map((i) => i.ref);
132
+ const message = [text, ...refs.map((i) => i.placeholder).filter((p) => !text.includes(p))].filter(Boolean).join(" ");
133
+ const delivery = deliver(message, {
134
+ ...resolvedDelivery(text, typed),
135
+ pastes,
136
+ images: refs,
137
+ previews: saved.map((i) => i.preview)
138
+ });
139
+ delivering.current = delivery;
140
+ const refusal = await delivery;
141
+ settle(!refusal);
142
+ if (refusal) warn(refusal.text, refusal.unreachable);
143
+ else reached();
144
+ return !refusal;
145
+ }, [
146
+ api,
147
+ archiveTyped,
148
+ commandOutputs.add,
149
+ commandOutputs.clear,
150
+ deliver,
151
+ handleLocally,
152
+ loadPalette,
153
+ machine,
154
+ machineInfo?.archiveAfterTurn,
155
+ onCleared,
156
+ onShellRun,
157
+ palette,
158
+ reached,
159
+ refetch,
160
+ running,
161
+ session,
162
+ sessionId,
163
+ showError,
164
+ t,
165
+ takeImages,
166
+ warn
167
+ ]);
168
+ const [stopping, setStopping] = useState(false);
169
+ const stop = useCallback(async () => {
170
+ if (!session) return;
171
+ setStopping(true);
172
+ await delivering.current;
173
+ const refusal = await stopSession(session);
174
+ setStopping(false);
175
+ if (refusal) showError(refusal);
176
+ }, [
177
+ showError,
178
+ session,
179
+ stopSession
180
+ ]);
181
+ const restoreImages = images?.restore;
182
+ /** Takes back what waits into the composer, as ↑ does in the terminal; one the model read meanwhile stays sent. */
183
+ const takeBack = useCallback(async () => {
184
+ const { taken, refusal } = await takeBackPending();
185
+ if (refusal) warn(refusal);
186
+ restoreImages?.(taken.flatMap(({ images = [], previews = [] }) => images.flatMap((ref, i) => {
187
+ const preview = previews[i];
188
+ return preview ? [{
189
+ ref,
190
+ preview
191
+ }] : [];
192
+ })));
193
+ return taken.map((m) => ({
194
+ text: withoutAppendedImages(m.text, m.images),
195
+ pastes: m.pastes
196
+ }));
197
+ }, [
198
+ restoreImages,
199
+ takeBackPending,
200
+ warn
201
+ ]);
202
+ const status = detail ? liveSessionStatus(detail.status, transcript, goal) : null;
203
+ const approvals = transcript ? pendingApprovals(transcript).map((p) => ({ kind: p.approvalKind })) : detail?.approvals;
204
+ const unreachable = isMachineDown(machineInfo) && !feed.connected;
205
+ const liveElsewhere = status === "live_elsewhere";
206
+ const reconnecting = !!detail && feed.disconnected && !unreachable && !liveElsewhere;
207
+ const archived = !!session?.archivedAt;
208
+ const machineName = machineInfo?.name ?? machine;
209
+ useEffect(() => {
210
+ if (!unreachable && !feed.disconnected) reached();
211
+ }, [
212
+ unreachable,
213
+ feed.disconnected,
214
+ reached
215
+ ]);
216
+ const working = status === "running" && !unreachable;
217
+ const background = api.useBackgroundCommands({
218
+ machine,
219
+ sessionId,
220
+ running: working && bashRunning(transcript),
221
+ onError: showError
222
+ });
223
+ const state = composerState({
224
+ unreachable,
225
+ archived,
226
+ machineName,
227
+ staleFor,
228
+ status,
229
+ liveHost: detail?.liveHost,
230
+ approvals,
231
+ shellRun: shellRun ?? void 0,
232
+ t
233
+ });
234
+ return {
235
+ /** Sends what was typed; false hands it back to the composer. */
236
+ send,
237
+ turn: {
238
+ running: (running || checkingGoal) && !unreachable,
239
+ stop,
240
+ stopping
241
+ },
242
+ composer: {
243
+ ...state,
244
+ disabled: sending || !!images?.taking || state.locked
245
+ },
246
+ /** The composer's `recall`: ↑ in it, or Edit under the queue, takes back what waits. */
247
+ recall: {
248
+ available: queued.some((m) => canRemoveQueued(m.id)),
249
+ take: takeBack
250
+ },
251
+ /** Why nothing can be sent to the session at all, which a subagent's composer shows too. */
252
+ sessionLock: unreachable || archived || liveElsewhere ? state : null,
253
+ shellRun,
254
+ outputs: commandOutputs.outputs,
255
+ dismissOutput: commandOutputs.dismiss,
256
+ palette,
257
+ paletteLoading,
258
+ /** Opens the command menu, which asks for the session's palette again. */
259
+ openPalette,
260
+ loadPalette,
261
+ status,
262
+ approvals,
263
+ unreachable,
264
+ reconnecting,
265
+ archived,
266
+ machineName,
267
+ /** A turn is under way on a machine that answers. */
268
+ working,
269
+ checkingGoal,
270
+ /** The session rests between turns and can be reached. */
271
+ idle: status === "idle" && !unreachable && !archived && !feed.disconnected,
272
+ /** Ends the transcript while the machine cannot be reached. */
273
+ endNote: unreachable ? t("detail.transcriptEnds", { machine: machineName }) : void 0,
274
+ /** The offer to move the Bash commands the turn waits on to the background. */
275
+ background
276
+ };
277
+ }
278
+ /** Stops a composer's turn as `@parallelworks/ui/ai`'s session view does,
279
+ * for a host that draws its own composer: while what waits can come back
280
+ * (`recall.available`), `takeBack`, the composer's own take-back into its
281
+ * box, runs first, so none of it starts a turn once this one stops; then
282
+ * the turn stops, even when taking back failed. Resolves to what taking
283
+ * back threw, which the session view only logs.
284
+ * Takes `usePwCodeComposer`'s or `usePwCodeSubagent`'s result. */
285
+ async function stopTurn(composer, takeBack) {
286
+ let failure;
287
+ if (composer.recall.available) try {
288
+ await takeBack();
289
+ } catch (error) {
290
+ failure = error;
291
+ }
292
+ await composer.turn.stop();
293
+ return failure;
294
+ }
295
+ export { promptHistory, stopTurn, useCommandOutputs, usePwCodeComposer };
@@ -0,0 +1,71 @@
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
+ /** The send appends the placeholders of images its text left out; a message
35
+ * taken back gives them back as images, so they leave its text. */
36
+ export declare function withoutAppendedImages(text: string, images: readonly PwCodeImageRef[] | undefined): string;
37
+ /** Images stay with the reader until there is a session to save them with. */
38
+ export declare function useComposerImages<F extends PwCodeImageFile>({ api, machine, sessionId, messages, onError, describeError, encode, preview, release, }: {
39
+ api: Pick<PwCodeApi, 'saveImage'>;
40
+ machine?: string | undefined;
41
+ sessionId?: string | undefined;
42
+ /** The live transcript: the fetched history misses what the terminal sent since. */
43
+ messages: readonly {
44
+ content?: string | null | undefined;
45
+ }[] | undefined;
46
+ onError: (text: string) => void;
47
+ /** Words a refusal or failure for the reader. */
48
+ describeError: (error: unknown) => string;
49
+ /** Base64 of the image fitted within `IMAGE_MAX_BYTES` and `IMAGE_MAX_SIDE`,
50
+ * in the type it was written in. Throws `PwCodeImageTooLarge` for one that
51
+ * will not fit. */
52
+ encode: (file: F, type: PwCodeImageType) => Promise<{
53
+ data: string;
54
+ mime: PwCodeImageType;
55
+ }>;
56
+ /** A URL the host draws the image from until `release` frees it. */
57
+ preview: (file: F) => string;
58
+ release?: ((url: string) => void) | undefined;
59
+ }): {
60
+ images: PwCodeComposerImage[];
61
+ /** Whether a message is waiting on images still being saved. */
62
+ taking: boolean;
63
+ add: (files: readonly F[]) => void;
64
+ remove: (key: string) => void;
65
+ /** Empties the composer and resolves to the saved images; settling with false puts them back. */
66
+ take: () => Promise<PwCodeTakenImages>;
67
+ /** Puts back the images a message taken back was sent with, already saved with the session. */
68
+ restore: (saved: readonly PwCodeSavedImage[]) => void;
69
+ /** Saves the images added before there was a session; null once one failed, which `onError` was told. */
70
+ saveTo: (machine: string, sessionId: string) => Promise<PwCodeImageRef[] | null>;
71
+ };