@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,314 @@
1
+ import { steerMayHaveLanded } from "./command.js";
2
+ import { sessionImageUrl } from "./images.js";
3
+ import { isUnreachableError } from "./machine.js";
4
+ import { usePwCodeTranslations } from "./messages.js";
5
+ import { useCompactionNotice, useRecapNotice, useTranscriptWords } from "./notices.js";
6
+ import { isSession, sharedStoreCopy } from "./session.js";
7
+ import { changesSubagents } from "./sessionEvents.js";
8
+ import { pasteRefs, patchSessionNames } from "./sessionsApi.js";
9
+ import { pendingApprovals, pendingMessages } from "./transcript.js";
10
+ import { usePwCodeTranscript } from "./useTranscript.js";
11
+ import { useCallback, useEffect, useRef, useState } from "react";
12
+ // src/useConversation.ts
13
+ /** A transcript's messages as a view draws them: those it holds, then the one
14
+ * streaming, then those still waiting to be taken. */
15
+ function transcriptMessages(transcript) {
16
+ const messages = transcript?.messages ?? [];
17
+ const queued = transcript ? pendingMessages(transcript) : [];
18
+ return {
19
+ messages,
20
+ queued,
21
+ all: transcript ? [
22
+ ...messages,
23
+ ...transcript.streaming ? [transcript.streaming] : [],
24
+ ...queued
25
+ ] : messages
26
+ };
27
+ }
28
+ /** A direction that got no answer may have landed, so it reads as lost, never as refused. */
29
+ async function directionOutcome(request, lost, describeError) {
30
+ try {
31
+ const { data, error } = await request();
32
+ if (!error) return {
33
+ delivered: !!data?.delivered,
34
+ id: data?.id
35
+ };
36
+ return steerMayHaveLanded(error) ? { lost } : { error: describeError(error) };
37
+ } catch {
38
+ return { lost };
39
+ }
40
+ }
41
+ /** Taking back a direction is refused once the model read it, and a lost connection refuses it too. */
42
+ async function withdrawalOutcome(noteId, request, alreadyRead, describeError) {
43
+ try {
44
+ const { data, error } = await request();
45
+ if (error) return { error: describeError(error) };
46
+ return data?.withdrawn?.includes(noteId) ? {} : { error: alreadyRead };
47
+ } catch (error) {
48
+ return { error: describeError(error) };
49
+ }
50
+ }
51
+ /** What a frame says of the main conversation's own turn; null leaves it to the refetched detail, undefined says nothing. */
52
+ function mainTurnAfter(ev) {
53
+ if (ev.type === "replay_truncated") return null;
54
+ if (ev.id) return;
55
+ if (ev.type === "user_message" || ev.type === "turn_start") return true;
56
+ if (ev.turnId && (ev.type === "done" || ev.type === "error")) return false;
57
+ }
58
+ /** An open session's conversation: its live transcript, sends routed to the
59
+ * machine, approvals, the notice above the composer, and its subagents. The
60
+ * host reads the listing and the session (`api.useSessions`,
61
+ * `api.useSessionDetail`) and opens the feed with `api.useSessionEvents`,
62
+ * handing it `onEvent` and, once the detail is this visit's own, `cursor`. */
63
+ function usePwCodeConversation({ api, machine, sessionId, sessions, detail: read, describeError, notify, onCleared, onMoved, goalNotice }) {
64
+ const t = usePwCodeTranslations("agents");
65
+ const { data: list, mutate: mutateSessions } = sessions;
66
+ const { data: detail, mutate } = read;
67
+ const session = list?.sessions?.find((s) => isSession(s, machine, sessionId)) ?? detail;
68
+ const moved = sharedStoreCopy(list, machine, sessionId);
69
+ const onMovedRef = useRef(onMoved);
70
+ onMovedRef.current = onMoved;
71
+ useEffect(() => {
72
+ if (moved) onMovedRef.current(moved);
73
+ }, [moved]);
74
+ const [liveState, setLiveState] = useState(null);
75
+ const [notice, setNotice] = useState(null);
76
+ const showError = useCallback((error) => setNotice({
77
+ text: describeError(error),
78
+ warn: true,
79
+ unreachable: isUnreachableError(error)
80
+ }), [describeError]);
81
+ const warn = useCallback((text, unreachable) => setNotice(unreachable === void 0 ? {
82
+ text,
83
+ warn: true
84
+ } : {
85
+ text,
86
+ warn: true,
87
+ unreachable
88
+ }), []);
89
+ const dismissNotice = useCallback(() => setNotice(null), []);
90
+ const reached = useCallback(() => setNotice((current) => current?.unreachable ? null : current), []);
91
+ const sendUnreachable = useRef(false);
92
+ const runEffect = useCallback((effect) => {
93
+ switch (effect.type) {
94
+ case "refetch":
95
+ mutate();
96
+ break;
97
+ case "cleared":
98
+ notify(t("detail.cleared"));
99
+ onCleared(effect.newId);
100
+ break;
101
+ case "state": {
102
+ setLiveState(effect.state);
103
+ const names = {
104
+ name: effect.state.name ?? "",
105
+ autoName: effect.state.autoName ?? ""
106
+ };
107
+ mutateSessions((current) => patchSessionNames(current, machine, sessionId, names), { revalidate: false });
108
+ break;
109
+ }
110
+ case "notice": setNotice({
111
+ text: effect.text,
112
+ warn: effect.warn
113
+ });
114
+ }
115
+ }, [
116
+ machine,
117
+ sessionId,
118
+ mutate,
119
+ mutateSessions,
120
+ notify,
121
+ onCleared,
122
+ t
123
+ ]);
124
+ const postMessage = useCallback(async (text, pastes, images) => {
125
+ try {
126
+ const { data, error } = await api.sendMessage(machine, sessionId, {
127
+ text,
128
+ ...pasteRefs(pastes),
129
+ ...images ? { images } : {}
130
+ });
131
+ if (error) {
132
+ sendUnreachable.current = isUnreachableError(error);
133
+ return { error: describeError(error) };
134
+ }
135
+ return {
136
+ turnId: data?.turnId,
137
+ queued: data?.queued
138
+ };
139
+ } catch (error) {
140
+ return { error: describeError(error) };
141
+ }
142
+ }, [
143
+ api,
144
+ describeError,
145
+ machine,
146
+ sessionId
147
+ ]);
148
+ const withdrawQueued = useCallback(async (turnId) => {
149
+ try {
150
+ const { error } = await api.withdrawQueued(machine, sessionId, turnId);
151
+ return error ? { error: describeError(error) } : {};
152
+ } catch (error) {
153
+ return { error: describeError(error) };
154
+ }
155
+ }, [
156
+ api,
157
+ describeError,
158
+ machine,
159
+ sessionId
160
+ ]);
161
+ const postDirection = useCallback((text, pastes, images) => directionOutcome(() => api.steer(machine, sessionId, {
162
+ text,
163
+ ...pasteRefs(pastes),
164
+ ...images ? { images } : {}
165
+ }), t("detail.steerUncertain"), describeError), [
166
+ api,
167
+ describeError,
168
+ machine,
169
+ sessionId,
170
+ t
171
+ ]);
172
+ const withdrawDirection = useCallback((noteId) => withdrawalOutcome(noteId, () => api.withdrawDirection(machine, sessionId, [noteId]), t("detail.steerAlreadyRead"), describeError), [
173
+ api,
174
+ describeError,
175
+ machine,
176
+ sessionId,
177
+ t
178
+ ]);
179
+ const compactionNotice = useCompactionNotice();
180
+ const recapNotice = useRecapNotice();
181
+ const words = useTranscriptWords();
182
+ const imageUrl = useCallback((ref) => sessionImageUrl(machine, sessionId, ref), [machine, sessionId]);
183
+ const { transcript, sending, onEvent: applyEvent, sendMessage: sendToTranscript, resolveApproval, noteShellRun, canRemoveQueued, removeQueued: removeFromTranscript, takeBackPending, cursor } = usePwCodeTranscript({
184
+ sessionId,
185
+ detail,
186
+ send: postMessage,
187
+ steer: postDirection,
188
+ withdraw: withdrawQueued,
189
+ withdrawDirection,
190
+ onEffect: runEffect,
191
+ ...goalNotice ? { goalNotice } : {},
192
+ compactionNotice,
193
+ recapNotice,
194
+ words,
195
+ imageUrl
196
+ });
197
+ /** Resolves to the refusal and whether it was the machine not answering, or null once the session took the message. */
198
+ const deliver = useCallback(async (text, options) => {
199
+ sendUnreachable.current = false;
200
+ const refusal = await sendToTranscript(text, options);
201
+ return refusal === null ? null : {
202
+ text: refusal,
203
+ unreachable: sendUnreachable.current
204
+ };
205
+ }, [sendToTranscript]);
206
+ const removeQueued = useCallback(async (id) => {
207
+ const refusal = await removeFromTranscript(id);
208
+ if (refusal) setNotice({
209
+ text: refusal,
210
+ warn: true
211
+ });
212
+ }, [removeFromTranscript]);
213
+ const answerApproval = useCallback(async (approvalId, answer) => {
214
+ const refusal = await api.answerApproval(machine, sessionId, approvalId, answer);
215
+ if (refusal) {
216
+ showError(refusal);
217
+ return;
218
+ }
219
+ setNotice(null);
220
+ resolveApproval(approvalId);
221
+ }, [
222
+ api,
223
+ showError,
224
+ resolveApproval,
225
+ machine,
226
+ sessionId
227
+ ]);
228
+ const { subagents, refresh: refreshSubagents } = api.useSubagents(machine, sessionId, !!detail && detail.status !== "live_elsewhere");
229
+ const feedListeners = useRef(/* @__PURE__ */ new Set());
230
+ const subscribe = useCallback((listener) => {
231
+ feedListeners.current.add(listener);
232
+ return () => {
233
+ feedListeners.current.delete(listener);
234
+ };
235
+ }, []);
236
+ const [mainTurn, setMainTurn] = useState(null);
237
+ const childTurns = useRef(/* @__PURE__ */ new Set());
238
+ const onEvent = useCallback((ev) => {
239
+ applyEvent(ev);
240
+ for (const listener of feedListeners.current) listener(ev);
241
+ const said = mainTurnAfter(ev);
242
+ if (said !== void 0) setMainTurn(said);
243
+ const childTurn = ev.id ? ev.turnId : void 0;
244
+ const started = !!childTurn && !childTurns.current.has(childTurn);
245
+ if (childTurn) childTurns.current.add(childTurn);
246
+ if (started || changesSubagents(ev)) refreshSubagents();
247
+ }, [applyEvent, refreshSubagents]);
248
+ const stopSubagent = useCallback(async (id) => {
249
+ const refusal = await api.stopSubagent(machine, sessionId, id);
250
+ if (refusal) showError(refusal);
251
+ }, [
252
+ api,
253
+ machine,
254
+ sessionId,
255
+ showError
256
+ ]);
257
+ const stopAllSubagents = useCallback(async () => {
258
+ const refusal = await api.stopAllSubagents(machine, sessionId);
259
+ if (refusal) showError(refusal);
260
+ }, [
261
+ api,
262
+ machine,
263
+ sessionId,
264
+ showError
265
+ ]);
266
+ const goal = liveState ? liveState.goal : detail?.goal;
267
+ const addDirs = liveState ? liveState.addDirs : detail?.addDirs;
268
+ const allowedDirs = liveState ? liveState.allowedDirs : detail?.allowedDirs;
269
+ const steered = new Set(transcript ? [...transcript.notes, ...transcript.steered].map((m) => m.id) : []);
270
+ const mainWaits = !!transcript && pendingApprovals(transcript).some((p) => !p.agent);
271
+ const mainRuns = mainTurn ?? !!detail?.turnId;
272
+ const mainState = mainWaits ? "approval" : mainRuns ? "running" : "idle";
273
+ return {
274
+ /** The session as the listing has it, or as its fetch does until then. */
275
+ session,
276
+ detail,
277
+ /** The session's state as its last state frame said, until which the detail stands. */
278
+ liveState,
279
+ goal,
280
+ addDirs,
281
+ allowedDirs,
282
+ refetch: mutate,
283
+ transcript,
284
+ ...transcriptMessages(transcript),
285
+ sending,
286
+ /** Hands each frame of the session's feed to the transcript and the subagent views. */
287
+ onEvent,
288
+ /** Where the feed resumes from. */
289
+ cursor,
290
+ /** Hands every frame of the feed to `listener` until the returned call, as a subagent's view reads it. */
291
+ subscribe,
292
+ notice,
293
+ dismissNotice,
294
+ warn,
295
+ showError,
296
+ /** Takes back a notice that the machine could not be reached, once it answers. */
297
+ reached,
298
+ deliver,
299
+ noteShellRun,
300
+ canRemoveQueued,
301
+ removeQueued,
302
+ /** Takes back every message the machine still holds, with the first refusal. */
303
+ takeBackPending,
304
+ /** Whether a queued message goes into the running turn's next step or waits for its reply. */
305
+ queueDelivery: (id) => steered.has(id) ? "nextStep" : "afterReply",
306
+ answerApproval,
307
+ subagents,
308
+ refreshSubagents,
309
+ stopSubagent,
310
+ stopAllSubagents,
311
+ mainState
312
+ };
313
+ }
314
+ export { directionOutcome, transcriptMessages, usePwCodeConversation, withdrawalOutcome };
@@ -0,0 +1,104 @@
1
+ import type { ApprovalAnswerValue, MessagePaste } from '@parallelworks/ui/ai/headless';
2
+ import { type PwCodeSwitcherAgent } from './agentSwitcher.js';
3
+ import type { Schemas } from './apiClient.js';
4
+ import type { PwCodeApi } from './createPwCodeApi.js';
5
+ import type { PwCodeSubagentUsage } from './types.js';
6
+ declare const nextStep: (_id: string) => 'nextStep' | 'afterReply';
7
+ /** One subagent's conversation in place of the main one: its transcript, kept
8
+ * current from the session's feed, and a composer that talks to it. Commands
9
+ * and `!` stay with the main conversation's composer. The host reads the
10
+ * subagent with `api.useSubagentDetail`. */
11
+ export declare function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, listed, usage, subscribe, loadPalette, describeError, sessionLock, modelNames, onSent, }: {
12
+ api: PwCodeApi;
13
+ machine: string;
14
+ sessionId: string;
15
+ subId: string;
16
+ /** The subagent, as `api.useSubagentDetail` reads it. */
17
+ subagent: {
18
+ data: Schemas['SubagentDetail'] | undefined;
19
+ error?: unknown;
20
+ refresh: () => void;
21
+ };
22
+ /** Its row in the session's switcher, which the feed keeps current; its own read stands in until the list has it. */
23
+ listed: PwCodeSwitcherAgent | undefined;
24
+ /** Its tokens as the session's feed last counted them. */
25
+ usage: PwCodeSubagentUsage | undefined;
26
+ /** Hands over each frame of the session's feed until the returned call: the main conversation's `subscribe`. */
27
+ subscribe: (listener: (ev: Schemas['AgentStreamEvent']) => void) => () => void;
28
+ /** The session's palette, which says what typed text is a command. */
29
+ loadPalette: () => Promise<Schemas['AgentPalette'] | null>;
30
+ /** Words a refusal or failure for the reader. */
31
+ describeError: (error: unknown) => string;
32
+ /** Why nothing can be sent to the session at all, such as an unreachable machine. */
33
+ sessionLock: {
34
+ placeholder: string;
35
+ hint: string;
36
+ } | null;
37
+ /** Names the session gives its models, as its state frames carry them. */
38
+ modelNames?: Readonly<Record<string, string>> | undefined;
39
+ /** The subagent took a message, so the session's list of them reads differently. */
40
+ onSent: () => void;
41
+ }): {
42
+ messages: import("@parallelworks/ui/ai/headless").ChatMessage[];
43
+ queued: import("@parallelworks/ui/ai/headless").ChatMessage[];
44
+ all: import("@parallelworks/ui/ai/headless").ChatMessage[];
45
+ /** The subagent as its own view shows it; unset until it is listed or read. */
46
+ agent: PwCodeSwitcherAgent | undefined;
47
+ /** The composer's draft key, under its session's and apart from the main conversation's. */
48
+ draftKey: string;
49
+ /** The model it runs on; empty until it is read, or when it names none. */
50
+ model: string;
51
+ /** That model's name as the session gives it, or its id without the provider. */
52
+ modelLabel: string;
53
+ transcript: import("./transcript.js").TranscriptState | null;
54
+ sending: boolean;
55
+ running: boolean;
56
+ approvals: import("@parallelworks/ui/ai/headless").ApprovalPart[];
57
+ notice: string | null;
58
+ dismissNotice: () => void;
59
+ /** Sends what was typed; false hands it back to the composer. */
60
+ send: (typed: string, sent?: MessagePaste[]) => Promise<boolean>;
61
+ canRemoveQueued: (id: string) => boolean;
62
+ removeQueued: (id: string) => Promise<void>;
63
+ /** The composer's `recall`: ↑ in it, or Edit under the queue, takes back what waits. */
64
+ recall: {
65
+ available: boolean;
66
+ take: () => Promise<{
67
+ text: string;
68
+ pastes: MessagePaste[] | undefined;
69
+ }[]>;
70
+ };
71
+ showAuthor: boolean;
72
+ /** The subagent has yet to load for the first time. */
73
+ loading: boolean;
74
+ /** Shown in place of a transcript that never loaded: why, or undefined
75
+ * for the host's own line. */
76
+ failed: {
77
+ message: string | undefined;
78
+ } | null;
79
+ /** Whether a queued message goes into the running turn's next step or waits for its reply. */
80
+ queueDelivery: typeof nextStep;
81
+ /** The composer's activity line while the subagent's turn runs; until its
82
+ * read lands, timed from when its row in the list says it started. */
83
+ activity: {
84
+ kind: 'working';
85
+ startedAt: string | null;
86
+ inputTokens: number | undefined;
87
+ outputTokens: number | undefined;
88
+ word: string | undefined;
89
+ } | null;
90
+ turn: {
91
+ running: boolean;
92
+ stop: () => Promise<void>;
93
+ stopping: boolean;
94
+ };
95
+ answerApproval: (approvalId: string, answer: ApprovalAnswerValue) => Promise<void>;
96
+ composer: {
97
+ placeholder: string;
98
+ hint: string;
99
+ locked: boolean;
100
+ disabled: boolean;
101
+ };
102
+ };
103
+ export type PwCodeSubagent = ReturnType<typeof usePwCodeSubagent>;
104
+ export {};
@@ -0,0 +1,212 @@
1
+ import { switcherAgent, useAgentTypeLabel } from "./agentSwitcher.js";
2
+ import { shellCommand, slashAction } from "./command.js";
3
+ import { sessionImageUrl } from "./images.js";
4
+ import { loadFailure } from "./loadError.js";
5
+ import { usePwCodeTranslations } from "./messages.js";
6
+ import { useTranscriptWords } from "./notices.js";
7
+ import { pendingApprovals, subagentSessionDetail, turnRunning } from "./transcript.js";
8
+ import { directionOutcome, transcriptMessages, withdrawalOutcome } from "./useConversation.js";
9
+ import { usePwCodeTranscript } from "./useTranscript.js";
10
+ import { modelLabel } from "./models.js";
11
+ import { sessionDraftKey, workingActivity } from "./sessionScreen.js";
12
+ import { pasteRefs } from "./sessionsApi.js";
13
+ import { composerState } from "./wording.js";
14
+ import { useCallback, useEffect, useMemo, useState } from "react";
15
+ // src/useSubagent.ts
16
+ var nextStep = (_id) => "nextStep";
17
+ /** One subagent's conversation in place of the main one: its transcript, kept
18
+ * current from the session's feed, and a composer that talks to it. Commands
19
+ * and `!` stay with the main conversation's composer. The host reads the
20
+ * subagent with `api.useSubagentDetail`. */
21
+ function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, listed, usage, subscribe, loadPalette, describeError, sessionLock, modelNames, onSent }) {
22
+ const t = usePwCodeTranslations("agents");
23
+ const typeLabel = useAgentTypeLabel();
24
+ const { data, error, refresh } = subagent;
25
+ const known = listed ?? (data ? switcherAgent(data, usage) : void 0);
26
+ const name = known ? typeLabel(known.agentType) : "";
27
+ const detail = useMemo(() => data ? subagentSessionDetail(data) : void 0, [data]);
28
+ const [notice, setNotice] = useState(null);
29
+ const postMessage = useCallback(async (text, sent) => {
30
+ try {
31
+ const { data: accepted, error: refusal } = await api.messageSubagent(machine, sessionId, subId, {
32
+ text,
33
+ ...pasteRefs(sent)
34
+ });
35
+ return refusal ? { error: describeError(refusal) } : { turnId: accepted?.turnId };
36
+ } catch (thrown) {
37
+ return { error: describeError(thrown) };
38
+ }
39
+ }, [
40
+ api,
41
+ describeError,
42
+ machine,
43
+ sessionId,
44
+ subId
45
+ ]);
46
+ const postDirection = useCallback((text, sent) => directionOutcome(() => api.steerSubagent(machine, sessionId, subId, {
47
+ text,
48
+ ...pasteRefs(sent)
49
+ }), t("detail.steerUncertain"), describeError), [
50
+ api,
51
+ describeError,
52
+ machine,
53
+ sessionId,
54
+ subId,
55
+ t
56
+ ]);
57
+ const withdrawDirection = useCallback((noteId) => withdrawalOutcome(noteId, () => api.withdrawSubagentDirection(machine, sessionId, subId, [noteId]), t("detail.steerAlreadyRead"), describeError), [
58
+ api,
59
+ describeError,
60
+ machine,
61
+ sessionId,
62
+ subId,
63
+ t
64
+ ]);
65
+ const runEffect = useCallback((effect) => {
66
+ if (effect.type === "refetch") refresh();
67
+ }, [refresh]);
68
+ const words = useTranscriptWords();
69
+ const imageUrl = useCallback((ref) => sessionImageUrl(machine, sessionId, ref), [machine, sessionId]);
70
+ const { transcript, sending, onEvent, sendMessage: sendToTranscript, resolveApproval, canRemoveQueued, removeQueued: removeFromTranscript, takeBackPending } = usePwCodeTranscript({
71
+ subagent: subId,
72
+ detail,
73
+ send: postMessage,
74
+ steer: postDirection,
75
+ withdrawDirection,
76
+ onEffect: runEffect,
77
+ words,
78
+ imageUrl
79
+ });
80
+ useEffect(() => subscribe(onEvent), [subscribe, onEvent]);
81
+ const removeQueued = useCallback(async (id) => {
82
+ const refusal = await removeFromTranscript(id);
83
+ if (refusal) setNotice(refusal);
84
+ }, [removeFromTranscript]);
85
+ const takeBack = useCallback(async () => {
86
+ const { taken, refusal } = await takeBackPending();
87
+ if (refusal) setNotice(refusal);
88
+ return taken.map(({ text, pastes }) => ({
89
+ text,
90
+ pastes
91
+ }));
92
+ }, [takeBackPending]);
93
+ const send = useCallback(async (typed, sent) => {
94
+ if (shellCommand(typed) !== null || typed.trimStart().startsWith("/") && slashAction(typed, await loadPalette().catch(() => null)).kind !== "message") {
95
+ setNotice(t("switcher.commandsOnMain"));
96
+ return false;
97
+ }
98
+ const refusal = await sendToTranscript(typed, { pastes: sent });
99
+ setNotice(refusal);
100
+ if (!refusal) onSent();
101
+ return !refusal;
102
+ }, [
103
+ loadPalette,
104
+ onSent,
105
+ sendToTranscript,
106
+ t
107
+ ]);
108
+ const [stopping, setStopping] = useState(false);
109
+ const stop = useCallback(async () => {
110
+ setStopping(true);
111
+ const refusal = await api.stopSubagent(machine, sessionId, subId);
112
+ setStopping(false);
113
+ setNotice(refusal ? describeError(refusal) : null);
114
+ }, [
115
+ api,
116
+ describeError,
117
+ machine,
118
+ sessionId,
119
+ subId
120
+ ]);
121
+ const answerApproval = useCallback(async (approvalId, answer) => {
122
+ const refusal = await api.answerApproval(machine, sessionId, approvalId, answer);
123
+ if (refusal) {
124
+ setNotice(describeError(refusal));
125
+ return;
126
+ }
127
+ setNotice(null);
128
+ resolveApproval(approvalId);
129
+ }, [
130
+ api,
131
+ describeError,
132
+ machine,
133
+ resolveApproval,
134
+ sessionId
135
+ ]);
136
+ const dismissNotice = useCallback(() => setNotice(null), []);
137
+ const running = transcript ? turnRunning(transcript) : known?.status === "running";
138
+ const agent = known && running && known.status !== "running" ? {
139
+ ...known,
140
+ status: "running",
141
+ endedAt: void 0
142
+ } : known;
143
+ const approvals = transcript ? pendingApprovals(transcript) : [];
144
+ const composer = sessionLock ? {
145
+ ...sessionLock,
146
+ locked: true
147
+ } : approvals.length > 0 ? composerState({
148
+ unreachable: false,
149
+ archived: false,
150
+ machineName: "",
151
+ staleFor: "",
152
+ status: "awaiting_approval",
153
+ liveHost: void 0,
154
+ approvals: approvals.map((p) => ({ kind: p.approvalKind })),
155
+ t
156
+ }) : {
157
+ placeholder: t("switcher.composer", { name }),
158
+ hint: running ? t("switcher.steerHint") : "",
159
+ locked: false
160
+ };
161
+ const messages = transcriptMessages(transcript);
162
+ const working = running && !sessionLock;
163
+ const model = data?.model ?? "";
164
+ return {
165
+ /** The subagent as its own view shows it; unset until it is listed or read. */
166
+ agent,
167
+ /** The composer's draft key, under its session's and apart from the main conversation's. */
168
+ draftKey: `${sessionDraftKey(sessionId, void 0)}:${subId}`,
169
+ /** The model it runs on; empty until it is read, or when it names none. */
170
+ model,
171
+ /** That model's name as the session gives it, or its id without the provider. */
172
+ modelLabel: modelLabel(model, modelNames?.[model]),
173
+ transcript,
174
+ ...messages,
175
+ sending,
176
+ running,
177
+ approvals,
178
+ notice,
179
+ dismissNotice,
180
+ /** Sends what was typed; false hands it back to the composer. */
181
+ send,
182
+ canRemoveQueued,
183
+ removeQueued,
184
+ /** The composer's `recall`: ↑ in it, or Edit under the queue, takes back what waits. */
185
+ recall: {
186
+ available: messages.queued.some((m) => canRemoveQueued(m.id)),
187
+ take: takeBack
188
+ },
189
+ showAuthor: messages.all.some((m) => m.author),
190
+ /** The subagent has yet to load for the first time. */
191
+ loading: !data && !error,
192
+ /** Shown in place of a transcript that never loaded: why, or undefined
193
+ * for the host's own line. */
194
+ failed: loadFailure(error, !!data, describeError),
195
+ /** Whether a queued message goes into the running turn's next step or waits for its reply. */
196
+ queueDelivery: nextStep,
197
+ /** The composer's activity line while the subagent's turn runs; until its
198
+ * read lands, timed from when its row in the list says it started. */
199
+ activity: working ? workingActivity(transcript ?? { turnStartedAt: known?.startedAt ?? null }, usage) : null,
200
+ turn: {
201
+ running: working,
202
+ stop,
203
+ stopping
204
+ },
205
+ answerApproval,
206
+ composer: {
207
+ ...composer,
208
+ disabled: sending || composer.locked || !data
209
+ }
210
+ };
211
+ }
212
+ export { usePwCodeSubagent };
@@ -7,9 +7,11 @@ export type PwCodeSendResult = {
7
7
  } | {
8
8
  error: string;
9
9
  };
10
- /** lost: no answer came, so the direction may have reached the turn. */
10
+ /** lost: no answer came, so the direction may have reached the turn. id takes
11
+ * a delivered direction back; older machines name none. */
11
12
  export type PwCodeSteerResult = {
12
13
  delivered: boolean;
14
+ id?: string | undefined;
13
15
  } | {
14
16
  error: string;
15
17
  } | {
@@ -18,8 +20,17 @@ export type PwCodeSteerResult = {
18
20
  export type PwCodeWithdrawResult = {
19
21
  error?: string;
20
22
  };
23
+ /** A pending message taken back before the model read it, as it was sent. */
24
+ export interface PwCodeTakenBack {
25
+ text: string;
26
+ pastes?: MessagePaste[] | undefined;
27
+ images?: PwCodeImageRef[] | undefined;
28
+ previews?: PwCodeImage[] | undefined;
29
+ }
21
30
  interface SendOptions {
22
31
  steer?: boolean;
32
+ /** What was typed, when the text is what a command resolved it to, such as /plan's prompt; taken back, it returns as typed. */
33
+ typed?: string | undefined;
23
34
  pastes?: MessagePaste[] | undefined;
24
35
  images?: PwCodeImageRef[] | undefined;
25
36
  /** Drawn on the message until its echo brings the daemon's; a note can wait a whole tool call for that. */
@@ -27,7 +38,7 @@ interface SendOptions {
27
38
  }
28
39
  /** Holds the live transcript for one session. The host still owns the socket
29
40
  * and the fetch: it feeds events to `onEvent` and posts through `send`. */
30
- export declare function usePwCodeTranscript({ sessionId, subagent, detail, send, steer, withdraw, onEffect, goalNotice, compactionNotice, recapNotice, words, imageUrl, }: {
41
+ export declare function usePwCodeTranscript({ sessionId, subagent, detail, send, steer, withdraw, withdrawDirection, onEffect, goalNotice, compactionNotice, recapNotice, words, imageUrl, }: {
31
42
  /** The session shown, so frames from the conversation it cleared are dropped. */
32
43
  sessionId?: string | undefined;
33
44
  /** Shows this subagent's conversation instead of the main one: the frames
@@ -39,6 +50,8 @@ export declare function usePwCodeTranscript({ sessionId, subagent, detail, send,
39
50
  steer?: (text: string, pastes?: MessagePaste[], images?: PwCodeImageRef[]) => Promise<PwCodeSteerResult>;
40
51
  /** Takes back a queued message, by the turn it was accepted as. */
41
52
  withdraw?: (turnId: string) => Promise<PwCodeWithdrawResult>;
53
+ /** Takes back a steered message by the id steering named it; refused once the model read it. */
54
+ withdrawDirection?: (noteId: string) => Promise<PwCodeWithdrawResult>;
42
55
  onEffect: (effect: StreamEffect) => void;
43
56
  goalNotice?: GoalNotice;
44
57
  compactionNotice?: CompactionNotice;
@@ -53,10 +66,17 @@ export declare function usePwCodeTranscript({ sessionId, subagent, detail, send,
53
66
  sendMessage: (text: string, options?: SendOptions) => Promise<string | null>;
54
67
  resolveApproval: (approvalId: string) => void;
55
68
  noteShellRun: (command: string, output: string) => void;
56
- /** Queued messages the daemon has named a turn for can be taken back. */
69
+ /** Pending messages the daemon named a turn or note for can be taken back
70
+ * until they reach the model. */
57
71
  canRemoveQueued: (id: string) => boolean;
58
72
  /** Resolves to the refusal, or null once the message is gone. */
59
73
  removeQueued: (id: string) => Promise<string | null>;
74
+ /** Takes back every pending message the machine still holds, with the first
75
+ * refusal; one the model read meanwhile stays sent. */
76
+ takeBackPending: () => Promise<{
77
+ taken: PwCodeTakenBack[];
78
+ refusal: string | null;
79
+ }>;
60
80
  /** Where a reconnect resumes from: the last seq applied, read outside render. */
61
81
  cursor: () => number;
62
82
  };