@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,256 @@
1
+ import { canStartHere, isMachineDown, splitMachines } from "./machine.js";
2
+ import { canRunModel, isClaudeModel, runsClaude } from "./models.js";
3
+ import { recentDirectories } from "./session.js";
4
+ import { rememberSentPrompt } from "./wording.js";
5
+ import { useEffect, useMemo, useRef, useState } from "react";
6
+ import { clampPermissionMode } from "@parallelworks/ui/ai/headless";
7
+ // src/startSession.ts
8
+ /** The machines a session can start on, then those listed but not answering,
9
+ * each with computers before resources. A resource with no agent on it is
10
+ * one the reader has not touched, so it is not counted as down. */
11
+ function startMachines(machines) {
12
+ const ordered = (list) => {
13
+ const { computers, resources } = splitMachines(list);
14
+ return [...computers, ...resources];
15
+ };
16
+ return {
17
+ startable: ordered(machines.filter(canStartHere)),
18
+ down: ordered(machines.filter((m) => m.status !== "no_agent" && isMachineDown(m)))
19
+ };
20
+ }
21
+ /** clampPermissionMode falls to a machine's widest mode, which would turn auto
22
+ * into bypass on a machine too old for auto; capping at the mode itself first
23
+ * keeps the result from ever being wider than what was asked for. */
24
+ function startingMode(mode, machine) {
25
+ const accepted = machine?.permissionModes ?? void 0;
26
+ return clampPermissionMode(clampPermissionMode(mode, mode, accepted), machine?.remoteMaxPermissionMode, accepted);
27
+ }
28
+ function useStartLocation(machines, sessions, preference) {
29
+ const { startable, down } = useMemo(() => startMachines(machines), [machines]);
30
+ const [machineId, setMachineId] = useState("");
31
+ const wanted = machineId || preference?.saved;
32
+ const machine = startable.find((m) => m.id === wanted) ?? (startable.length === 1 ? startable[0] : void 0);
33
+ const directories = useMemo(() => recentDirectories(sessions, machine?.id), [sessions, machine]);
34
+ const [dir, setDir] = useState("");
35
+ const [typing, setTyping] = useState(false);
36
+ const settledOn = useRef(void 0);
37
+ useEffect(() => {
38
+ if (settledOn.current === machine?.id) return;
39
+ settledOn.current = machine?.id;
40
+ setDir("");
41
+ setTyping(false);
42
+ }, [machine?.id]);
43
+ const directory = typing ? dir : dir || directories[0]?.path || "";
44
+ const typeDirectory = (path) => {
45
+ setTyping(true);
46
+ setDir(path);
47
+ };
48
+ return {
49
+ startable,
50
+ down,
51
+ machine,
52
+ pickMachine: (id) => {
53
+ setMachineId(id);
54
+ preference?.remember(id);
55
+ setDir("");
56
+ setTyping(false);
57
+ },
58
+ directories,
59
+ directory,
60
+ typing,
61
+ pickDirectory: (path) => {
62
+ setDir(path);
63
+ setTyping(false);
64
+ },
65
+ typeDirectory,
66
+ typeOtherDirectory: () => typeDirectory(typing ? directory : "")
67
+ };
68
+ }
69
+ /** The mode a session starts in: the one saved, or one picked on this visit,
70
+ * within what the machine allows. A pick holds until the visit ends, so one
71
+ * the host declines to save, such as bypass, still applies to this start. */
72
+ function useStartPermissionMode(preference, machine) {
73
+ const [picked, setPicked] = useState(null);
74
+ return {
75
+ mode: startingMode(picked ?? preference.saved, machine),
76
+ pick: (mode) => {
77
+ setPicked(mode);
78
+ preference.remember(mode);
79
+ },
80
+ ceiling: machine?.remoteMaxPermissionMode,
81
+ accepted: machine?.permissionModes ?? void 0
82
+ };
83
+ }
84
+ /** The model, effort, allocation, account and images hold while a session
85
+ * starts. The permission mode, machine and directory are not held, and a pick
86
+ * there reaches only the next start. Until a machine is chosen, its model,
87
+ * effort and account chip wait for one too. */
88
+ function startControls(machine, starting) {
89
+ const none = !machine;
90
+ return {
91
+ disabled: {
92
+ model: starting || none,
93
+ effort: starting || none,
94
+ allocation: starting,
95
+ account: starting,
96
+ accountChip: none,
97
+ images: starting
98
+ },
99
+ canStart: !!machine && canStartHere(machine)
100
+ };
101
+ }
102
+ function useRememberedAccount(api, machine, saved) {
103
+ const claudeReady = runsClaude(machine);
104
+ const names = api.useClaudeAccountNames(machine?.id ?? "", claudeReady && !!saved);
105
+ const listed = !names.data || names.data.some((a) => a.name === saved);
106
+ const { mutate } = names;
107
+ useEffect(() => {
108
+ if (saved && !listed) mutate();
109
+ }, [
110
+ saved,
111
+ listed,
112
+ mutate
113
+ ]);
114
+ return claudeReady && listed ? saved : void 0;
115
+ }
116
+ function useRememberedModel(api, machine, account, last, platformModels, handedOff) {
117
+ const claudeReady = runsClaude(machine);
118
+ const claudeModels = api.useClaudeModels(machine?.id ?? "", void 0, account, claudeReady && !handedOff && isClaudeModel(last.model));
119
+ return canRunModel(last.model, claudeReady, platformModels, claudeModels.data ?? void 0) && !handedOff ? last : null;
120
+ }
121
+ /** Picks hold for the machine they were made on. Until then a session starts
122
+ * on the model last picked where the machine and the platform still offer
123
+ * it, else on the host's selected one, and on the account saved for the
124
+ * machine where the machine still lists it. */
125
+ function useStartModel(api, { machine, platform, last, account: accountPreference, handedOff }) {
126
+ const [picked, setPicked] = useState(null);
127
+ const choice = picked?.machine === machine?.id ? picked : null;
128
+ const remembered = useRememberedAccount(api, machine, accountPreference.saved);
129
+ const account = choice?.account ?? remembered;
130
+ const lastModel = useRememberedModel(api, machine, account, last, platform.models, handedOff);
131
+ const pick = (change) => {
132
+ if (machine) setPicked({
133
+ ...choice,
134
+ ...change,
135
+ machine: machine.id
136
+ });
137
+ };
138
+ return {
139
+ model: choice?.model ?? lastModel?.model ?? platform.model,
140
+ allocation: choice?.allocation ?? lastModel?.allocation ?? platform.allocation,
141
+ account,
142
+ pickedAccount: choice?.account,
143
+ pickModel: (model) => pick({ model }),
144
+ pickAllocation: (allocation) => pick({ allocation }),
145
+ pickAccount: (next) => {
146
+ pick({ account: next });
147
+ accountPreference.remember(next);
148
+ }
149
+ };
150
+ }
151
+ function sessionBody(machine, { directory, mode, model, effort, allocation, account }, prompt) {
152
+ return {
153
+ workspace: directory,
154
+ ...model ? { model } : {},
155
+ ...effort ? { effort } : {},
156
+ ...!isClaudeModel(model) && allocation ? { allocation } : {},
157
+ ...machine.claudeCodeAllowed && account ? { claudeAccount: account } : {},
158
+ permissionMode: mode,
159
+ ...prompt ? { prompt } : {}
160
+ };
161
+ }
162
+ /** The prompt, then each image it does not name already. */
163
+ function withPlaceholders(prompt, images) {
164
+ return [prompt, ...images.map((image) => image.placeholder).filter((placeholder) => !prompt.includes(placeholder))].filter(Boolean).join(" ");
165
+ }
166
+ /** Starts a session, reads the listing again so it shows there, and hands it
167
+ * to `onStarted` once its first prompt is sent. With images, the session is
168
+ * created first and they are saved with it; a retry after they fail reuses
169
+ * that session while nothing it started with has changed. */
170
+ function useStartSession(api, options) {
171
+ const { machine, directory, images, firstPrompt, onStarted } = options;
172
+ const { mutate } = api.useSessions();
173
+ const [starting, setStarting] = useState(false);
174
+ const [error, setError] = useState(null);
175
+ const pendingSession = useRef(null);
176
+ const config = JSON.stringify([
177
+ machine?.id,
178
+ directory,
179
+ options.mode,
180
+ options.model,
181
+ options.effort,
182
+ options.allocation,
183
+ options.account
184
+ ]);
185
+ const ready = !!machine && directory.startsWith("/") && !starting && !options.waiting;
186
+ const started = (machineId, id, text) => {
187
+ rememberSentPrompt(machineId, id, text);
188
+ mutate();
189
+ onStarted(machineId, id);
190
+ };
191
+ /** The new session's id, or null once its refusal is kept. */
192
+ const create = async (on, prompt) => {
193
+ const { data, error: failed } = await api.createSession(on.id, sessionBody(on, options, prompt));
194
+ if (failed) {
195
+ setError(failed);
196
+ return null;
197
+ }
198
+ return data?.id || null;
199
+ };
200
+ const send = async (on, id, first) => {
201
+ const saved = images ? await images.saveTo(on.id, id) : [];
202
+ if (saved === null) return false;
203
+ const text = withPlaceholders(first, saved);
204
+ const { error: failed } = await api.sendMessage(on.id, id, {
205
+ text,
206
+ images: saved
207
+ });
208
+ if (failed) {
209
+ setError(failed);
210
+ return false;
211
+ }
212
+ started(on.id, id, text);
213
+ return true;
214
+ };
215
+ const attempt = async (on, prompt) => {
216
+ const pending = pendingSession.current?.config === config ? pendingSession.current.id : "";
217
+ const first = firstPrompt ? firstPrompt(prompt) : prompt;
218
+ const withImages = !!images?.count;
219
+ if (withImages) pendingSession.current = {
220
+ id: pending,
221
+ config
222
+ };
223
+ if (pending) return send(on, pending, first);
224
+ const id = await create(on, withImages ? "" : first);
225
+ if (!id) return false;
226
+ if (!withImages) {
227
+ started(on.id, id, first);
228
+ return true;
229
+ }
230
+ pendingSession.current = {
231
+ id,
232
+ config
233
+ };
234
+ return send(on, id, first);
235
+ };
236
+ const start = async (prompt) => {
237
+ if (!ready || !machine) return false;
238
+ setStarting(true);
239
+ setError(null);
240
+ try {
241
+ return await attempt(machine, prompt);
242
+ } catch (thrown) {
243
+ setError(thrown);
244
+ return false;
245
+ } finally {
246
+ setStarting(false);
247
+ }
248
+ };
249
+ return {
250
+ ready,
251
+ starting,
252
+ error,
253
+ start
254
+ };
255
+ }
256
+ export { startControls, startMachines, startingMode, useStartLocation, useStartModel, useStartPermissionMode, useStartSession };
@@ -0,0 +1,30 @@
1
+ import { type PwCodeMachine, type TerminalHandoff } from './machine.js';
2
+ import type { PwCodeTranslator } from './messages.js';
3
+ import { type PwCodeSession } from './session.js';
4
+ /** What picking a session up in a terminal shows: a note until its machine
5
+ * is listed, then the command to copy and what running it does. */
6
+ export type TerminalHandoffPanel = {
7
+ status: 'loading' | 'missing';
8
+ note: string;
9
+ } | {
10
+ status: 'ready';
11
+ handoff: TerminalHandoff;
12
+ /** What running the command does, and where. */
13
+ body: string;
14
+ /** What the copied command is announced as. */
15
+ commandLabel: string;
16
+ /** That a resource's session picks up from any terminal signed in to pw. */
17
+ anyTerminal: string | undefined;
18
+ /** That picking an archived session up restores it. */
19
+ archived: string | undefined;
20
+ };
21
+ export declare function terminalHandoffPanel(listing: {
22
+ machines?: readonly PwCodeMachine[] | null | undefined;
23
+ sessions?: readonly Pick<PwCodeSession, 'machineId' | 'id' | 'archivedAt'>[] | null | undefined;
24
+ } | undefined, machine: string, sessionId: string, username: string | undefined, t: PwCodeTranslator<'agents'>): TerminalHandoffPanel;
25
+ /** A handoff command split before the session it names, which a narrow
26
+ * panel keeps whole rather than breaking at a hyphen in its id. */
27
+ export declare function handoffCommandParts(command: string): {
28
+ head: string;
29
+ session: string;
30
+ };
@@ -0,0 +1,33 @@
1
+ import { terminalHandoff } from "./machine.js";
2
+ import { isArchived, isSession } from "./session.js";
3
+ // src/terminalHandoffPanel.ts
4
+ function terminalHandoffPanel(listing, machine, sessionId, username, t) {
5
+ const found = listing?.machines?.find((m) => m.id === machine);
6
+ if (!found) return listing ? {
7
+ status: "missing",
8
+ note: t("terminal.machineMissing")
9
+ } : {
10
+ status: "loading",
11
+ note: t("terminal.machineLoading")
12
+ };
13
+ const session = listing?.sessions?.find((s) => isSession(s, machine, sessionId));
14
+ const handoff = terminalHandoff(found, sessionId, username);
15
+ return {
16
+ status: "ready",
17
+ handoff,
18
+ body: handoff.on === "resource" ? t("terminal.resourceBody", { machine: found.name }) : t("terminal.computerBody", { host: handoff.host }),
19
+ commandLabel: t("terminal.commandLabel"),
20
+ anyTerminal: handoff.on === "resource" ? t("terminal.anyTerminal") : void 0,
21
+ archived: session && isArchived(session) ? t("terminal.archived") : void 0
22
+ };
23
+ }
24
+ /** A handoff command split before the session it names, which a narrow
25
+ * panel keeps whole rather than breaking at a hyphen in its id. */
26
+ function handoffCommandParts(command) {
27
+ const at = command.lastIndexOf(" ") + 1;
28
+ return {
29
+ head: command.slice(0, at),
30
+ session: command.slice(at)
31
+ };
32
+ }
33
+ export { handoffCommandParts, terminalHandoffPanel };
@@ -126,6 +126,8 @@ export interface TranscriptWords {
126
126
  deliveryLine: (notice: SubagentNotice) => string;
127
127
  /** An approval's option that opens the directory it names for the session. */
128
128
  allowDirectory: (dir: PwCodeAllowedDirectory) => string;
129
+ /** Who wrote a subagent's prompt: the conversation that started it. */
130
+ mainConversation: string;
129
131
  }
130
132
  /** The verb the terminal picks for a turn, so the same turn reads the same in both. */
131
133
  export declare function turnVerb(endedAt: string): TurnVerb;
@@ -1,16 +1,22 @@
1
- import { DateTime } from "luxon";
1
+ import { runsInBackgroundTool } from "./commandsApi.js";
2
+ import { sessionImagePreviewUrl } from "./images.js";
2
3
  import { INTERRUPTED_NOTICE, applyPartDelta, askQuestionsFromArgs, classifyPseudoUserMessage, finalizeParts, firstNonEmptyLine, hiddenTranscriptTool, interruptionNotice, parseSubagentNotice, planFromArgs, resultFailed, subagentDeliveryLine, taskCallFromArgs } from "@parallelworks/ui/ai/headless";
4
+ import { DateTime } from "luxon";
3
5
  // src/transcript.ts
4
- var MAIN_SESSION_AUTHOR = {
5
- id: "main",
6
- username: "main session"
7
- };
6
+ function mainConversationAuthor(words) {
7
+ return {
8
+ id: "main",
9
+ username: "main session",
10
+ name: words?.mainConversation ?? "Main conversation",
11
+ kind: "agent"
12
+ };
13
+ }
8
14
  var synthCounter = 0;
9
15
  function synthId(prefix) {
10
16
  synthCounter += 1;
11
17
  return `${prefix}-${synthCounter}`;
12
18
  }
13
- function userMessage(text, fromMain, id, pastes, images, imageUrl) {
19
+ function userMessage(text, author, id, pastes, images, imageUrl) {
14
20
  const pseudo = classifyPseudoUserMessage("user", text);
15
21
  const attachments = imageAttachments(images, imageUrl);
16
22
  return {
@@ -18,26 +24,35 @@ function userMessage(text, fromMain, id, pastes, images, imageUrl) {
18
24
  role: "user",
19
25
  content: text,
20
26
  ...pseudo ? { pseudo } : {},
21
- ...fromMain ? { author: MAIN_SESSION_AUTHOR } : {},
27
+ ...author ? { author } : {},
22
28
  ...pastes?.length ? { pastes } : {},
23
29
  ...attachments.length ? { attachments } : {}
24
30
  };
25
31
  }
26
32
  /** The daemon sends a preview of each image inline; one whose original it
27
33
  * names opens at full size from the host, any other from its preview. */
34
+ /** The preview's size, which holds its place in the page until it has loaded. */
35
+ function previewBox(image) {
36
+ return image.width && image.height ? {
37
+ previewWidth: image.width,
38
+ previewHeight: image.height
39
+ } : {};
40
+ }
28
41
  function imageAttachments(images, imageUrl) {
29
- return (images ?? []).filter((image) => image.mime.startsWith("image/")).map((image) => {
30
- const preview = `data:${image.mime};base64,${image.data}`;
31
- const previewSize = Math.floor(image.data.length * 3 / 4) - (image.data.match(/=*$/)?.[0].length ?? 0);
42
+ return (images ?? []).filter((image) => image.mime.startsWith("image/")).flatMap((image) => {
32
43
  const original = image.ref && imageUrl ? imageUrl(image.ref) : void 0;
33
- return {
44
+ const preview = image.data ? `data:${image.mime};base64,${image.data}` : original && sessionImagePreviewUrl(original);
45
+ if (!preview) return [];
46
+ const previewSize = Math.floor(image.data.length * 3 / 4) - (image.data.match(/=*$/)?.[0].length ?? 0);
47
+ return [{
34
48
  id: original ?? preview,
35
49
  previewUrl: preview,
36
50
  filename: "",
37
51
  contentType: original && image.originalMime || image.mime,
38
52
  size: original ? image.originalSize ?? 0 : previewSize,
39
- uploadedAt: ""
40
- };
53
+ uploadedAt: "",
54
+ ...previewBox(image)
55
+ }];
41
56
  });
42
57
  }
43
58
  function assistantMessage(parts = [], id) {
@@ -94,7 +109,7 @@ function completeOldestRunning(parts, result) {
94
109
  function approvalSubject(req) {
95
110
  if (req.reason === "file is outside the workspace") return "path";
96
111
  if (req.tool === "NotebookRun" || req.reason === "code in the notebook kernel") return "code";
97
- if (req.tool !== void 0 && req.tool !== "Bash") return "call";
112
+ if (req.tool !== void 0 && req.tool !== "Bash" && req.tool !== "Monitor") return "call";
98
113
  return "command";
99
114
  }
100
115
  function approvalToPart(req, words) {
@@ -208,7 +223,7 @@ function historyToMessages(history, options = {}) {
208
223
  }
209
224
  flush(true);
210
225
  messages.push({
211
- ...userMessage(command, false, `h-u-${index}`),
226
+ ...userMessage(command, void 0, `h-u-${index}`),
212
227
  commandAnswer: answer
213
228
  });
214
229
  };
@@ -236,7 +251,7 @@ function historyToMessages(history, options = {}) {
236
251
  append(shellRunPart(shell.command, shell.output), index);
237
252
  return;
238
253
  }
239
- messages.push(userMessage(item.text ?? "", item.fromMain ?? false, `h-u-${index}`, item.pastes, item.images, options.imageUrl));
254
+ messages.push(userMessage(item.text ?? "", item.fromMain ? mainConversationAuthor(words) : void 0, `h-u-${index}`, item.pastes, item.images, options.imageUrl));
240
255
  return;
241
256
  }
242
257
  case "assistant": {
@@ -253,7 +268,8 @@ function historyToMessages(history, options = {}) {
253
268
  case "thinking":
254
269
  append({
255
270
  kind: "reasoning",
256
- text: item.text ?? ""
271
+ text: item.text ?? "",
272
+ ...item.durationMs ? { durationMs: item.durationMs } : {}
257
273
  }, index);
258
274
  return;
259
275
  case "tool_call": {
@@ -340,12 +356,13 @@ function historyToMessages(history, options = {}) {
340
356
  }
341
357
  case "notice": {
342
358
  const text = item.text ?? "";
343
- const delivery = parseSubagentNotice(text);
359
+ const delivery = readDelivery(text);
344
360
  if (delivery?.silent) return;
361
+ const detail = delivery ? deliveryDetail(delivery) : void 0;
345
362
  append(delivery ? {
346
363
  kind: "notice",
347
364
  text: deliveryLine(delivery, words),
348
- ...delivery.body ? { detail: delivery.body } : {}
365
+ ...detail ? { detail } : {}
349
366
  } : {
350
367
  kind: "notice",
351
368
  text: text.trim()
@@ -574,7 +591,7 @@ function resolveApprovalEverywhere(state, id) {
574
591
  * short, so the page must not close the turn either: its open tool calls
575
592
  * would read as interrupted while they are still running. */
576
593
  function appendOwnMessage(state, text, id, pastes, previews) {
577
- const message = userMessage(text, false, id, pastes, previews);
594
+ const message = userMessage(text, void 0, id, pastes, previews);
578
595
  if (turnRunning(state)) return {
579
596
  ...state,
580
597
  queued: [...state.queued, message]
@@ -611,7 +628,7 @@ function withSentPastesAndImages(messages, ev, id, imageUrl) {
611
628
  function appendSteeredMessage(state, text, id, pastes, previews) {
612
629
  return {
613
630
  ...state,
614
- steered: [...state.steered, userMessage(text, false, id, pastes, previews)]
631
+ steered: [...state.steered, userMessage(text, void 0, id, pastes, previews)]
615
632
  };
616
633
  }
617
634
  /** The daemon queued a message this page had shown as sent, because the turn
@@ -656,7 +673,7 @@ function turnRunning(state) {
656
673
  }
657
674
  /** Whether the turn waits on a Bash call, which the machine can move to the background. */
658
675
  function bashRunning(state) {
659
- return (state?.streaming?.parts ?? []).some((p) => p.kind === "tool_call" && p.name === "Bash" && p.status === "running");
676
+ return (state?.streaming?.parts ?? []).some((p) => p.kind === "tool_call" && runsInBackgroundTool(p));
660
677
  }
661
678
  /** Daemons before the interrupted flag close a stopped turn with the
662
679
  * cancelled context's error. */
@@ -840,6 +857,25 @@ var TURN_VERBS = [
840
857
  function deliveryLine(n, words) {
841
858
  return words ? words.deliveryLine(n) : subagentDeliveryLine(n);
842
859
  }
860
+ var REPORT_SCAN_HEADER = "[pw code: subagent report matched";
861
+ /** A delivered notice, with a monitor event's line taken from what its script printed rather than the scanner's header above it. */
862
+ function readDelivery(text) {
863
+ const n = parseSubagentNotice(text);
864
+ if (!n?.monitor || !n.body.startsWith(REPORT_SCAN_HEADER)) return n;
865
+ const nl = n.body.indexOf("\n");
866
+ return {
867
+ ...n,
868
+ preview: nl === -1 ? "" : firstNonEmptyLine(n.body.slice(nl + 1), 100)
869
+ };
870
+ }
871
+ /** What a delivery's line opens to. A monitor's lines are a script's output, which Markdown would run together, so they go in a code block. */
872
+ function deliveryDetail(n) {
873
+ if (!n.body) return;
874
+ if (!n.monitor) return n.body;
875
+ const longest = Math.max(0, ...(n.body.match(/`+/g) ?? []).map((run) => run.length));
876
+ const fence = "`".repeat(Math.max(3, longest + 1));
877
+ return `${fence}\n${n.body}\n${fence}`;
878
+ }
843
879
  function isPlanFile(path) {
844
880
  const slashed = path.replaceAll("\\", "/");
845
881
  const base = slashed.slice(slashed.lastIndexOf("/") + 1).toLowerCase();
@@ -1125,7 +1161,7 @@ function noteHandedOver(state, id, ev, imageUrl) {
1125
1161
  return {
1126
1162
  ...state,
1127
1163
  steered,
1128
- notes: note ? withSentPastesAndImages([...state.notes, note], ev, note.id, imageUrl) : [...state.notes, userMessage(text, false, void 0, ev.pastes, ev.images, imageUrl)]
1164
+ notes: note ? withSentPastesAndImages([...state.notes, note], ev, note.id, imageUrl) : [...state.notes, userMessage(text, void 0, void 0, ev.pastes, ev.images, imageUrl)]
1129
1165
  };
1130
1166
  }
1131
1167
  function nowIso() {
@@ -1248,7 +1284,7 @@ function applyStreamEvent(state, ev, options = {}) {
1248
1284
  next = finishTurn(next);
1249
1285
  next = ownEcho ? takeEcho(next, options.echoOf, ev, options.imageUrl) : {
1250
1286
  ...next,
1251
- messages: [...next.messages, userMessage(ev.content ?? "", false, void 0, ev.pastes, ev.images, options.imageUrl)]
1287
+ messages: [...next.messages, userMessage(ev.content ?? "", void 0, void 0, ev.pastes, ev.images, options.imageUrl)]
1252
1288
  };
1253
1289
  next = {
1254
1290
  ...next,
@@ -1279,8 +1315,8 @@ function applyStreamEvent(state, ev, options = {}) {
1279
1315
  };
1280
1316
  break;
1281
1317
  case "subagent_delivered": {
1282
- const delivery = parseSubagentNotice(ev.notice ?? "");
1283
- if (delivery && !delivery.silent) next = appendNotice(next, deliveryLine(delivery, options.words), delivery.body || void 0);
1318
+ const delivery = readDelivery(ev.notice ?? "");
1319
+ if (delivery && !delivery.silent) next = appendNotice(next, deliveryLine(delivery, options.words), deliveryDetail(delivery));
1284
1320
  break;
1285
1321
  }
1286
1322
  case "done": {
package/dist/types.d.ts CHANGED
@@ -43,16 +43,22 @@ export interface PwCodeHistoryItem {
43
43
  turnEnd?: PwCodeTurnEnd;
44
44
  /** On an EditFile call: the line its hunk begins on, as a live tool_start carries it. */
45
45
  startLine?: number;
46
+ /** On a thinking item: how long the thought took, when the session recorded it. */
47
+ durationMs?: number;
46
48
  }
47
49
  /** A preview of an image a message carried, base64-encoded; ref names the
48
50
  * full-size image when the daemon can serve it, and originalMime and
49
- * originalSize describe that image. */
51
+ * originalSize describe that image. Data is empty where the transcript was
52
+ * read with its previews left to their refs. */
50
53
  export interface PwCodeImage {
51
54
  mime: string;
52
55
  data: string;
53
56
  ref?: string;
54
57
  originalMime?: string;
55
58
  originalSize?: number;
59
+ /** The preview's size in pixels. */
60
+ width?: number;
61
+ height?: number;
56
62
  }
57
63
  /** An image the session saved, sent with the message that names its placeholder. */
58
64
  export interface PwCodeImageRef {
@@ -141,6 +147,8 @@ export interface PwCodeGoalStatus {
141
147
  paused?: boolean;
142
148
  /** An evaluation is in flight, which spends tokens with no turn to show. */
143
149
  checking?: boolean;
150
+ /** Time spent working toward it when the snapshot was taken; a pause stops it. */
151
+ elapsedMs?: number;
144
152
  }
145
153
  /** One step of a /goal loop, as the daemon files and announces it. */
146
154
  export interface PwCodeGoalProgress {
@@ -151,6 +159,8 @@ export interface PwCodeGoalProgress {
151
159
  err?: string;
152
160
  /** Set when a usage limit stopped the check; the goal is checked again then. */
153
161
  resumeAt?: string;
162
+ /** Set on a check-in: how long the check has waited on background work still running. */
163
+ waitedMs?: number;
154
164
  elapsedMs?: number;
155
165
  tokens?: number;
156
166
  }
@@ -0,0 +1,8 @@
1
+ export interface UsageLimitWait {
2
+ /** That the turn waits for the limit to reset, and when once that is known. */
3
+ waiting: string;
4
+ /** What offers another Claude Code account, which takes the turn over at once. */
5
+ switchAccount: string;
6
+ }
7
+ /** The running turn's line while it waits for a usage limit to reset. */
8
+ export declare function useUsageLimitWait(resumeAt: string | null | undefined): UsageLimitWait;
@@ -0,0 +1,13 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { useResumeTime } from "./notices.js";
3
+ // src/usageLimit.ts
4
+ /** The running turn's line while it waits for a usage limit to reset. */
5
+ function useUsageLimitWait(resumeAt) {
6
+ const t = usePwCodeTranslations("agents");
7
+ const resumeTime = useResumeTime();
8
+ return {
9
+ waiting: resumeAt ? t("detail.waitingForUsageLimitUntil", { time: resumeTime(resumeAt) }) : t("detail.waitingForUsageLimit"),
10
+ switchAccount: t("detail.switchClaudeAccount")
11
+ };
12
+ }
13
+ export { useUsageLimitWait };
@@ -0,0 +1,30 @@
1
+ import type { PwCodeApi } from './createPwCodeApi.js';
2
+ export declare const recapAfterTurnMs: number;
3
+ export declare const recapAfterLeavingMs = 2000;
4
+ /** Whether the reader has the session in front of them, as the host's app knows it. */
5
+ export interface PwCodePresence {
6
+ /** Whether the reader is away: the app is out of sight or out of focus. */
7
+ away: () => boolean;
8
+ /** Calls `leave` when the reader may have left and `back` when they may
9
+ * have come back, until the returned call. Each reads `away` itself. */
10
+ watch: (on: {
11
+ leave: () => void;
12
+ back: () => void;
13
+ }) => () => void;
14
+ }
15
+ /** Has the session recapped while the reader is away from it, as pw code
16
+ * does while its terminal is out of focus, so the recap is waiting when they
17
+ * come back. The machine declines while its recaps are off. */
18
+ export declare function useAwayRecap({ api, machine, sessionId, turnEndSeq, idle, drafting, presence, }: {
19
+ api: Pick<PwCodeApi, 'requestRecap'>;
20
+ machine: string;
21
+ sessionId: string;
22
+ /** Changes each time the reader's view sees a main turn end. */
23
+ turnEndSeq: number | undefined;
24
+ /** Whether the session rests between turns and can be reached; read when the wait ends. */
25
+ idle: boolean;
26
+ /** Whether a message is being typed: nothing is asked for over one. Read when the wait ends. */
27
+ drafting: () => boolean;
28
+ /** Read when the session opens and whenever it is asked again. */
29
+ presence: PwCodePresence;
30
+ }): void;