@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
@@ -0,0 +1,301 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { createQuery } from "./query.js";
3
+ import { pathBasename } from "./session.js";
4
+ import { useState } from "react";
5
+ // src/directories.ts
6
+ /** Text that starts at neither the root nor ~ is read from the home directory, so a bare name finds a folder there. */
7
+ function splitTypedPath(typed) {
8
+ const text = typed.trimStart();
9
+ const path = text.startsWith("/") || text === "~" || text.startsWith("~/") ? text : `~/${text}`;
10
+ if (path === "~") return {
11
+ parent: "~",
12
+ partial: ""
13
+ };
14
+ const cut = path.lastIndexOf("/");
15
+ return {
16
+ parent: path.slice(0, cut) || "/",
17
+ partial: path.slice(cut + 1)
18
+ };
19
+ }
20
+ var withoutTrailingSlashes = (path) => path.replace(/\/+$/, "") || "/";
21
+ /** The absolute path typed text names, with ~ read as `home`; null while it names none. */
22
+ function typedDirectory(typed, home) {
23
+ const text = typed.trim();
24
+ if (text.startsWith("/")) return withoutTrailingSlashes(text);
25
+ if (home && (text === "~" || text.startsWith("~/"))) return withoutTrailingSlashes(`${home}${text.slice(1)}`);
26
+ return null;
27
+ }
28
+ var joinDirectory = (parent, name) => parent.endsWith("/") ? `${parent}${name}` : `${parent}/${name}`;
29
+ /** The directory that holds `path`; null at the root. */
30
+ function parentDirectory(path) {
31
+ const trimmed = withoutTrailingSlashes(path);
32
+ if (trimmed === "/") return null;
33
+ return trimmed.slice(0, trimmed.lastIndexOf("/")) || "/";
34
+ }
35
+ /** A path as the field holds it while its folders are listed: it ends at a separator. */
36
+ var listedText = (path) => path.endsWith("/") ? path : `${path}/`;
37
+ /** How many recent directories lead the rows before anything is typed. */
38
+ var RECENT_LIMIT = 5;
39
+ /** How many folders the rows list at once; typing narrows to the rest. */
40
+ var FOLDER_LIMIT = 100;
41
+ var rank = (name, partial) => {
42
+ if (name === partial) return 0;
43
+ const lower = name.toLowerCase();
44
+ const wanted = partial.toLowerCase();
45
+ if (lower === wanted) return 1;
46
+ return lower.startsWith(wanted) ? 2 : 3;
47
+ };
48
+ /** The folders of `listing` to show: a hidden one, named from a dot, only once hidden folders are asked for. */
49
+ function visibleFolders(listing, showHidden) {
50
+ return (listing.entries ?? []).filter((entry) => showHidden || !entry.name.startsWith("."));
51
+ }
52
+ /** The folders of `listing` whose names hold `partial`, the closest first. A hidden folder shows once the name typed starts with a dot. */
53
+ function matchingFolders(listing, partial) {
54
+ const wanted = partial.toLowerCase();
55
+ const matches = visibleFolders(listing, partial.startsWith(".")).filter((entry) => entry.name.toLowerCase().includes(wanted));
56
+ if (!partial) return matches;
57
+ return matches.map((entry, index) => ({
58
+ entry,
59
+ index,
60
+ rank: rank(entry.name, partial)
61
+ })).sort((a, b) => a.rank - b.rank || a.index - b.index).map(({ entry }) => entry);
62
+ }
63
+ /** The text starts at the root or at ~, rather than being a name to look for. */
64
+ var isPathText = (typed) => /^\s*[/~]/.test(typed);
65
+ /** The rows under a path field, and whether they leave folders out, which
66
+ * typing a name reaches. `listing` is the listing of the directory `typed`
67
+ * points at, once loaded; `untouched` holds until the text is edited, which
68
+ * is when the recent directories lead. */
69
+ function pathCompletions({ typed, untouched, listing, recents }) {
70
+ const { partial } = splitTypedPath(typed);
71
+ const rows = [];
72
+ const unlisted = listing ? null : typedDirectory(typed, void 0);
73
+ if (listing && !partial) rows.push({
74
+ kind: "use",
75
+ path: listing.path,
76
+ listed: true
77
+ });
78
+ else if (unlisted) rows.push({
79
+ kind: "use",
80
+ path: unlisted,
81
+ listed: false
82
+ });
83
+ const offered = rows[0]?.path;
84
+ if (untouched) rows.push(...recents.filter((recent) => recent.path !== offered).slice(0, 5).map((recent) => ({
85
+ kind: "recent",
86
+ ...named(recent)
87
+ })));
88
+ else if (!isPathText(typed) && typed.trim()) {
89
+ const wanted = typed.trim().toLowerCase();
90
+ const found = recents.filter((recent) => recent.path.toLowerCase().includes(wanted));
91
+ const byName = (recent) => recent.name.toLowerCase().includes(wanted);
92
+ rows.push(...[...found.filter(byName), ...found.filter((r) => !byName(r))].map((recent) => ({
93
+ kind: "recent",
94
+ ...named(recent)
95
+ })));
96
+ }
97
+ if (!listing) return {
98
+ rows,
99
+ cut: false
100
+ };
101
+ const up = partial ? null : parentDirectory(listing.path);
102
+ if (up) rows.push({
103
+ kind: "up",
104
+ path: up
105
+ });
106
+ const folders = matchingFolders(listing, partial);
107
+ rows.push(...folders.slice(0, 100).map((entry) => ({
108
+ kind: "folder",
109
+ path: joinDirectory(listing.path, entry.name),
110
+ name: entry.name,
111
+ repository: entry.repository === true
112
+ })));
113
+ return {
114
+ rows,
115
+ cut: folders.length > 100 || listing.truncated === true
116
+ };
117
+ }
118
+ var named = ({ path, name }) => ({
119
+ path,
120
+ name
121
+ });
122
+ /** The listing was refused because the path is no directory the machine's account can read. */
123
+ function isUnlistedDirectory(error) {
124
+ return error?.code === "agents_workspace_invalid";
125
+ }
126
+ function pathRow(row, t) {
127
+ switch (row.kind) {
128
+ case "use": return {
129
+ ...row,
130
+ opens: false,
131
+ detail: row.listed ? t("start.useDirectory") : t("start.useTypedPath")
132
+ };
133
+ case "recent": return {
134
+ ...row,
135
+ opens: false,
136
+ detail: parentDirectory(row.path) ?? row.path
137
+ };
138
+ case "up": return {
139
+ ...row,
140
+ opens: true,
141
+ detail: row.path
142
+ };
143
+ case "folder": return {
144
+ ...row,
145
+ opens: false,
146
+ detail: void 0
147
+ };
148
+ }
149
+ }
150
+ /** `rows`, in the order `pathCompletions` gives them, as the sections a path
151
+ * field shows: the directory the text names, the recent ones, then the
152
+ * folders listed, which are headed only below recent ones. Empty sections
153
+ * are left out. */
154
+ function pathSections(rows, { typed, untouched }, t) {
155
+ const shown = rows.map((row) => pathRow(row, t));
156
+ const recent = shown.filter((row) => row.kind === "recent");
157
+ return [
158
+ {
159
+ key: "named",
160
+ label: void 0,
161
+ rows: shown.filter((row) => row.kind === "use")
162
+ },
163
+ {
164
+ key: "recent",
165
+ label: t("start.recentDirectories"),
166
+ rows: recent
167
+ },
168
+ {
169
+ key: "folders",
170
+ label: recent.length > 0 ? untouched || isPathText(typed) ? t("start.inThisDirectory") : t("start.inHomeDirectory") : void 0,
171
+ rows: shown.filter((row) => row.kind === "up" || row.kind === "folder")
172
+ }
173
+ ].filter((section) => section.rows.length > 0);
174
+ }
175
+ /** The one line under a path field's rows: why there are none, or what they
176
+ * leave out; null for none. */
177
+ function pathNote({ typed, listable, loading, error, listing, rows, cut }, t, describeError) {
178
+ if (!listable) return t("start.directoriesUnsupported");
179
+ if (loading) return null;
180
+ const { parent, partial } = splitTypedPath(typed);
181
+ if (error) return isUnlistedDirectory(error) ? t("start.directoryUnlisted", { path: parent }) : describeError(error);
182
+ if (!listing) return null;
183
+ if (cut) return t("start.directoriesCut");
184
+ if (rows.some((row) => row.kind === "folder")) return null;
185
+ return partial ? t("start.noDirectoryMatches", { name: partial }) : t("start.noDirectories");
186
+ }
187
+ /** Where browsing from a path field opens: the directory listed, else the one
188
+ * the text names; empty for the home directory. */
189
+ function browseStart(typed, listing) {
190
+ return listing?.path ?? typedDirectory(typed, void 0) ?? "";
191
+ }
192
+ /** The directory a path field picks as it closes, from what it was left
193
+ * holding: the one an edited text names, unless that is `chosen` already;
194
+ * null for none. A field closed to cancel picks nothing; the host does not
195
+ * ask this of it. */
196
+ function pickedOnClose(left, chosen) {
197
+ if (!left.edited) return null;
198
+ const path = typedDirectory(left.typed, left.home);
199
+ return path && path !== chosen ? path : null;
200
+ }
201
+ /** The chip naming the directory a session starts in: its last segment, with
202
+ * the whole path as its label; both ask for one while `directory` is empty. */
203
+ function directoryChip(directory, t) {
204
+ if (!directory) {
205
+ const choose = t("start.chooseDirectory");
206
+ return {
207
+ text: choose,
208
+ label: choose
209
+ };
210
+ }
211
+ return {
212
+ text: pathBasename(directory),
213
+ label: t("detail.workingDirectory", { path: directory })
214
+ };
215
+ }
216
+ function directoriesApi(client) {
217
+ const useQuery = createQuery(client);
218
+ const query = (path, filter) => ({
219
+ ...path ? { path } : {},
220
+ ...filter ? { filter } : {}
221
+ });
222
+ /** Lists the folders in `path` on the machine: absolute, or from ~, which an empty path lists. */
223
+ function listDirectories(machine, path, filter = "") {
224
+ return client.GET("/api/code/machines/{machine}/directories", { params: {
225
+ path: { machine },
226
+ query: query(path, filter)
227
+ } });
228
+ }
229
+ /** The folders in `path` on the machine, kept while the visit lasts; a null path asks nothing. */
230
+ function useDirectories(machine, path, filter = "") {
231
+ return useQuery("/api/code/machines/{machine}/directories", machine && path !== null ? { params: {
232
+ path: { machine },
233
+ query: query(path, filter)
234
+ } } : null, { shouldRetryOnError: false });
235
+ }
236
+ /** What a path field offers under `typed`: the machine's folders there, and
237
+ * the directories its sessions worked in. A machine that cannot list its
238
+ * folders, an older one, still offers those, and the path as typed. */
239
+ function usePathCompletion({ machine, typed, untouched, recents, describeError }) {
240
+ const t = usePwCodeTranslations("agents");
241
+ const { parent, partial } = splitTypedPath(typed);
242
+ const listable = machine?.directories === true;
243
+ const whole = useDirectories(machine?.id, listable ? parent : null);
244
+ const listing = useDirectories(machine?.id, whole.data?.truncated && partial ? parent : null, partial).data ?? whole.data;
245
+ const loading = listable && whole.isLoading;
246
+ const error = whole.error;
247
+ const { rows, cut } = pathCompletions({
248
+ typed,
249
+ untouched,
250
+ listing,
251
+ recents
252
+ });
253
+ const sections = pathSections(rows, {
254
+ typed,
255
+ untouched
256
+ }, t);
257
+ return {
258
+ rows: sections.flatMap((section) => section.rows),
259
+ sections,
260
+ note: pathNote({
261
+ typed,
262
+ listable,
263
+ loading,
264
+ error,
265
+ listing,
266
+ rows,
267
+ cut
268
+ }, t, describeError),
269
+ canBrowse: listable,
270
+ browseFrom: browseStart(typed, listing),
271
+ cut,
272
+ listing,
273
+ loading,
274
+ error
275
+ };
276
+ }
277
+ /** A folder tree of the machine: where it opens, at `from` or else the home
278
+ * directory, and its moves up from there. */
279
+ function useDirectoryTree(machine, from) {
280
+ const home = useDirectories(machine.id, from ? null : "~");
281
+ const [moved, setMoved] = useState(null);
282
+ const root = moved ?? (from || home.data?.path);
283
+ const above = root ? parentDirectory(root) : null;
284
+ return {
285
+ root,
286
+ title: root ? pathBasename(root) || root : machine.name,
287
+ above,
288
+ goUp: () => {
289
+ if (above) setMoved(above);
290
+ },
291
+ error: root ? void 0 : home.error
292
+ };
293
+ }
294
+ return {
295
+ listDirectories,
296
+ useDirectories,
297
+ usePathCompletion,
298
+ useDirectoryTree
299
+ };
300
+ }
301
+ export { FOLDER_LIMIT, RECENT_LIMIT, browseStart, directoriesApi, directoryChip, isPathText, isUnlistedDirectory, joinDirectory, listedText, matchingFolders, parentDirectory, pathCompletions, pathNote, pathSections, pickedOnClose, splitTypedPath, typedDirectory, visibleFolders };
package/dist/goal.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { type useFormatter } from 'use-intl';
2
+ import type { Schemas } from './apiClient.js';
3
+ import type { PwCodeApi } from './createPwCodeApi.js';
4
+ import { type PwCodeTranslator } from './messages.js';
5
+ import type { PwCodeGoalStatus } from './types.js';
6
+ /** A session's goal as /goal answers with it: the condition and the run so far. */
7
+ export type PwCodeGoal = Schemas['AgentGoalResult'];
8
+ /** What a reader can ask of a standing goal. */
9
+ export type PwCodeGoalAction = 'edit' | 'pause' | 'resume' | 'clear';
10
+ /** A goal's state as a dot: unlit while paused, pulsing while a check is in flight. */
11
+ export interface PwCodeGoalMark {
12
+ tone: 'info';
13
+ off: boolean;
14
+ pulse: boolean;
15
+ }
16
+ export declare function goalMark(status: PwCodeGoalStatus | null | undefined): PwCodeGoalMark;
17
+ /** A goal's working time: to the second on the `panel`, and on the `chip` to
18
+ * the second for its first minute and to the minute after, so the chip sits
19
+ * still while the panel's clock runs. */
20
+ export declare function goalElapsed(ms: number, clock: 'chip' | 'panel', locale: string): string;
21
+ /** The goal's working time as `clock` shows it, kept running between the
22
+ * machine's snapshots while the goal is active: from the snapshot as of when
23
+ * the caller mounted, or when a new one came. */
24
+ export declare function useGoalElapsed(status: PwCodeGoalStatus, clock: 'chip' | 'panel'): string;
25
+ /** What follows a goal's state, each set apart: its working time, then the
26
+ * turns checked and the tokens spent once there are any. */
27
+ export declare function goalFacts(elapsed: string, goal: Pick<PwCodeGoal, 'turns' | 'tokens'>, t: PwCodeTranslator<'agents'>, format: Pick<ReturnType<typeof useFormatter>, 'number'>): string[];
28
+ export interface PwCodeSessionGoal {
29
+ goal: PwCodeGoal | null;
30
+ /** Nothing read yet. */
31
+ loading: boolean;
32
+ pending: PwCodeGoalAction | null;
33
+ /** Why the last read or action failed: the machine's refusal, or what was thrown. */
34
+ error: unknown;
35
+ /** Rewrites the condition, keeping the run's progress. */
36
+ edit: (condition: string) => Promise<boolean>;
37
+ pause: () => Promise<boolean>;
38
+ resume: () => Promise<boolean>;
39
+ clear: () => Promise<boolean>;
40
+ /** `loading` until the first read answers, `none` without a condition,
41
+ * `editing` while a draft is open, else `goal`. */
42
+ view: 'loading' | 'none' | 'editing' | 'goal';
43
+ /** The line `loading` shows, and `none` once a read found no goal. */
44
+ note: string | null;
45
+ /** Nothing can be asked: the session takes no commands, or an action runs. */
46
+ busy: boolean;
47
+ /** The run's state, ahead of its facts. */
48
+ state: PwCodeGoalMark & {
49
+ text: string;
50
+ };
51
+ /** Why the last check found the goal unmet, under its heading. */
52
+ lastCheck: {
53
+ title: string;
54
+ reason: string;
55
+ } | null;
56
+ /** Said while the goal is paused. */
57
+ pausedNote: string | null;
58
+ /** Pause while the goal is active, resume while it is paused. */
59
+ toggle: {
60
+ action: 'pause' | 'resume';
61
+ label: string;
62
+ };
63
+ /** The condition being rewritten; null while not editing. It outlives the
64
+ * panel closing. */
65
+ draft: string | null;
66
+ /** Null leaves editing. */
67
+ setDraft: (draft: string | null) => void;
68
+ /** Opens a draft on the condition as it stands. */
69
+ startEdit: () => void;
70
+ /** A draft is open and blank. */
71
+ empty: boolean;
72
+ /** The draft says what the condition says, spacing around it aside. */
73
+ unchanged: boolean;
74
+ canSave: boolean;
75
+ saving: boolean;
76
+ /** Saves the draft when it can be, leaving editing once the machine takes it. */
77
+ save: () => Promise<boolean>;
78
+ }
79
+ /** The session's goal for a panel that shows it. It is read when `open` turns
80
+ * on, and again whenever the loop moves while it stays open, so the checks
81
+ * and the last reason follow the loop; each action answers with the goal as
82
+ * it left it, and joins the conversation as typing it would. One action runs
83
+ * at a time. */
84
+ export declare function useSessionGoal(api: Pick<PwCodeApi, 'runGoal'>, machine: string, sessionId: string, { open, status, locked, }: {
85
+ open: boolean;
86
+ status: PwCodeGoalStatus | null | undefined;
87
+ /** The session takes no commands, such as while its machine is unreachable. */
88
+ locked?: boolean;
89
+ }): PwCodeSessionGoal;
package/dist/goal.js ADDED
@@ -0,0 +1,164 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { useLocale } from "use-intl";
4
+ import { DateTime } from "luxon";
5
+ import { formatDuration, useClock } from "@parallelworks/ui/headless";
6
+ // src/goal.ts
7
+ function goalMark(status) {
8
+ return {
9
+ tone: "info",
10
+ off: !status?.active,
11
+ pulse: !!status?.checking
12
+ };
13
+ }
14
+ var SECOND = 1e3;
15
+ var MINUTE = 6e4;
16
+ /** A goal's working time: to the second on the `panel`, and on the `chip` to
17
+ * the second for its first minute and to the minute after, so the chip sits
18
+ * still while the panel's clock runs. */
19
+ function goalElapsed(ms, clock, locale) {
20
+ const unit = clock === "chip" && ms >= MINUTE ? MINUTE : SECOND;
21
+ return formatDuration(Math.floor(ms / unit) * unit, locale);
22
+ }
23
+ /** The goal's working time as `clock` shows it, kept running between the
24
+ * machine's snapshots while the goal is active: from the snapshot as of when
25
+ * the caller mounted, or when a new one came. */
26
+ function useGoalElapsed(status, clock) {
27
+ const locale = useLocale();
28
+ const ms = status.elapsedMs ?? 0;
29
+ const [base, setBase] = useState(() => ({
30
+ ms,
31
+ at: DateTime.now().toMillis()
32
+ }));
33
+ if (base.ms !== ms) setBase({
34
+ ms,
35
+ at: DateTime.now().toMillis()
36
+ });
37
+ const active = !!status.active;
38
+ return useClock((now) => goalElapsed(active ? base.ms + Math.max(now - base.at, 0) : base.ms, clock, locale), active);
39
+ }
40
+ /** What follows a goal's state, each set apart: its working time, then the
41
+ * turns checked and the tokens spent once there are any. */
42
+ function goalFacts(elapsed, goal, t, format) {
43
+ const facts = [elapsed];
44
+ if (goal.turns) facts.push(t("detail.goalPanel.turns", { count: goal.turns }));
45
+ if (goal.tokens) facts.push(t("detail.goalPanel.tokens", { tokens: format.number(goal.tokens, {
46
+ notation: "compact",
47
+ maximumFractionDigits: 1
48
+ }) }));
49
+ return facts;
50
+ }
51
+ function panelWords(goal, status, loading, t) {
52
+ const active = !!status?.active;
53
+ return {
54
+ note: loading ? t("detail.goalPanel.loading") : goal && !goal.condition ? t("detail.goalPanel.none") : null,
55
+ state: {
56
+ ...goalMark(status),
57
+ text: status?.checking ? t("detail.goalPanel.checking") : active ? t("detail.goalPanel.active") : t("detail.goalPanel.paused")
58
+ },
59
+ lastCheck: goal?.reason ? {
60
+ title: t("detail.goalPanel.lastCheck"),
61
+ reason: goal.reason
62
+ } : null,
63
+ pausedNote: active ? null : t("detail.goalPanel.pausedNote"),
64
+ toggle: active ? {
65
+ action: "pause",
66
+ label: t("detail.goalPanel.pause")
67
+ } : {
68
+ action: "resume",
69
+ label: t("detail.goalPanel.resume")
70
+ }
71
+ };
72
+ }
73
+ /** The session's goal for a panel that shows it. It is read when `open` turns
74
+ * on, and again whenever the loop moves while it stays open, so the checks
75
+ * and the last reason follow the loop; each action answers with the goal as
76
+ * it left it, and joins the conversation as typing it would. One action runs
77
+ * at a time. */
78
+ function useSessionGoal(api, machine, sessionId, { open, status, locked = false }) {
79
+ const t = usePwCodeTranslations("agents");
80
+ const [goal, setGoal] = useState(null);
81
+ const [reading, setReading] = useState(false);
82
+ const [pending, setPending] = useState(null);
83
+ const [error, setError] = useState(null);
84
+ const [draft, setDraft] = useState(null);
85
+ const latest = useRef(0);
86
+ const acting = useRef(false);
87
+ const request = async (args) => {
88
+ const n = ++latest.current;
89
+ const { data, error } = await api.runGoal(machine, sessionId, args).catch((thrown) => ({ error: thrown }));
90
+ if (n !== latest.current) return !!data;
91
+ setReading(false);
92
+ if (!data) {
93
+ setError(error);
94
+ return false;
95
+ }
96
+ setError(null);
97
+ setGoal(data);
98
+ return true;
99
+ };
100
+ const active = !!status?.active;
101
+ const paused = !!status?.paused;
102
+ const checking = !!status?.checking;
103
+ useEffect(() => {
104
+ if (!open) return;
105
+ setReading(true);
106
+ request("edit");
107
+ }, [
108
+ open,
109
+ machine,
110
+ sessionId,
111
+ active,
112
+ paused,
113
+ checking
114
+ ]);
115
+ const act = async (action, args) => {
116
+ if (acting.current) return false;
117
+ acting.current = true;
118
+ setPending(action);
119
+ setError(null);
120
+ try {
121
+ return await request(args);
122
+ } finally {
123
+ acting.current = false;
124
+ setPending(null);
125
+ }
126
+ };
127
+ const edit = (text) => {
128
+ const condition = text.trim();
129
+ return condition ? act("edit", `edit ${condition}`) : Promise.resolve(false);
130
+ };
131
+ const loading = reading && !goal;
132
+ const condition = goal?.condition ?? "";
133
+ const busy = locked || pending !== null;
134
+ const empty = draft !== null && !draft.trim();
135
+ const unchanged = draft !== null && draft.trim() === condition.trim();
136
+ const canSave = draft !== null && !busy && !empty && !unchanged;
137
+ return {
138
+ goal,
139
+ loading,
140
+ pending,
141
+ error,
142
+ edit,
143
+ pause: () => act("pause", "pause"),
144
+ resume: () => act("resume", "resume"),
145
+ clear: () => act("clear", "clear"),
146
+ view: loading ? "loading" : !condition ? "none" : draft !== null ? "editing" : "goal",
147
+ busy,
148
+ ...panelWords(goal, status, loading, t),
149
+ draft,
150
+ setDraft,
151
+ startEdit: () => setDraft(condition),
152
+ empty,
153
+ unchanged,
154
+ canSave,
155
+ saving: pending === "edit",
156
+ save: async () => {
157
+ if (draft === null || !canSave) return false;
158
+ const saved = await edit(draft);
159
+ if (saved) setDraft(null);
160
+ return saved;
161
+ }
162
+ };
163
+ }
164
+ export { goalElapsed, goalFacts, goalMark, useGoalElapsed, useSessionGoal };
@@ -0,0 +1,23 @@
1
+ import { type PwCodeImageType } from './useComposerImages.js';
2
+ /** The size and type a host writes an image at, scaled from the one it decoded. */
3
+ export interface PwCodeImageFit {
4
+ width: number;
5
+ height: number;
6
+ type: PwCodeImageType;
7
+ }
8
+ /** Scales an image down until it fits the terminal's paste limits, as
9
+ * clipimage.Fit does, through the host's `write`, which draws the decoded
10
+ * image at a fit and resolves to what it wrote. Resolves to null for an image
11
+ * that fits as it is, and throws `PwCodeImageTooLarge` for one no pass fits. */
12
+ export declare function fitImageWith<W extends {
13
+ size: number;
14
+ type: string;
15
+ }>(image: {
16
+ width: number;
17
+ height: number;
18
+ size: number;
19
+ type: PwCodeImageType;
20
+ }, write: (fit: PwCodeImageFit) => Promise<W>): Promise<{
21
+ image: W;
22
+ mime: PwCodeImageType;
23
+ } | null>;
@@ -0,0 +1,27 @@
1
+ import { IMAGE_MAX_BYTES, IMAGE_MAX_SIDE, IMAGE_TYPES, PwCodeImageTooLarge } from "./useComposerImages.js";
2
+ // src/imageFit.ts
3
+ var MAX_PASSES = 8;
4
+ /** Scales an image down until it fits the terminal's paste limits, as
5
+ * clipimage.Fit does, through the host's `write`, which draws the decoded
6
+ * image at a fit and resolves to what it wrote. Resolves to null for an image
7
+ * that fits as it is, and throws `PwCodeImageTooLarge` for one no pass fits. */
8
+ async function fitImageWith(image, write) {
9
+ const { width, height } = image;
10
+ let scale = Math.min(1, IMAGE_MAX_SIDE / width, IMAGE_MAX_SIDE / height, Math.sqrt(IMAGE_MAX_BYTES / image.size));
11
+ if (scale === 1) return null;
12
+ const type = image.type === "image/gif" ? "image/png" : image.type;
13
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
14
+ const written = await write({
15
+ width: Math.max(1, Math.floor(width * scale)),
16
+ height: Math.max(1, Math.floor(height * scale)),
17
+ type
18
+ });
19
+ if (written.size <= 5242880) return {
20
+ image: written,
21
+ mime: IMAGE_TYPES.find((t) => t === written.type) ?? "image/png"
22
+ };
23
+ scale *= Math.sqrt(IMAGE_MAX_BYTES / written.size);
24
+ }
25
+ throw new PwCodeImageTooLarge();
26
+ }
27
+ export { fitImageWith };
package/dist/images.d.ts CHANGED
@@ -1,7 +1,35 @@
1
+ import type { PwCodeTranslator } from './messages.js';
1
2
  /** The full-size image a session's transcript names by ref. */
2
3
  export declare function sessionImageUrl(machine: string, session: string, ref: string): string;
4
+ /** The preview of the image `original` serves, as a transcript read with
5
+ * `PREVIEWS_BY_REF` leaves it to be loaded. */
6
+ export declare function sessionImagePreviewUrl(original: string): string;
7
+ /** Asks for a session's transcript with each image that has a ref left
8
+ * without its preview. Previews are most of what a transcript with pictures
9
+ * weighs, and the page loads only the ones it draws. A machine whose pw code
10
+ * predates it sends every preview, which draws as before. */
11
+ export declare const PREVIEWS_BY_REF = "refs";
3
12
  export declare function isSessionImageUrl(url: string): boolean;
4
13
  /** The asset id of a file attached on GitHub, which a private repository shows only to its members. */
5
14
  export declare function githubAttachmentAsset(src: string): string | undefined;
6
15
  /** A GitHub attachment as the session's machine reads it from a pull request the session opened. */
7
16
  export declare function sessionGitHubImageUrl(machine: string, session: string, asset: string): string;
17
+ /** Where a markdown image that is a GitHub attachment loads from, in order,
18
+ * and what it links to once none of them loads. */
19
+ export interface PwCodeMarkdownImage {
20
+ sources: string[];
21
+ link: string;
22
+ }
23
+ /** A private repository's GitHub attachment loads only through the session's
24
+ * machine, so that comes first, then GitHub itself. Null for any other image,
25
+ * which loads as it is. */
26
+ export declare function markdownImageSources(src: string, session?: {
27
+ machine: string;
28
+ sessionId: string;
29
+ } | undefined): PwCodeMarkdownImage | null;
30
+ /** The link a GitHub attachment becomes once none of its sources loads: its
31
+ * alt text, or the word for an image when it has none. */
32
+ export declare function markdownImageLink(alt: string | undefined, t: PwCodeTranslator<'agentTranscript'>): {
33
+ name: string;
34
+ title: string;
35
+ };