@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,218 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { IMAGE_PLACEHOLDER } from "./wording.js";
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+ // src/useComposerImages.ts
5
+ var IMAGE_TYPES = [
6
+ "image/png",
7
+ "image/jpeg",
8
+ "image/gif",
9
+ "image/webp"
10
+ ];
11
+ var IMAGE_MAX_BYTES = 5242880;
12
+ var IMAGE_MAX_SIDE = 8e3;
13
+ /** The terminal refuses to read an image file past this, rather than decode it. */
14
+ var IMAGE_READ_MAX_BYTES = 26214400;
15
+ /** Thrown by a host's `encode` for an image it cannot fit within `IMAGE_MAX_BYTES`. */
16
+ var PwCodeImageTooLarge = class extends Error {};
17
+ /** Numbers past every placeholder the texts name, as the terminal does. */
18
+ function nextImageSeq(texts, after) {
19
+ let seq = after;
20
+ for (const text of texts ?? []) for (const match of text?.matchAll(IMAGE_PLACEHOLDER) ?? []) {
21
+ const n = Number(match[1]);
22
+ if (Number.isSafeInteger(n)) seq = Math.max(seq, n);
23
+ }
24
+ return seq + 1;
25
+ }
26
+ /** 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
+ }
34
+ /** Images stay with the reader until there is a session to save them with. */
35
+ function useComposerImages({ api, machine, sessionId, messages, onError, describeError, encode, preview, release }) {
36
+ const t = usePwCodeTranslations("agents");
37
+ const [images, setImages] = useState([]);
38
+ const [taking, setTaking] = useState(false);
39
+ const imagesRef = useRef(images);
40
+ imagesRef.current = images;
41
+ const messagesRef = useRef(messages);
42
+ messagesRef.current = messages;
43
+ const host = useRef({
44
+ api,
45
+ describeError,
46
+ encode,
47
+ preview,
48
+ release
49
+ });
50
+ host.current = {
51
+ api,
52
+ describeError,
53
+ encode,
54
+ preview,
55
+ release
56
+ };
57
+ const lastSeq = useRef(0);
58
+ const uploads = useRef(/* @__PURE__ */ new Map());
59
+ const staged = useRef(/* @__PURE__ */ new Map());
60
+ const releasePreview = useCallback((url) => {
61
+ host.current.release?.(url);
62
+ }, []);
63
+ const upload = useCallback(async (machine, sessionId, placeholder, file, seq, mime) => {
64
+ const encoded = await host.current.encode(file, mime);
65
+ const { data, error } = await host.current.api.saveImage(machine, sessionId, {
66
+ seq,
67
+ mime: encoded.mime,
68
+ data: encoded.data
69
+ });
70
+ if (error || !data) throw error;
71
+ return {
72
+ ref: {
73
+ placeholder,
74
+ path: data.path,
75
+ mime: encoded.mime
76
+ },
77
+ preview: {
78
+ mime: encoded.mime,
79
+ data: encoded.data
80
+ }
81
+ };
82
+ }, []);
83
+ const mounted = useRef(false);
84
+ useEffect(() => {
85
+ mounted.current = true;
86
+ return () => {
87
+ mounted.current = false;
88
+ for (const image of imagesRef.current) releasePreview(image.previewUrl);
89
+ };
90
+ }, [releasePreview]);
91
+ /** True when the image was still waiting to go with a message. */
92
+ const discard = useCallback((image) => {
93
+ releasePreview(image.previewUrl);
94
+ setImages((current) => current.filter((i) => i.key !== image.key));
95
+ staged.current.delete(image.key);
96
+ return uploads.current.delete(image.key);
97
+ }, [releasePreview]);
98
+ const reportError = useCallback((error) => onError(error instanceof PwCodeImageTooLarge ? t("detail.imageTooLarge") : host.current.describeError(error)), [onError, t]);
99
+ const add = useCallback((files) => {
100
+ for (const file of files) {
101
+ const mime = IMAGE_TYPES.find((type) => type === file.type);
102
+ if (!mime) {
103
+ onError(t("detail.imageUnsupported"));
104
+ continue;
105
+ }
106
+ if (file.size > 26214400) {
107
+ onError(t("detail.imageTooLarge"));
108
+ continue;
109
+ }
110
+ const seq = nextImageSeq(messagesRef.current?.map((m) => m.content), lastSeq.current);
111
+ lastSeq.current = seq;
112
+ const placeholder = `[Image #${seq}]`;
113
+ const image = {
114
+ key: placeholder,
115
+ placeholder,
116
+ previewUrl: host.current.preview(file),
117
+ saved: !sessionId
118
+ };
119
+ setImages((current) => [...current, image]);
120
+ if (!machine || !sessionId) {
121
+ staged.current.set(image.key, {
122
+ file,
123
+ seq,
124
+ mime
125
+ });
126
+ continue;
127
+ }
128
+ uploads.current.set(image.key, upload(machine, sessionId, placeholder, file, seq, mime).then((saved) => {
129
+ setImages((current) => current.map((i) => i.key === image.key ? {
130
+ ...i,
131
+ saved: true
132
+ } : i));
133
+ return saved;
134
+ }, (error) => {
135
+ if (discard(image)) reportError(error);
136
+ return null;
137
+ }));
138
+ }
139
+ }, [
140
+ discard,
141
+ machine,
142
+ onError,
143
+ reportError,
144
+ sessionId,
145
+ t,
146
+ upload
147
+ ]);
148
+ const saveTo = useCallback(async (machine, sessionId) => {
149
+ setTaking(true);
150
+ try {
151
+ const results = await Promise.allSettled(Array.from(staged.current, ([placeholder, pending]) => upload(machine, sessionId, placeholder, pending.file, pending.seq, pending.mime)));
152
+ const refs = [];
153
+ for (const result of results) {
154
+ if (result.status === "rejected") {
155
+ reportError(result.reason);
156
+ return null;
157
+ }
158
+ refs.push(result.value.ref);
159
+ }
160
+ return refs;
161
+ } finally {
162
+ setTaking(false);
163
+ }
164
+ }, [reportError, upload]);
165
+ return {
166
+ images,
167
+ taking,
168
+ add,
169
+ remove: useCallback((key) => {
170
+ const image = imagesRef.current.find((i) => i.key === key);
171
+ if (image) discard(image);
172
+ }, [discard]),
173
+ take: useCallback(async () => {
174
+ const taken = imagesRef.current;
175
+ if (taken.length === 0) return {
176
+ saved: [],
177
+ settle: () => {}
178
+ };
179
+ setImages([]);
180
+ setTaking(true);
181
+ const results = await Promise.all(taken.map((i) => uploads.current.get(i.key)));
182
+ setTaking(false);
183
+ return {
184
+ saved: results.filter((image) => image !== null && image !== void 0),
185
+ settle: (sent) => {
186
+ if (!sent && mounted.current) {
187
+ setImages((current) => [...taken.filter((_, index) => results[index]).map((image) => ({
188
+ ...image,
189
+ saved: true
190
+ })), ...current]);
191
+ return;
192
+ }
193
+ for (const image of taken) {
194
+ releasePreview(image.previewUrl);
195
+ uploads.current.delete(image.key);
196
+ }
197
+ }
198
+ };
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
+ }, []),
215
+ saveTo
216
+ };
217
+ }
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 };
@@ -0,0 +1,199 @@
1
+ import type { ApprovalAnswerValue, ChatMessage, MessagePaste } from '@parallelworks/ui/ai/headless';
2
+ import type { KeyedMutator } from 'swr';
3
+ import type { PwCodeResult, Schemas } from './apiClient.js';
4
+ import type { PwCodeApi } from './createPwCodeApi.js';
5
+ import { type GoalNotice, type TranscriptState } from './transcript.js';
6
+ import type { PwCodeImage, PwCodeImageRef, PwCodeSessionState } from './types.js';
7
+ import { type PwCodeSteerResult, type PwCodeWithdrawResult } from './useTranscript.js';
8
+ type Session = Schemas['AgentSession'];
9
+ type SessionDetail = Schemas['AgentSessionDetail'];
10
+ type SessionsResponse = Schemas['AgentSessionsResponse'];
11
+ type StreamEvent = Schemas['AgentStreamEvent'];
12
+ /** A word for the reader above the composer, until they dismiss it. */
13
+ export interface PwCodeNotice {
14
+ text: string;
15
+ warn: boolean;
16
+ /** Said because the machine could not be reached, so it goes once the machine answers. */
17
+ unreachable?: boolean | undefined;
18
+ }
19
+ /** How a main or subagent conversation stands in a list of them. */
20
+ export type PwCodeConversationState = 'approval' | 'running' | 'idle';
21
+ /** A transcript's messages as a view draws them: those it holds, then the one
22
+ * streaming, then those still waiting to be taken. */
23
+ export declare function transcriptMessages(transcript: TranscriptState | null): {
24
+ messages: ChatMessage[];
25
+ queued: ChatMessage[];
26
+ all: ChatMessage[];
27
+ };
28
+ /** A direction that got no answer may have landed, so it reads as lost, never as refused. */
29
+ export declare function directionOutcome(request: () => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>, lost: string, describeError: (error: unknown) => string): Promise<PwCodeSteerResult>;
30
+ /** 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>;
32
+ /** An open session's conversation: its live transcript, sends routed to the
33
+ * machine, approvals, the notice above the composer, and its subagents. The
34
+ * host reads the listing and the session (`api.useSessions`,
35
+ * `api.useSessionDetail`) and opens the feed with `api.useSessionEvents`,
36
+ * handing it `onEvent` and, once the detail is this visit's own, `cursor`. */
37
+ export declare function usePwCodeConversation({ api, machine, sessionId, sessions, detail: read, describeError, notify, onCleared, onMoved, goalNotice, }: {
38
+ api: PwCodeApi;
39
+ machine: string;
40
+ sessionId: string;
41
+ /** The listing, as `api.useSessions` reads it. */
42
+ sessions: {
43
+ data: SessionsResponse | undefined;
44
+ mutate: KeyedMutator<SessionsResponse>;
45
+ };
46
+ /** The session, as `api.useSessionDetail` reads it. */
47
+ detail: {
48
+ data: SessionDetail | undefined;
49
+ mutate: () => Promise<unknown>;
50
+ };
51
+ /** Words a refusal or failure for the reader. */
52
+ describeError: (error: unknown) => string;
53
+ /** Tells the reader something in passing, such as in a toast. */
54
+ notify: (text: string) => void;
55
+ /** Shows the session that a clear made elsewhere started in place of this one. */
56
+ onCleared: (newId: string) => void;
57
+ /** Shows the copy of this session the listing now has from a shared store. */
58
+ onMoved: (copy: Session) => void;
59
+ goalNotice?: GoalNotice;
60
+ }): {
61
+ messages: ChatMessage[];
62
+ queued: ChatMessage[];
63
+ all: ChatMessage[];
64
+ /** The session as the listing has it, or as its fetch does until then. */
65
+ session: {
66
+ allocation?: string;
67
+ approvals?: import("./api.js").components["schemas"]["ApprovalRequest"][] | null;
68
+ archivedAt?: string;
69
+ autoName?: string;
70
+ branch?: string;
71
+ createdAt: string;
72
+ effort?: string;
73
+ group?: string;
74
+ id: string;
75
+ inputTokens?: number;
76
+ lastError?: string;
77
+ liveHost?: string;
78
+ machineId: string;
79
+ messages: number;
80
+ model: string;
81
+ name?: string;
82
+ outputTokens?: number;
83
+ permissionMode?: string;
84
+ pinnedAt?: string;
85
+ preview: string;
86
+ pullRequestStates?: {
87
+ [key: string]: string;
88
+ };
89
+ pullRequests?: string[] | null;
90
+ remoteControl?: boolean;
91
+ status: "idle" | "running" | "awaiting_approval" | "live_elsewhere";
92
+ turnStartedAt?: string;
93
+ updatedAt: string;
94
+ workspace: string;
95
+ } | undefined;
96
+ detail: {
97
+ addDirs?: import("./api.js").components["schemas"]["AddedDirectory"][] | null;
98
+ allocation?: string;
99
+ allowedDirs?: import("./api.js").components["schemas"]["AllowedDirectory"][] | null;
100
+ approvals?: import("./api.js").components["schemas"]["ApprovalRequest"][] | null;
101
+ archivedAt?: string;
102
+ autoName?: string;
103
+ branch?: string;
104
+ claudeAccount?: string;
105
+ createdAt: string;
106
+ effort?: string;
107
+ goal?: import("./api.js").components["schemas"]["GoalStatus"];
108
+ group?: string;
109
+ history: import("./api.js").components["schemas"]["HistoryItem"][] | null;
110
+ id: string;
111
+ inputTokens?: number;
112
+ lastError?: string;
113
+ lastSeq?: number;
114
+ liveHost?: string;
115
+ machineId: string;
116
+ messages: number;
117
+ model: string;
118
+ name?: string;
119
+ outputTokens?: number;
120
+ permissionMode?: string;
121
+ pinnedAt?: string;
122
+ preview: string;
123
+ pullRequestStates?: {
124
+ [key: string]: string;
125
+ };
126
+ pullRequests?: string[] | null;
127
+ remoteControl?: boolean;
128
+ status: "idle" | "running" | "awaiting_approval" | "live_elsewhere";
129
+ turnId?: string;
130
+ turnStartedAt?: string;
131
+ updatedAt: string;
132
+ usageLimitResumeAt?: string;
133
+ waitingForUsageLimit?: boolean;
134
+ workspace: string;
135
+ workspaceUntrusted?: boolean;
136
+ } | undefined;
137
+ /** The session's state as its last state frame said, until which the detail stands. */
138
+ liveState: PwCodeSessionState | null;
139
+ goal: import("./types.js").PwCodeGoalStatus | undefined;
140
+ addDirs: import("./types.js").PwCodeAddedDirectory[] | null | undefined;
141
+ allowedDirs: import("./types.js").PwCodeAllowedDirectory[] | null | undefined;
142
+ refetch: () => Promise<unknown>;
143
+ transcript: TranscriptState | null;
144
+ sending: boolean;
145
+ /** Hands each frame of the session's feed to the transcript and the subagent views. */
146
+ onEvent: (ev: StreamEvent) => void;
147
+ /** Where the feed resumes from. */
148
+ cursor: () => number;
149
+ /** Hands every frame of the feed to `listener` until the returned call, as a subagent's view reads it. */
150
+ subscribe: (listener: (ev: StreamEvent) => void) => () => void;
151
+ notice: PwCodeNotice | null;
152
+ dismissNotice: () => void;
153
+ warn: (text: string, unreachable?: boolean) => void;
154
+ showError: (error: unknown) => void;
155
+ /** Takes back a notice that the machine could not be reached, once it answers. */
156
+ reached: () => void;
157
+ deliver: (text: string, options: {
158
+ steer?: boolean;
159
+ /** What was typed, when the text is what a command resolved it to. */
160
+ typed?: string | undefined;
161
+ pastes?: MessagePaste[] | undefined;
162
+ images?: PwCodeImageRef[] | undefined;
163
+ previews?: PwCodeImage[] | undefined;
164
+ }) => Promise<{
165
+ text: string;
166
+ unreachable: boolean;
167
+ } | null>;
168
+ noteShellRun: (command: string, output: string) => void;
169
+ canRemoveQueued: (id: string) => boolean;
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
+ }>;
176
+ /** Whether a queued message goes into the running turn's next step or waits for its reply. */
177
+ queueDelivery: (id: string) => 'nextStep' | 'afterReply';
178
+ answerApproval: (approvalId: string, answer: ApprovalAnswerValue) => Promise<void>;
179
+ subagents: {
180
+ agentType?: string;
181
+ awaitingApproval?: boolean;
182
+ background?: boolean;
183
+ color?: string;
184
+ current?: boolean;
185
+ description?: string;
186
+ endedAt?: string;
187
+ id: string;
188
+ model?: string;
189
+ startedAt?: string;
190
+ status: "running" | "done" | "failed" | "stopped";
191
+ usage?: import("./api.js").components["schemas"]["SubagentUsage"];
192
+ }[];
193
+ refreshSubagents: () => void;
194
+ stopSubagent: (id: string) => Promise<void>;
195
+ stopAllSubagents: () => Promise<void>;
196
+ mainState: PwCodeConversationState;
197
+ };
198
+ export type PwCodeConversation = ReturnType<typeof usePwCodeConversation>;
199
+ export {};