@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,328 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { useFormatter } from "use-intl";
4
+ import { DateTime } from "luxon";
5
+ // src/claudeAccounts.ts
6
+ var signInRequiredCode = "agents_claude_sign_in_required";
7
+ /** The refusal of a read that needs the account signed in first. */
8
+ function claudeSignInRequired(error) {
9
+ return error?.code === signInRequiredCode;
10
+ }
11
+ /** The account name `input` gives once trimmed, or null when Claude Code
12
+ * can't take it. */
13
+ function claudeAccountName(input) {
14
+ const name = input.trim();
15
+ if (!/^[a-zA-Z0-9_.@-]{1,64}$/.test(name) || name === "." || name === ".." || name.endsWith(".lock")) return null;
16
+ return name;
17
+ }
18
+ function unavailableNotice(allowed, installed, t) {
19
+ if (!allowed) return t("claude.disabled");
20
+ return installed ? null : t("claude.notInstalled");
21
+ }
22
+ function viewWords(view, host, hint, t) {
23
+ switch (view.kind) {
24
+ case "signIn": return {
25
+ title: t("claude.signInTitle"),
26
+ description: t("claude.profileOnHost", {
27
+ account: view.account,
28
+ host
29
+ }),
30
+ signInNote: null,
31
+ removeBody: null
32
+ };
33
+ case "remove": return {
34
+ title: t("claude.removeAccount"),
35
+ description: t("claude.profileOnHost", {
36
+ account: view.account,
37
+ host
38
+ }),
39
+ signInNote: null,
40
+ removeBody: t("claude.removeBody", {
41
+ account: view.account,
42
+ host
43
+ })
44
+ };
45
+ case "add": return {
46
+ title: t("claude.addAccount"),
47
+ description: t("claude.hostAccounts", { host }),
48
+ signInNote: null,
49
+ removeBody: null
50
+ };
51
+ default: return {
52
+ title: t("claude.accounts"),
53
+ description: t("claude.hostAccounts", { host }),
54
+ signInNote: hint ?? t("claude.loginStaysOnHost", { host }),
55
+ removeBody: null
56
+ };
57
+ }
58
+ }
59
+ function listControls(view, available, canAdd) {
60
+ const showRefresh = available && view.kind === "list";
61
+ return {
62
+ showAdd: showRefresh && canAdd,
63
+ showRefresh
64
+ };
65
+ }
66
+ function startRows(accounts, selected, claudeLogin) {
67
+ const selectedIndex = accounts.findIndex((a) => a.name === selected);
68
+ const firstEnabledIndex = accounts.findIndex((a) => claudeLogin || !a.signInRequired);
69
+ return {
70
+ startIndex: startIndexOf(selectedIndex, firstEnabledIndex),
71
+ selectedIndex,
72
+ firstEnabledIndex
73
+ };
74
+ }
75
+ function startIndexOf(selectedIndex, firstEnabledIndex) {
76
+ return selectedIndex < 0 ? firstEnabledIndex : selectedIndex;
77
+ }
78
+ /** Moves a host's highlight to the list's start row, then back to it each
79
+ * time the selected or first enabled row changes, such as when the
80
+ * accounts' sign-in states arrive. */
81
+ function useClaudeAccountStartRow(panel, setActive) {
82
+ const { selectedIndex, firstEnabledIndex } = panel;
83
+ useEffect(() => {
84
+ setActive(startIndexOf(selectedIndex, firstEnabledIndex));
85
+ }, [
86
+ selectedIndex,
87
+ firstEnabledIndex,
88
+ setActive
89
+ ]);
90
+ }
91
+ function signInHint(claudeLogin, t) {
92
+ return claudeLogin ? null : t("claude.loginOnHost");
93
+ }
94
+ function accountDetail(account, hint) {
95
+ if (account.signInRequired && hint !== null) return {
96
+ kind: "signInHint",
97
+ text: hint
98
+ };
99
+ return account.email ? {
100
+ kind: "email",
101
+ text: account.email
102
+ } : null;
103
+ }
104
+ /** The Claude Code accounts on a machine, and the steps a panel listing them
105
+ * takes: adding, signing in, removing after a confirmation the host shows,
106
+ * and choosing one for the `account` setting. */
107
+ function useClaudeAccountPanel(calls, { machine, machineName, sessionId, claudeInstalled, claudeAllowed, claudeLogin = false, claudeAccountRemove = false, account, onClose }) {
108
+ const t = usePwCodeTranslations("agents");
109
+ const [adding, setAdding] = useState(false);
110
+ const [signIn, setSignIn] = useState(null);
111
+ const [removing, setRemoving] = useState(null);
112
+ const [refreshError, setRefreshError] = useState(null);
113
+ const [refreshingModels, setRefreshingModels] = useState(false);
114
+ const available = claudeAllowed && claudeInstalled;
115
+ const catalog = calls.useClaudeAccounts(machine, sessionId, available);
116
+ const refreshModels = calls.useRefreshClaudeModels(machine, sessionId);
117
+ const deleteAccount = calls.useRemoveClaudeAccount(machine, sessionId);
118
+ const selected = account.value || void 0;
119
+ const disabled = useRef(account.disabled);
120
+ disabled.current = account.disabled;
121
+ useEffect(() => {
122
+ if (!available || !claudeLogin) {
123
+ setSignIn(null);
124
+ setAdding(false);
125
+ }
126
+ }, [available, claudeLogin]);
127
+ useEffect(() => {
128
+ if (!available || !claudeAccountRemove) setRemoving(null);
129
+ }, [available, claudeAccountRemove]);
130
+ const refresh = async (signedInAccount) => {
131
+ const signedInSelected = signedInAccount !== void 0 && signedInAccount === selected;
132
+ setRefreshError(null);
133
+ setRefreshingModels(true);
134
+ try {
135
+ await Promise.all([
136
+ catalog.refresh(),
137
+ claudeLogin && refreshModels(selected).catch((cause) => {
138
+ if (signedInSelected || !claudeSignInRequired(cause)) throw cause;
139
+ }),
140
+ ...signedInAccount !== void 0 && !signedInSelected && claudeLogin ? [refreshModels(signedInAccount)] : []
141
+ ]);
142
+ } catch (cause) {
143
+ setRefreshError(cause);
144
+ } finally {
145
+ setRefreshingModels(false);
146
+ }
147
+ };
148
+ const select = (name) => {
149
+ account.onChange(name);
150
+ onClose();
151
+ };
152
+ const unlessDisabled = (run) => () => {
153
+ if (!disabled.current) run();
154
+ };
155
+ const actions = (a) => {
156
+ if (account.disabled) return [];
157
+ const entries = [];
158
+ if (!a.signInRequired) entries.push({
159
+ kind: "use",
160
+ label: t("claude.useAccount"),
161
+ destructive: false,
162
+ run: unlessDisabled(() => select(a.name))
163
+ });
164
+ if (claudeLogin) entries.push({
165
+ kind: a.signInRequired ? "signIn" : "signInAgain",
166
+ label: a.signInRequired ? t("claude.signIn") : t("claude.signInAgain"),
167
+ destructive: false,
168
+ run: unlessDisabled(() => setSignIn(a.name))
169
+ });
170
+ if (claudeAccountRemove && a.name !== "default") entries.push({
171
+ kind: "remove",
172
+ label: t("claude.remove"),
173
+ destructive: true,
174
+ run: unlessDisabled(() => setRemoving(a.name))
175
+ });
176
+ return entries;
177
+ };
178
+ const view = signIn !== null && claudeLogin ? {
179
+ kind: "signIn",
180
+ account: signIn
181
+ } : adding ? { kind: "add" } : removing !== null ? {
182
+ kind: "remove",
183
+ account: removing
184
+ } : { kind: "list" };
185
+ const hint = signInHint(claudeLogin, t);
186
+ const canAdd = claudeLogin && !account.disabled;
187
+ return {
188
+ available,
189
+ notice: unavailableNotice(claudeAllowed, claudeInstalled, t),
190
+ view,
191
+ ...viewWords(view, machineName, hint, t),
192
+ emptyHint: hint,
193
+ accounts: catalog.accounts,
194
+ loading: catalog.loading,
195
+ loadedUsage: catalog.loadedUsage,
196
+ error: catalog.error || refreshError,
197
+ empty: !catalog.loading && !catalog.error && catalog.accounts.length === 0,
198
+ refreshing: catalog.refreshing || refreshingModels,
199
+ canAdd,
200
+ ...listControls(view, available, canAdd),
201
+ ...startRows(catalog.accounts, account.value, claudeLogin),
202
+ isDisabled: (a) => !!account.disabled || !!a.signInRequired && !claudeLogin,
203
+ detail: (a) => accountDetail(a, hint),
204
+ choose: (a) => {
205
+ if (a.signInRequired && claudeLogin) {
206
+ setSignIn(a.name);
207
+ return;
208
+ }
209
+ select(a.name);
210
+ },
211
+ select,
212
+ actions,
213
+ add: () => setAdding(true),
214
+ startSignIn: (name) => {
215
+ setSignIn(name);
216
+ setAdding(false);
217
+ },
218
+ finishSignIn: () => {
219
+ if (signIn !== null) refresh(signIn);
220
+ },
221
+ selectSignedIn: view.kind === "signIn" && !account.disabled ? () => select(view.account) : void 0,
222
+ back: () => {
223
+ if (view.kind === "signIn") {
224
+ setSignIn(null);
225
+ refresh();
226
+ } else if (view.kind === "remove") setRemoving(null);
227
+ else setAdding(false);
228
+ },
229
+ refresh: () => refresh(),
230
+ removeAccount: async (name) => {
231
+ await deleteAccount(name);
232
+ if (account.value === name && !account.disabled) account.onChange("default");
233
+ setRemoving(null);
234
+ }
235
+ };
236
+ }
237
+ /** The confirmation of a removal: whether it runs, and why it last failed. */
238
+ function useClaudeAccountRemoval(remove) {
239
+ const [pending, setPending] = useState(false);
240
+ const [error, setError] = useState(null);
241
+ const confirm = async () => {
242
+ setPending(true);
243
+ setError(null);
244
+ try {
245
+ await remove();
246
+ } catch (cause) {
247
+ setError(cause);
248
+ } finally {
249
+ setPending(false);
250
+ }
251
+ };
252
+ return {
253
+ pending,
254
+ error,
255
+ confirm
256
+ };
257
+ }
258
+ /** The name field of a new account, which continues to its sign-in only with
259
+ * a name Claude Code can take. */
260
+ function useClaudeAccountName(onContinue) {
261
+ const [name, setName] = useState("");
262
+ const [invalid, setInvalid] = useState(false);
263
+ return {
264
+ name,
265
+ invalid,
266
+ change: (value) => {
267
+ setName(value);
268
+ setInvalid(false);
269
+ },
270
+ submit: () => {
271
+ const valid = claudeAccountName(name);
272
+ if (valid === null) {
273
+ setInvalid(true);
274
+ return;
275
+ }
276
+ setInvalid(false);
277
+ onContinue(valid);
278
+ }
279
+ };
280
+ }
281
+ /** An account's usage limits as its row words them. */
282
+ function useClaudeAccountUsage(account, loaded) {
283
+ const t = usePwCodeTranslations("agents");
284
+ const format = useFormatter();
285
+ const status = account.signInRequired ? t("claude.signedOut") : account.error ? t("claude.usageUnavailable") : !loaded ? t("claude.loadingUsage") : null;
286
+ if (status) return {
287
+ status,
288
+ limits: []
289
+ };
290
+ const reset = (resetsAt) => {
291
+ const at = resetsAt ? DateTime.fromISO(resetsAt) : null;
292
+ if (!at?.isValid) return null;
293
+ const minutes = Math.max(0, Math.ceil(at.diffNow("minutes").minutes));
294
+ const unit = minutes >= 1440 ? "day" : minutes >= 60 ? "hour" : "minute";
295
+ const duration = format.number(Math.ceil(minutes / (unit === "day" ? 1440 : unit === "hour" ? 60 : 1)), {
296
+ style: "unit",
297
+ unit,
298
+ unitDisplay: "narrow"
299
+ });
300
+ return {
301
+ at: t("claude.resets", { time: format.dateTime(at.toJSDate(), {
302
+ weekday: "short",
303
+ month: "short",
304
+ day: "numeric",
305
+ hour: "numeric",
306
+ minute: "2-digit",
307
+ timeZoneName: "short"
308
+ }) }),
309
+ countdown: t("claude.resetsIn", { time: duration }),
310
+ shortCountdown: t("claude.resetsInShort", { time: duration })
311
+ };
312
+ };
313
+ return {
314
+ status: null,
315
+ limits: [{
316
+ window: "fiveHour",
317
+ label: t("claude.fiveHourColumn"),
318
+ used: account.fiveHourUsedPercent,
319
+ reset: reset(account.fiveHourResetsAt)
320
+ }, {
321
+ window: "week",
322
+ label: t("claude.weekColumn"),
323
+ used: account.weeklyUsedPercent,
324
+ reset: reset(account.weeklyResetsAt)
325
+ }]
326
+ };
327
+ }
328
+ export { claudeAccountName, claudeSignInRequired, useClaudeAccountName, useClaudeAccountPanel, useClaudeAccountRemoval, useClaudeAccountStartRow, useClaudeAccountUsage };
package/dist/claudeApi.js CHANGED
@@ -59,7 +59,7 @@ function claudeLoginFinished(status) {
59
59
  return status !== "running" && status !== "checking";
60
60
  }
61
61
  /** Aborts after `ms`, or with `signal`. Built by hand where AbortSignal has no
62
- * `timeout` or `any`, as React Native's polyfill has neither. */
62
+ * `timeout` or `any`, as React Native's before 0.87 had neither. */
63
63
  function deadline(ms, signal) {
64
64
  if (typeof AbortSignal.timeout === "function" && (!signal || typeof AbortSignal.any === "function")) {
65
65
  const timeout = AbortSignal.timeout(ms);
@@ -0,0 +1,80 @@
1
+ import { type ClaudeLogin, type claudeApi } from './claudeApi.js';
2
+ /** The sign-in calls of `createPwCodeApi`. */
3
+ export type ClaudeSignInCalls = Pick<ReturnType<typeof claudeApi>, 'startClaudeLogin' | 'followClaudeLogin' | 'writeClaudeLogin' | 'cancelClaudeLogin'>;
4
+ export interface ClaudeTerminalSize {
5
+ columns: number;
6
+ rows: number;
7
+ }
8
+ /** The host's terminal that Claude Code's sign-in prompt runs in. */
9
+ export interface ClaudeSignInTerminal {
10
+ /** Its size in cells, read as the sign-in starts and on `resized`. */
11
+ size: () => ClaudeTerminalSize;
12
+ /** Output as Claude Code printed it, escape sequences included. */
13
+ write?: (bytes: Uint8Array) => void;
14
+ /** Clears the screen: the output before this is gone. */
15
+ reset?: () => void;
16
+ /** Whether what is typed into it reaches Claude Code. */
17
+ setInputEnabled?: (enabled: boolean) => void;
18
+ /** Called once the sign-in has started and waits for input. */
19
+ focus?: () => void;
20
+ }
21
+ export interface ClaudeSignInState {
22
+ /** Bumped by `retry`, which starts a new sign-in; give each attempt a fresh terminal. */
23
+ attempt: number;
24
+ login: ClaudeLogin | null;
25
+ /** Why starting, following or writing failed. */
26
+ error: unknown;
27
+ /** Earlier output was dropped, so the screen was cleared. */
28
+ truncated: boolean;
29
+ /** The last input was refused for not fitting the queue. */
30
+ inputTooLong: boolean;
31
+ /** The sign-in page's address, as Claude Code last printed it. */
32
+ link: string | null;
33
+ /** The address to offer opening the sign-in page at: `link`, while the
34
+ * sign-in runs. */
35
+ signInPage: string | null;
36
+ /** What to do, until the sign-in completes. */
37
+ instructions: string | null;
38
+ /** That earlier output was dropped, until the sign-in completes. */
39
+ truncatedNote: string | null;
40
+ /** Leaving the view: back once the sign-in finished, cancelling it before. */
41
+ closeLabel: string;
42
+ /** The last 8192 characters of output since the screen was last cleared. */
43
+ output: string;
44
+ acceptsInput: boolean;
45
+ starting: boolean;
46
+ signedIn: boolean;
47
+ finished: boolean;
48
+ /** `onUse`, offered only once the account is signed in. */
49
+ use: (() => void) | undefined;
50
+ /** Following broke while the sign-in still runs. */
51
+ canReconnect: boolean;
52
+ /** The sign-in never started or ended without signing in. */
53
+ canRetry: boolean;
54
+ /** Where the sign-in stands, in words. */
55
+ status: string | null;
56
+ /** Queues text, such as a pasted code (Enter is `\r`); false when refused. */
57
+ input: (data: string) => boolean;
58
+ /** Sends the terminal's new size, if it changed while the sign-in runs. */
59
+ resized: () => void;
60
+ /** Follows the sign-in again from the last output read. */
61
+ reconnect: () => void;
62
+ retry: () => void;
63
+ }
64
+ /** Whether a link in the sign-in's output may be opened: web addresses only,
65
+ * never a script or a local file. */
66
+ export declare function canOpenSignInLink(uri: string): boolean;
67
+ /** Runs Claude Code's sign-in for `account` on a machine: starts it at the
68
+ * terminal's size, follows its output into the terminal, sends what is typed,
69
+ * and cancels it when the host leaves before it finishes. */
70
+ export declare function useClaudeSignIn(calls: ClaudeSignInCalls, { machine, machineName, sessionId, account, terminal, onSignedIn, onUse, }: {
71
+ machine: string;
72
+ machineName: string;
73
+ sessionId: string | undefined;
74
+ account: string;
75
+ terminal: ClaudeSignInTerminal;
76
+ onSignedIn?: (() => void) | undefined;
77
+ /** Makes the account the one in use, such as `useClaudeAccountPanel`'s
78
+ * `selectSignedIn`; unset where it can't be. */
79
+ onUse?: (() => void) | undefined;
80
+ }): ClaudeSignInState;
@@ -0,0 +1,249 @@
1
+ import { base64ToBytes, bytesToBase64 } from "./base64.js";
2
+ import { claudeLoginFinished } from "./claudeApi.js";
3
+ import { usePwCodeTranslations } from "./messages.js";
4
+ import { useCallback, useEffect, useRef, useState } from "react";
5
+ // src/claudeSignIn.ts
6
+ var pendingStops = /* @__PURE__ */ new Map();
7
+ var signInUrl = /https:\/\/claude\.(?:ai|com)\/[\w\-.~:/?#[\]@!$&'()*+,;=%]+(?=[^\w\-.~:/?#[\]@!$&'()*+,;=%])/g;
8
+ var maxQueuedInput = 16384;
9
+ var inputChunk = 4096;
10
+ var inputBatchMs = 30;
11
+ /** Whether a link in the sign-in's output may be opened: web addresses only,
12
+ * never a script or a local file. */
13
+ function canOpenSignInLink(uri) {
14
+ return /^https?:\/\//i.test(uri);
15
+ }
16
+ /** Runs Claude Code's sign-in for `account` on a machine: starts it at the
17
+ * terminal's size, follows its output into the terminal, sends what is typed,
18
+ * and cancels it when the host leaves before it finishes. */
19
+ function useClaudeSignIn(calls, { machine, machineName, sessionId, account, terminal, onSignedIn, onUse }) {
20
+ const t = usePwCodeTranslations("agents");
21
+ const [attempt, setAttempt] = useState(0);
22
+ const [login, setLogin] = useState(null);
23
+ const [error, setError] = useState(null);
24
+ const [truncated, setTruncated] = useState(false);
25
+ const [inputTooLong, setInputTooLong] = useState(false);
26
+ const [link, setLink] = useState(null);
27
+ const [output, setOutput] = useState("");
28
+ const [acceptsInput, setAcceptsInput] = useState(false);
29
+ const running = useRef(null);
30
+ const latest = useRef({
31
+ calls,
32
+ terminal,
33
+ onSignedIn
34
+ });
35
+ latest.current = {
36
+ calls,
37
+ terminal,
38
+ onSignedIn
39
+ };
40
+ useEffect(() => {
41
+ const { calls } = latest.current;
42
+ const screen = () => latest.current.terminal;
43
+ let disposed = false;
44
+ let current = null;
45
+ let cursor = 0;
46
+ let pending = /* @__PURE__ */ new Uint8Array(0);
47
+ let queuedBytes = 0;
48
+ let writeEpoch = 0;
49
+ let writeFailed = false;
50
+ let inputEnabled = false;
51
+ let flushTimer;
52
+ let writes = Promise.resolve();
53
+ let reading;
54
+ let tail = "";
55
+ let sentSize = "";
56
+ const decoder = new TextDecoder();
57
+ setLogin(null);
58
+ setError(null);
59
+ setTruncated(false);
60
+ setInputTooLong(false);
61
+ setLink(null);
62
+ setOutput("");
63
+ setAcceptsInput(false);
64
+ const allowInput = (enabled) => {
65
+ inputEnabled = enabled;
66
+ screen().setInputEnabled?.(enabled);
67
+ setAcceptsInput(enabled);
68
+ };
69
+ const findLink = (bytes) => {
70
+ tail = (tail + decoder.decode(bytes, { stream: true })).slice(-8192);
71
+ const found = tail.match(signInUrl)?.at(-1);
72
+ if (found) setLink(found);
73
+ };
74
+ const receive = (event) => {
75
+ if (disposed) return;
76
+ if (event.offset > cursor || cursor > event.next) {
77
+ screen().reset?.();
78
+ tail = "";
79
+ setTruncated(true);
80
+ }
81
+ current = event.login;
82
+ allowInput(!writeFailed && current.status === "running");
83
+ setLogin(current);
84
+ if (event.data) {
85
+ const bytes = base64ToBytes(event.data);
86
+ screen().write?.(bytes);
87
+ findLink(bytes);
88
+ }
89
+ setOutput(tail);
90
+ cursor = event.next;
91
+ if (current.status === "signed_in") latest.current.onSignedIn?.();
92
+ };
93
+ const read = async () => {
94
+ if (!current || disposed) return;
95
+ reading?.abort();
96
+ const controller = new AbortController();
97
+ reading = controller;
98
+ writeFailed = false;
99
+ setError(null);
100
+ try {
101
+ await calls.followClaudeLogin(machine, current, cursor, controller.signal, receive);
102
+ } catch (cause) {
103
+ if (controller.signal.aborted) return;
104
+ allowInput(false);
105
+ setError(cause);
106
+ }
107
+ };
108
+ const send = (input, bytes = 0) => {
109
+ const id = current?.id;
110
+ if (!id || disposed) return;
111
+ const epoch = writeEpoch;
112
+ writes = writes.then(async () => {
113
+ if (!disposed && !writeFailed && epoch === writeEpoch && current?.status === "running") await calls.writeClaudeLogin(machine, id, input);
114
+ else if (input.columns) sentSize = "";
115
+ }).catch((cause) => {
116
+ if (input.columns) sentSize = "";
117
+ if (!disposed) {
118
+ writeEpoch++;
119
+ writeFailed = true;
120
+ allowInput(false);
121
+ setError(cause);
122
+ }
123
+ }).finally(() => {
124
+ queuedBytes -= bytes;
125
+ });
126
+ };
127
+ const flush = () => {
128
+ flushTimer = void 0;
129
+ const bytes = pending;
130
+ pending = /* @__PURE__ */ new Uint8Array(0);
131
+ for (let offset = 0; offset < bytes.length; offset += inputChunk) {
132
+ const chunk = bytes.subarray(offset, offset + inputChunk);
133
+ send({ data: bytesToBase64(chunk) }, chunk.length);
134
+ }
135
+ };
136
+ const input = (data) => {
137
+ if (!inputEnabled || current?.status !== "running" || disposed || writeFailed) return false;
138
+ const bytes = new TextEncoder().encode(data);
139
+ if (queuedBytes + bytes.length > maxQueuedInput) {
140
+ setInputTooLong(true);
141
+ return false;
142
+ }
143
+ queuedBytes += bytes.length;
144
+ setInputTooLong(false);
145
+ const buffer = new Uint8Array(pending.length + bytes.length);
146
+ buffer.set(pending);
147
+ buffer.set(bytes, pending.length);
148
+ pending = buffer;
149
+ flushTimer ??= setTimeout(flush, inputBatchMs);
150
+ return true;
151
+ };
152
+ const size = () => {
153
+ const { columns, rows } = screen().size();
154
+ return {
155
+ columns: Math.min(500, Math.max(1, columns)),
156
+ rows: Math.min(200, Math.max(1, rows))
157
+ };
158
+ };
159
+ const resized = () => {
160
+ const next = size();
161
+ const key = `${next.columns}x${next.rows}`;
162
+ if (current?.status === "running" && key !== sentSize) {
163
+ sentSize = key;
164
+ send(next);
165
+ }
166
+ };
167
+ running.current = {
168
+ input,
169
+ resized,
170
+ reconnect: () => {
171
+ read();
172
+ resized();
173
+ }
174
+ };
175
+ const key = JSON.stringify([
176
+ machine,
177
+ sessionId,
178
+ account
179
+ ]);
180
+ const previousStop = pendingStops.get(key);
181
+ const started = Promise.resolve().then(async () => {
182
+ await previousStop;
183
+ if (disposed) return;
184
+ const { columns, rows } = size();
185
+ sentSize = `${columns}x${rows}`;
186
+ return calls.startClaudeLogin(machine, account, sessionId, columns, rows);
187
+ });
188
+ started.then(async (event) => {
189
+ if (!event || disposed) return;
190
+ receive(event);
191
+ resized();
192
+ screen().focus?.();
193
+ await read();
194
+ }).catch((cause) => {
195
+ if (!disposed) setError(cause);
196
+ });
197
+ return () => {
198
+ disposed = true;
199
+ reading?.abort();
200
+ if (flushTimer) clearTimeout(flushTimer);
201
+ running.current = null;
202
+ const stopped = started.then(async (event) => {
203
+ const login = current ?? event?.login;
204
+ if (login && !claudeLoginFinished(login.status)) await calls.cancelClaudeLogin(machine, login.id);
205
+ }).catch(() => {});
206
+ pendingStops.set(key, stopped);
207
+ stopped.then(() => {
208
+ if (pendingStops.get(key) === stopped) pendingStops.delete(key);
209
+ });
210
+ };
211
+ }, [
212
+ machine,
213
+ account,
214
+ sessionId,
215
+ attempt
216
+ ]);
217
+ const input = useCallback((data) => running.current?.input(data) ?? false, []);
218
+ const resized = useCallback(() => running.current?.resized(), []);
219
+ const reconnect = useCallback(() => running.current?.reconnect(), []);
220
+ const retry = useCallback(() => setAttempt((value) => value + 1), []);
221
+ const finished = login ? claudeLoginFinished(login.status) : false;
222
+ const signedIn = login?.status === "signed_in";
223
+ return {
224
+ attempt,
225
+ login,
226
+ error,
227
+ truncated,
228
+ inputTooLong,
229
+ link,
230
+ signInPage: login?.status === "running" ? link : null,
231
+ instructions: signedIn ? null : t("claude.signInInstructions", { host: machineName }),
232
+ truncatedNote: truncated && !signedIn ? t("claude.terminalTruncated") : null,
233
+ closeLabel: finished ? t("claude.backToAccounts") : t("claude.cancelSignIn"),
234
+ output,
235
+ acceptsInput,
236
+ starting: !login && !error,
237
+ signedIn,
238
+ finished,
239
+ use: signedIn ? onUse : void 0,
240
+ canReconnect: Boolean(error) && !!login && !finished,
241
+ canRetry: Boolean(error) && !login || finished && !signedIn,
242
+ status: login ? t(`claude.signInStatus.${login.status}`, { email: login.email ?? account }) : null,
243
+ input,
244
+ resized,
245
+ reconnect,
246
+ retry
247
+ };
248
+ }
249
+ export { canOpenSignInLink, useClaudeSignIn };
@@ -1,4 +1,5 @@
1
- import { type PwCodeClient, type PwCodeResult, type Schemas } from './apiClient.js';
1
+ import type { ToolCallPart } from '@parallelworks/ui/ai/headless';
2
+ import type { PwCodeClient, PwCodeResult, Schemas } from './apiClient.js';
2
3
  import { type SlashAction } from './command.js';
3
4
  type Palette = Schemas['AgentPalette'];
4
5
  export type CommandOutcome = {
@@ -34,7 +35,16 @@ export interface SlashDeps {
34
35
  onRefused: (error: unknown) => void;
35
36
  }
36
37
  export declare const backgroundOfferDelayMs = 2000;
38
+ /** The tool whose running calls the machine can move to the background. */
39
+ export declare const BACKGROUND_TOOL = "Bash";
40
+ export declare function runsInBackgroundTool(part: Pick<ToolCallPart, 'name' | 'status'>): boolean;
41
+ /** The offer to move a turn's commands to the background sits under each of
42
+ * its running `BACKGROUND_TOOL` calls, once the session makes it. */
43
+ export declare function offersBackground(part: Pick<ToolCallPart, 'name' | 'status'>, background: {
44
+ offered: boolean;
45
+ } | null | undefined): boolean;
37
46
  export declare function commandsApi(client: PwCodeClient): {
47
+ runGoal: (machine: string, id: string, args: string) => Promise<PwCodeResult<Schemas['AgentGoalResult']>>;
38
48
  runSlashAction: (machine: string, id: string, action: Exclude<SlashAction, {
39
49
  kind: 'message' | 'archive';
40
50
  }>, planOnMachine: (path: string) => string) => Promise<CommandOutcome>;