@parallelworks/code 0.3.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 (103) hide show
  1. package/README.md +598 -113
  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 +3 -3
  7. package/dist/ago.js +10 -10
  8. package/dist/allocations.d.ts +41 -0
  9. package/dist/allocations.js +76 -0
  10. package/dist/api.d.ts +1080 -11
  11. package/dist/chatStrings.d.ts +188 -0
  12. package/dist/chatStrings.js +217 -0
  13. package/dist/claudeAccounts.d.ts +38 -1
  14. package/dist/claudeAccounts.js +98 -4
  15. package/dist/claudeApi.js +1 -1
  16. package/dist/claudeSignIn.d.ts +19 -1
  17. package/dist/claudeSignIn.js +12 -2
  18. package/dist/commandsApi.d.ts +11 -1
  19. package/dist/commandsApi.js +24 -5
  20. package/dist/createPwCodeApi.d.ts +44 -5
  21. package/dist/createPwCodeApi.js +18 -2
  22. package/dist/directories.d.ts +161 -0
  23. package/dist/directories.js +301 -0
  24. package/dist/goal.d.ts +89 -0
  25. package/dist/goal.js +164 -0
  26. package/dist/imageFit.d.ts +23 -0
  27. package/dist/imageFit.js +27 -0
  28. package/dist/images.d.ts +28 -0
  29. package/dist/images.js +38 -6
  30. package/dist/index.d.ts +27 -12
  31. package/dist/index.js +26 -12
  32. package/dist/loadError.d.ts +8 -0
  33. package/dist/loadError.js +19 -0
  34. package/dist/locales/en/agentTranscript.js +73 -12
  35. package/dist/locales/en/agents.js +71 -9
  36. package/dist/locales/en.d.ts +124 -8
  37. package/dist/locales/es/agentTranscript.js +73 -12
  38. package/dist/locales/es/agents.js +71 -9
  39. package/dist/locales/ja/agentTranscript.js +76 -15
  40. package/dist/locales/ja/agents.js +45 -120
  41. package/dist/locales/ko/agentTranscript.js +73 -12
  42. package/dist/locales/ko/agents.js +71 -9
  43. package/dist/locales/zh/agentTranscript.js +71 -10
  44. package/dist/locales/zh/agents.js +71 -9
  45. package/dist/machine.d.ts +2 -0
  46. package/dist/modelPicker.d.ts +79 -0
  47. package/dist/modelPicker.js +107 -0
  48. package/dist/notices.js +47 -19
  49. package/dist/platformDefaults.d.ts +22 -0
  50. package/dist/platformDefaults.js +30 -0
  51. package/dist/preferences.d.ts +78 -0
  52. package/dist/preferences.js +128 -0
  53. package/dist/pullRequestList.d.ts +10 -2
  54. package/dist/pullRequestList.js +41 -22
  55. package/dist/query.d.ts +6 -2
  56. package/dist/query.js +85 -10
  57. package/dist/session.d.ts +5 -2
  58. package/dist/session.js +12 -8
  59. package/dist/sessionActions.d.ts +11 -1
  60. package/dist/sessionActions.js +14 -6
  61. package/dist/sessionEvents.d.ts +8 -3
  62. package/dist/sessionEvents.js +10 -5
  63. package/dist/sessionGroups.d.ts +3 -2
  64. package/dist/sessionGroups.js +4 -3
  65. package/dist/sessionList.d.ts +57 -9
  66. package/dist/sessionList.js +74 -12
  67. package/dist/sessionScreen.d.ts +193 -0
  68. package/dist/sessionScreen.js +213 -0
  69. package/dist/sessionsApi.d.ts +13 -3
  70. package/dist/sessionsApi.js +88 -29
  71. package/dist/settingsApi.d.ts +3 -1
  72. package/dist/startPage.d.ts +153 -0
  73. package/dist/startPage.js +174 -0
  74. package/dist/startSession.d.ts +41 -7
  75. package/dist/startSession.js +26 -4
  76. package/dist/transcript.js +48 -15
  77. package/dist/types.d.ts +11 -1
  78. package/dist/useComposer.d.ts +25 -1
  79. package/dist/useComposer.js +54 -3
  80. package/dist/useComposerImages.d.ts +5 -0
  81. package/dist/useComposerImages.js +24 -1
  82. package/dist/useComposerPastes.d.ts +70 -0
  83. package/dist/useComposerPastes.js +130 -0
  84. package/dist/useConversation.d.ts +10 -1
  85. package/dist/useConversation.js +32 -5
  86. package/dist/useSubagent.d.ts +49 -3
  87. package/dist/useSubagent.js +70 -7
  88. package/dist/useTranscript.d.ts +23 -3
  89. package/dist/useTranscript.js +76 -19
  90. package/dist/wording.js +2 -2
  91. package/dist/workingDirectories.d.ts +31 -0
  92. package/dist/workingDirectories.js +25 -1
  93. package/locales/en/agentTranscript.json +67 -11
  94. package/locales/en/agents.json +68 -8
  95. package/locales/es/agentTranscript.json +67 -11
  96. package/locales/es/agents.json +68 -8
  97. package/locales/ja/agentTranscript.json +70 -14
  98. package/locales/ja/agents.json +68 -8
  99. package/locales/ko/agentTranscript.json +67 -11
  100. package/locales/ko/agents.json +68 -8
  101. package/locales/zh/agentTranscript.json +65 -9
  102. package/locales/zh/agents.json +68 -8
  103. package/package.json +6 -3
@@ -23,6 +23,14 @@ function nextImageSeq(texts, after) {
23
23
  }
24
24
  return seq + 1;
25
25
  }
26
+ /** The send appends the placeholders of images its text left out; a message
27
+ * taken back gives them back as images, so they leave its text. */
28
+ function withoutAppendedImages(text, images) {
29
+ let rest = text;
30
+ for (const { placeholder } of (images ?? []).toReversed()) if (rest === placeholder) rest = "";
31
+ else if (rest.endsWith(` ${placeholder}`)) rest = rest.slice(0, -placeholder.length - 1);
32
+ return rest;
33
+ }
26
34
  /** Images stay with the reader until there is a session to save them with. */
27
35
  function useComposerImages({ api, machine, sessionId, messages, onError, describeError, encode, preview, release }) {
28
36
  const t = usePwCodeTranslations("agents");
@@ -189,7 +197,22 @@ function useComposerImages({ api, machine, sessionId, messages, onError, describ
189
197
  }
190
198
  };
191
199
  }, [releasePreview]),
200
+ restore: useCallback((saved) => {
201
+ if (saved.length === 0) return;
202
+ lastSeq.current = nextImageSeq(saved.map((s) => s.ref.placeholder), lastSeq.current) - 1;
203
+ const restored = saved.map((image) => {
204
+ const { placeholder } = image.ref;
205
+ uploads.current.set(placeholder, Promise.resolve(image));
206
+ return {
207
+ key: placeholder,
208
+ placeholder,
209
+ previewUrl: `data:${image.preview.mime};base64,${image.preview.data}`,
210
+ saved: true
211
+ };
212
+ });
213
+ setImages((current) => [...restored, ...current]);
214
+ }, []),
192
215
  saveTo
193
216
  };
194
217
  }
195
- export { IMAGE_MAX_BYTES, IMAGE_MAX_SIDE, IMAGE_READ_MAX_BYTES, IMAGE_TYPES, PwCodeImageTooLarge, nextImageSeq, useComposerImages };
218
+ export { IMAGE_MAX_BYTES, IMAGE_MAX_SIDE, IMAGE_READ_MAX_BYTES, IMAGE_TYPES, PwCodeImageTooLarge, nextImageSeq, useComposerImages, withoutAppendedImages };
@@ -0,0 +1,70 @@
1
+ import { type ComposerPastes, type MessagePaste, type PasteCard } from '@parallelworks/ui/ai/headless';
2
+ import type { Schemas } from './apiClient.js';
3
+ import type { PwCodeChatStrings } from './chatStrings.js';
4
+ import type { PwCodeApi } from './createPwCodeApi.js';
5
+ import type { PwCodeSessionState } from './types.js';
6
+ /** Where a session's large pastes are saved, and the size past which one is.
7
+ * A live session's own limit stands, and a live session that reports none
8
+ * predates paste uploads, so its pastes stay text. Before the session is
9
+ * live, the context window of the model read of it sets the limit once the
10
+ * platform's models have loaded; until then every paste stays text. */
11
+ export declare function useComposerPastes(api: Pick<PwCodeApi, 'uploadPaste'> & {
12
+ /** The package's, or a host's list it already holds. */
13
+ usePlatformModels: () => {
14
+ models: readonly Pick<Schemas['ModelEntry'], 'id' | 'context_window'>[];
15
+ };
16
+ }, { machine, sessionId, liveState, detail, describeError, }: {
17
+ machine: string;
18
+ sessionId: string;
19
+ /** What the session reported while live, as `usePwCodeConversation` holds it; null before. */
20
+ liveState: Pick<PwCodeSessionState, 'pasteInlineMaxBytes'> | null;
21
+ /** The session as `api.useSessionDetail` read it. */
22
+ detail: Pick<Schemas['AgentSessionDetail'], 'model'> | undefined;
23
+ /** A failed save in the reader's language. */
24
+ describeError: (error: unknown) => string;
25
+ }): ComposerPastes | undefined;
26
+ /** A send's share of the composer: the message, which names each saved
27
+ * paste after the text, and the pastes it names. */
28
+ export interface PwCodePasteSend {
29
+ text: string;
30
+ pastes: MessagePaste[];
31
+ /** Puts the text back before anything typed since, and the cards with it,
32
+ * after a send that failed. False, putting nothing back, once the composer
33
+ * is another or gone, so the host can keep the text as that one's draft. */
34
+ putBack: () => boolean;
35
+ }
36
+ export interface PwCodePasteCards {
37
+ /** The pastes waiting as cards, in the order they were pasted. */
38
+ cards: PasteCard[];
39
+ /** A card is still saving or failed to save, which holds the send back
40
+ * until it saves or is removed. */
41
+ blocking: boolean;
42
+ /** Takes a paste: true when it became a card, so the box leaves the text
43
+ * out. Otherwise the box takes it, its line endings made `\n` as
44
+ * `normalizeNewlines` makes them. */
45
+ paste: (text: string) => boolean;
46
+ remove: (key: string) => void;
47
+ /** Empties the box and the cards for a send; null, leaving both, while a
48
+ * card holds the send back. */
49
+ send: () => PwCodePasteSend | null;
50
+ }
51
+ /** A composer's paste cards, for a host that draws its own composer: a paste
52
+ * past the limit becomes a card that saves with the session and goes as its
53
+ * placeholder, and a new limit, such as another model's, moves pastes
54
+ * between the box and the cards. */
55
+ export declare function usePasteCards({ pastes, input, setInput, composer, }: {
56
+ /** As `useComposerPastes` gives them; undefined keeps every paste text. */
57
+ pastes: ComposerPastes | undefined;
58
+ /** What the box holds now. */
59
+ input: string;
60
+ setInput: (value: string) => void;
61
+ /** The composer the cards belong to, such as the session's draft key:
62
+ * another one starts with none. */
63
+ composer: string;
64
+ }): PwCodePasteCards;
65
+ /** A paste card's name, and the line under it: why it failed, else that it is
66
+ * saving, else its lines and size. */
67
+ export declare function pasteCardText(card: PasteCard, words: PwCodeChatStrings['paste']): {
68
+ title: string;
69
+ detail: string;
70
+ };
@@ -0,0 +1,130 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { createPasteCards, joinPastes, pasteInlineMaxBytes } from "@parallelworks/ui/ai/headless";
3
+ import { formatBytes } from "@parallelworks/ui/headless";
4
+ // src/useComposerPastes.ts
5
+ /** Where a session's large pastes are saved, and the size past which one is.
6
+ * A live session's own limit stands, and a live session that reports none
7
+ * predates paste uploads, so its pastes stay text. Before the session is
8
+ * live, the context window of the model read of it sets the limit once the
9
+ * platform's models have loaded; until then every paste stays text. */
10
+ function useComposerPastes(api, { machine, sessionId, liveState, detail, describeError }) {
11
+ const { models } = api.usePlatformModels();
12
+ const contextWindow = models.find((m) => m.id === detail?.model)?.context_window;
13
+ const listedMax = models.length > 0 ? pasteInlineMaxBytes(contextWindow) : void 0;
14
+ const supported = !liveState || liveState.pasteInlineMaxBytes !== void 0;
15
+ const inlineMaxBytes = liveState ? liveState.pasteInlineMaxBytes : listedMax;
16
+ const { uploadPaste } = api;
17
+ const upload = useCallback((text) => uploadPaste(machine, sessionId, text, describeError), [
18
+ uploadPaste,
19
+ machine,
20
+ sessionId,
21
+ describeError
22
+ ]);
23
+ return useMemo(() => supported ? {
24
+ inlineMaxBytes,
25
+ upload
26
+ } : void 0, [
27
+ supported,
28
+ inlineMaxBytes,
29
+ upload
30
+ ]);
31
+ }
32
+ /** A composer's paste cards, for a host that draws its own composer: a paste
33
+ * past the limit becomes a card that saves with the session and goes as its
34
+ * placeholder, and a new limit, such as another model's, moves pastes
35
+ * between the box and the cards. */
36
+ function usePasteCards({ pastes, input, setInput, composer }) {
37
+ const [cards, setCards] = useState([]);
38
+ const latest = useRef({
39
+ pastes,
40
+ input,
41
+ setInput,
42
+ composer,
43
+ cards,
44
+ controller: null
45
+ });
46
+ latest.current = {
47
+ ...latest.current,
48
+ pastes,
49
+ input,
50
+ setInput,
51
+ composer
52
+ };
53
+ const cardsFor = (key) => {
54
+ const controller = createPasteCards({
55
+ pastes: () => latest.current.pastes,
56
+ input: () => latest.current.input,
57
+ setInput: (value) => {
58
+ if (latest.current.controller === controller) {
59
+ latest.current.input = value;
60
+ latest.current.setInput(value);
61
+ }
62
+ },
63
+ onCardsChange: (next) => {
64
+ if (latest.current.controller === controller) {
65
+ latest.current.cards = next;
66
+ setCards(next);
67
+ }
68
+ }
69
+ });
70
+ return {
71
+ composer: key,
72
+ controller
73
+ };
74
+ };
75
+ const [owned, setOwned] = useState(() => cardsFor(composer));
76
+ if (owned.composer !== composer) {
77
+ latest.current.cards = [];
78
+ setCards([]);
79
+ setOwned(cardsFor(composer));
80
+ }
81
+ const { controller } = owned;
82
+ latest.current.controller = controller;
83
+ const inlineMax = pastes?.inlineMaxBytes;
84
+ useEffect(() => {
85
+ if (inlineMax !== void 0) controller.applyInlineLimit(inlineMax);
86
+ }, [inlineMax, controller]);
87
+ const mounted = useRef(false);
88
+ useEffect(() => {
89
+ mounted.current = true;
90
+ return () => {
91
+ mounted.current = false;
92
+ };
93
+ }, []);
94
+ const send = useCallback(() => {
95
+ const { input: sent, composer: from, cards: taken } = latest.current;
96
+ if (taken.some((c) => !c.paste)) return null;
97
+ const saved = controller.takeCards();
98
+ latest.current.input = "";
99
+ latest.current.setInput("");
100
+ return {
101
+ text: joinPastes(sent, saved),
102
+ pastes: saved,
103
+ putBack: () => {
104
+ if (!mounted.current || latest.current.composer !== from) return false;
105
+ const typed = latest.current.input;
106
+ const value = [sent, typed].filter((text) => text.trim()).join("\n\n");
107
+ latest.current.input = value;
108
+ latest.current.setInput(value);
109
+ latest.current.controller?.returnCards(taken);
110
+ return true;
111
+ }
112
+ };
113
+ }, [controller]);
114
+ return {
115
+ cards,
116
+ blocking: cards.some((c) => !c.paste),
117
+ paste: controller.handleTextPaste,
118
+ remove: controller.removeCard,
119
+ send
120
+ };
121
+ }
122
+ /** A paste card's name, and the line under it: why it failed, else that it is
123
+ * saving, else its lines and size. */
124
+ function pasteCardText(card, words) {
125
+ return {
126
+ title: card.paste?.id ? `paste-${card.paste.id}.txt` : words.title,
127
+ detail: card.error ?? (card.paste ? `${words.lines(card.lines)} · ${formatBytes(card.bytes)}` : words.saving)
128
+ };
129
+ }
130
+ export { pasteCardText, useComposerPastes, usePasteCards };
@@ -4,7 +4,7 @@ import type { PwCodeResult, Schemas } from './apiClient.js';
4
4
  import type { PwCodeApi } from './createPwCodeApi.js';
5
5
  import { type GoalNotice, type TranscriptState } from './transcript.js';
6
6
  import type { PwCodeImage, PwCodeImageRef, PwCodeSessionState } from './types.js';
7
- import { type PwCodeSteerResult } from './useTranscript.js';
7
+ import { type PwCodeSteerResult, type PwCodeWithdrawResult } from './useTranscript.js';
8
8
  type Session = Schemas['AgentSession'];
9
9
  type SessionDetail = Schemas['AgentSessionDetail'];
10
10
  type SessionsResponse = Schemas['AgentSessionsResponse'];
@@ -27,6 +27,8 @@ export declare function transcriptMessages(transcript: TranscriptState | null):
27
27
  };
28
28
  /** A direction that got no answer may have landed, so it reads as lost, never as refused. */
29
29
  export declare function directionOutcome(request: () => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>, lost: string, describeError: (error: unknown) => string): Promise<PwCodeSteerResult>;
30
+ /** Taking back a direction is refused once the model read it, and a lost connection refuses it too. */
31
+ export declare function withdrawalOutcome(noteId: string, request: () => Promise<PwCodeResult<Schemas['AgentDirectionWithdrawn']>>, alreadyRead: string, describeError: (error: unknown) => string): Promise<PwCodeWithdrawResult>;
30
32
  /** An open session's conversation: its live transcript, sends routed to the
31
33
  * machine, approvals, the notice above the composer, and its subagents. The
32
34
  * host reads the listing and the session (`api.useSessions`,
@@ -154,6 +156,8 @@ export declare function usePwCodeConversation({ api, machine, sessionId, session
154
156
  reached: () => void;
155
157
  deliver: (text: string, options: {
156
158
  steer?: boolean;
159
+ /** What was typed, when the text is what a command resolved it to. */
160
+ typed?: string | undefined;
157
161
  pastes?: MessagePaste[] | undefined;
158
162
  images?: PwCodeImageRef[] | undefined;
159
163
  previews?: PwCodeImage[] | undefined;
@@ -164,6 +168,11 @@ export declare function usePwCodeConversation({ api, machine, sessionId, session
164
168
  noteShellRun: (command: string, output: string) => void;
165
169
  canRemoveQueued: (id: string) => boolean;
166
170
  removeQueued: (id: string) => Promise<void>;
171
+ /** Takes back every message the machine still holds, with the first refusal. */
172
+ takeBackPending: () => Promise<{
173
+ taken: import("./useTranscript.js").PwCodeTakenBack[];
174
+ refusal: string | null;
175
+ }>;
167
176
  /** Whether a queued message goes into the running turn's next step or waits for its reply. */
168
177
  queueDelivery: (id: string) => 'nextStep' | 'afterReply';
169
178
  answerApproval: (approvalId: string, answer: ApprovalAnswerValue) => Promise<void>;
@@ -29,12 +29,25 @@ function transcriptMessages(transcript) {
29
29
  async function directionOutcome(request, lost, describeError) {
30
30
  try {
31
31
  const { data, error } = await request();
32
- if (!error) return { delivered: !!data?.delivered };
32
+ if (!error) return {
33
+ delivered: !!data?.delivered,
34
+ id: data?.id
35
+ };
33
36
  return steerMayHaveLanded(error) ? { lost } : { error: describeError(error) };
34
37
  } catch {
35
38
  return { lost };
36
39
  }
37
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
+ }
38
51
  /** What a frame says of the main conversation's own turn; null leaves it to the refetched detail, undefined says nothing. */
39
52
  function mainTurnAfter(ev) {
40
53
  if (ev.type === "replay_truncated") return null;
@@ -133,8 +146,12 @@ function usePwCodeConversation({ api, machine, sessionId, sessions, detail: read
133
146
  sessionId
134
147
  ]);
135
148
  const withdrawQueued = useCallback(async (turnId) => {
136
- const { error } = await api.withdrawQueued(machine, sessionId, turnId);
137
- return error ? { error: describeError(error) } : {};
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
+ }
138
155
  }, [
139
156
  api,
140
157
  describeError,
@@ -152,16 +169,24 @@ function usePwCodeConversation({ api, machine, sessionId, sessions, detail: read
152
169
  sessionId,
153
170
  t
154
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
+ ]);
155
179
  const compactionNotice = useCompactionNotice();
156
180
  const recapNotice = useRecapNotice();
157
181
  const words = useTranscriptWords();
158
182
  const imageUrl = useCallback((ref) => sessionImageUrl(machine, sessionId, ref), [machine, sessionId]);
159
- const { transcript, sending, onEvent: applyEvent, sendMessage: sendToTranscript, resolveApproval, noteShellRun, canRemoveQueued, removeQueued: removeFromTranscript, cursor } = usePwCodeTranscript({
183
+ const { transcript, sending, onEvent: applyEvent, sendMessage: sendToTranscript, resolveApproval, noteShellRun, canRemoveQueued, removeQueued: removeFromTranscript, takeBackPending, cursor } = usePwCodeTranscript({
160
184
  sessionId,
161
185
  detail,
162
186
  send: postMessage,
163
187
  steer: postDirection,
164
188
  withdraw: withdrawQueued,
189
+ withdrawDirection,
165
190
  onEffect: runEffect,
166
191
  ...goalNotice ? { goalNotice } : {},
167
192
  compactionNotice,
@@ -274,6 +299,8 @@ function usePwCodeConversation({ api, machine, sessionId, sessions, detail: read
274
299
  noteShellRun,
275
300
  canRemoveQueued,
276
301
  removeQueued,
302
+ /** Takes back every message the machine still holds, with the first refusal. */
303
+ takeBackPending,
277
304
  /** Whether a queued message goes into the running turn's next step or waits for its reply. */
278
305
  queueDelivery: (id) => steered.has(id) ? "nextStep" : "afterReply",
279
306
  answerApproval,
@@ -284,4 +311,4 @@ function usePwCodeConversation({ api, machine, sessionId, sessions, detail: read
284
311
  mainState
285
312
  };
286
313
  }
287
- export { directionOutcome, transcriptMessages, usePwCodeConversation };
314
+ export { directionOutcome, transcriptMessages, usePwCodeConversation, withdrawalOutcome };
@@ -1,11 +1,14 @@
1
1
  import type { ApprovalAnswerValue, MessagePaste } from '@parallelworks/ui/ai/headless';
2
+ import { type PwCodeSwitcherAgent } from './agentSwitcher.js';
2
3
  import type { Schemas } from './apiClient.js';
3
4
  import type { PwCodeApi } from './createPwCodeApi.js';
5
+ import type { PwCodeSubagentUsage } from './types.js';
6
+ declare const nextStep: (_id: string) => 'nextStep' | 'afterReply';
4
7
  /** One subagent's conversation in place of the main one: its transcript, kept
5
8
  * current from the session's feed, and a composer that talks to it. Commands
6
9
  * and `!` stay with the main conversation's composer. The host reads the
7
10
  * subagent with `api.useSubagentDetail`. */
8
- export declare function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, subscribe, loadPalette, describeError, sessionLock, name, onSent, }: {
11
+ export declare function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, listed, usage, subscribe, loadPalette, describeError, sessionLock, modelNames, onSent, }: {
9
12
  api: PwCodeApi;
10
13
  machine: string;
11
14
  sessionId: string;
@@ -13,8 +16,13 @@ export declare function usePwCodeSubagent({ api, machine, sessionId, subId, suba
13
16
  /** The subagent, as `api.useSubagentDetail` reads it. */
14
17
  subagent: {
15
18
  data: Schemas['SubagentDetail'] | undefined;
19
+ error?: unknown;
16
20
  refresh: () => void;
17
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;
18
26
  /** Hands over each frame of the session's feed until the returned call: the main conversation's `subscribe`. */
19
27
  subscribe: (listener: (ev: Schemas['AgentStreamEvent']) => void) => () => void;
20
28
  /** The session's palette, which says what typed text is a command. */
@@ -26,14 +34,22 @@ export declare function usePwCodeSubagent({ api, machine, sessionId, subId, suba
26
34
  placeholder: string;
27
35
  hint: string;
28
36
  } | null;
29
- /** What the composer calls the subagent. */
30
- name: string;
37
+ /** Names the session gives its models, as its state frames carry them. */
38
+ modelNames?: Readonly<Record<string, string>> | undefined;
31
39
  /** The subagent took a message, so the session's list of them reads differently. */
32
40
  onSent: () => void;
33
41
  }): {
34
42
  messages: import("@parallelworks/ui/ai/headless").ChatMessage[];
35
43
  queued: import("@parallelworks/ui/ai/headless").ChatMessage[];
36
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;
37
53
  transcript: import("./transcript.js").TranscriptState | null;
38
54
  sending: boolean;
39
55
  running: boolean;
@@ -42,6 +58,35 @@ export declare function usePwCodeSubagent({ api, machine, sessionId, subId, suba
42
58
  dismissNotice: () => void;
43
59
  /** Sends what was typed; false hands it back to the composer. */
44
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;
45
90
  turn: {
46
91
  running: boolean;
47
92
  stop: () => Promise<void>;
@@ -56,3 +101,4 @@ export declare function usePwCodeSubagent({ api, machine, sessionId, subId, suba
56
101
  };
57
102
  };
58
103
  export type PwCodeSubagent = ReturnType<typeof usePwCodeSubagent>;
104
+ export {};
@@ -1,21 +1,29 @@
1
+ import { switcherAgent, useAgentTypeLabel } from "./agentSwitcher.js";
1
2
  import { shellCommand, slashAction } from "./command.js";
2
3
  import { sessionImageUrl } from "./images.js";
4
+ import { loadFailure } from "./loadError.js";
3
5
  import { usePwCodeTranslations } from "./messages.js";
4
6
  import { useTranscriptWords } from "./notices.js";
5
7
  import { pendingApprovals, subagentSessionDetail, turnRunning } from "./transcript.js";
6
- import { directionOutcome, transcriptMessages } from "./useConversation.js";
8
+ import { directionOutcome, transcriptMessages, withdrawalOutcome } from "./useConversation.js";
7
9
  import { usePwCodeTranscript } from "./useTranscript.js";
10
+ import { modelLabel } from "./models.js";
11
+ import { sessionDraftKey, workingActivity } from "./sessionScreen.js";
8
12
  import { pasteRefs } from "./sessionsApi.js";
9
13
  import { composerState } from "./wording.js";
10
14
  import { useCallback, useEffect, useMemo, useState } from "react";
11
15
  // src/useSubagent.ts
16
+ var nextStep = (_id) => "nextStep";
12
17
  /** One subagent's conversation in place of the main one: its transcript, kept
13
18
  * current from the session's feed, and a composer that talks to it. Commands
14
19
  * and `!` stay with the main conversation's composer. The host reads the
15
20
  * subagent with `api.useSubagentDetail`. */
16
- function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, subscribe, loadPalette, describeError, sessionLock, name, onSent }) {
21
+ function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, listed, usage, subscribe, loadPalette, describeError, sessionLock, modelNames, onSent }) {
17
22
  const t = usePwCodeTranslations("agents");
18
- const { data, refresh } = subagent;
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) : "";
19
27
  const detail = useMemo(() => data ? subagentSessionDetail(data) : void 0, [data]);
20
28
  const [notice, setNotice] = useState(null);
21
29
  const postMessage = useCallback(async (text, sent) => {
@@ -46,21 +54,42 @@ function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, subscribe
46
54
  subId,
47
55
  t
48
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
+ ]);
49
65
  const runEffect = useCallback((effect) => {
50
66
  if (effect.type === "refetch") refresh();
51
67
  }, [refresh]);
52
68
  const words = useTranscriptWords();
53
69
  const imageUrl = useCallback((ref) => sessionImageUrl(machine, sessionId, ref), [machine, sessionId]);
54
- const { transcript, sending, onEvent, sendMessage: sendToTranscript, resolveApproval } = usePwCodeTranscript({
70
+ const { transcript, sending, onEvent, sendMessage: sendToTranscript, resolveApproval, canRemoveQueued, removeQueued: removeFromTranscript, takeBackPending } = usePwCodeTranscript({
55
71
  subagent: subId,
56
72
  detail,
57
73
  send: postMessage,
58
74
  steer: postDirection,
75
+ withdrawDirection,
59
76
  onEffect: runEffect,
60
77
  words,
61
78
  imageUrl
62
79
  });
63
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]);
64
93
  const send = useCallback(async (typed, sent) => {
65
94
  if (shellCommand(typed) !== null || typed.trimStart().startsWith("/") && slashAction(typed, await loadPalette().catch(() => null)).kind !== "message") {
66
95
  setNotice(t("switcher.commandsOnMain"));
@@ -105,7 +134,12 @@ function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, subscribe
105
134
  sessionId
106
135
  ]);
107
136
  const dismissNotice = useCallback(() => setNotice(null), []);
108
- const running = turnRunning(transcript);
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;
109
143
  const approvals = transcript ? pendingApprovals(transcript) : [];
110
144
  const composer = sessionLock ? {
111
145
  ...sessionLock,
@@ -124,9 +158,20 @@ function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, subscribe
124
158
  hint: running ? t("switcher.steerHint") : "",
125
159
  locked: false
126
160
  };
161
+ const messages = transcriptMessages(transcript);
162
+ const working = running && !sessionLock;
163
+ const model = data?.model ?? "";
127
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]),
128
173
  transcript,
129
- ...transcriptMessages(transcript),
174
+ ...messages,
130
175
  sending,
131
176
  running,
132
177
  approvals,
@@ -134,8 +179,26 @@ function usePwCodeSubagent({ api, machine, sessionId, subId, subagent, subscribe
134
179
  dismissNotice,
135
180
  /** Sends what was typed; false hands it back to the composer. */
136
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,
137
200
  turn: {
138
- running: running && !sessionLock,
201
+ running: working,
139
202
  stop,
140
203
  stopping
141
204
  },
@@ -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
  };