@parallelworks/code 0.2.0 → 0.3.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 (83) hide show
  1. package/README.md +43 -10
  2. package/dist/ago.d.ts +8 -0
  3. package/dist/ago.js +26 -0
  4. package/dist/api.d.ts +78 -0
  5. package/dist/base64.d.ts +3 -0
  6. package/dist/base64.js +15 -0
  7. package/dist/chatHandoff.d.ts +12 -0
  8. package/dist/chatHandoff.js +27 -0
  9. package/dist/claudeAccounts.d.ts +112 -0
  10. package/dist/claudeAccounts.js +234 -0
  11. package/dist/claudeSignIn.d.ts +62 -0
  12. package/dist/claudeSignIn.js +239 -0
  13. package/dist/contextRow.d.ts +25 -0
  14. package/dist/contextRow.js +16 -0
  15. package/dist/createPwCodeApi.d.ts +8 -0
  16. package/dist/createPwCodeApi.js +2 -0
  17. package/dist/howSessionsAppear.d.ts +12 -0
  18. package/dist/howSessionsAppear.js +24 -0
  19. package/dist/index.d.ts +24 -1
  20. package/dist/index.js +24 -2
  21. package/dist/locales/en/agentTranscript.js +2 -10
  22. package/dist/locales/en/agents.js +5 -5
  23. package/dist/locales/en.d.ts +5 -13
  24. package/dist/locales/es/agentTranscript.js +2 -10
  25. package/dist/locales/es/agents.js +5 -5
  26. package/dist/locales/ja/agentTranscript.js +2 -10
  27. package/dist/locales/ja/agents.js +5 -5
  28. package/dist/locales/ko/agentTranscript.js +2 -10
  29. package/dist/locales/ko/agents.js +5 -5
  30. package/dist/locales/zh/agentTranscript.js +2 -10
  31. package/dist/locales/zh/agents.js +5 -5
  32. package/dist/machine.d.ts +2 -0
  33. package/dist/models.d.ts +47 -0
  34. package/dist/models.js +49 -0
  35. package/dist/notices.d.ts +2 -1
  36. package/dist/notices.js +29 -3
  37. package/dist/pullRequestList.d.ts +52 -0
  38. package/dist/pullRequestList.js +106 -0
  39. package/dist/session.d.ts +5 -0
  40. package/dist/sessionActions.d.ts +105 -0
  41. package/dist/sessionActions.js +178 -0
  42. package/dist/sessionGroups.d.ts +49 -0
  43. package/dist/sessionGroups.js +72 -0
  44. package/dist/sessionHeader.d.ts +14 -0
  45. package/dist/sessionHeader.js +16 -0
  46. package/dist/sessionList.d.ts +134 -0
  47. package/dist/sessionList.js +271 -0
  48. package/dist/sessionsApi.js +2 -4
  49. package/dist/settingsApi.d.ts +36 -0
  50. package/dist/settingsApi.js +151 -0
  51. package/dist/startSession.d.ts +138 -0
  52. package/dist/startSession.js +234 -0
  53. package/dist/terminalHandoffPanel.d.ts +30 -0
  54. package/dist/terminalHandoffPanel.js +33 -0
  55. package/dist/transcript.d.ts +2 -0
  56. package/dist/transcript.js +15 -12
  57. package/dist/usageLimit.d.ts +8 -0
  58. package/dist/usageLimit.js +13 -0
  59. package/dist/useAwayRecap.d.ts +30 -0
  60. package/dist/useAwayRecap.js +75 -0
  61. package/dist/useComposer.d.ts +121 -0
  62. package/dist/useComposer.js +244 -0
  63. package/dist/useComposerImages.d.ts +66 -0
  64. package/dist/useComposerImages.js +195 -0
  65. package/dist/useConversation.d.ts +190 -0
  66. package/dist/useConversation.js +287 -0
  67. package/dist/useSubagent.d.ts +58 -0
  68. package/dist/useSubagent.js +149 -0
  69. package/dist/workingDirectories.d.ts +32 -0
  70. package/dist/workingDirectories.js +71 -0
  71. package/dist/worktreeChoice.d.ts +31 -0
  72. package/dist/worktreeChoice.js +38 -0
  73. package/locales/en/agentTranscript.json +2 -10
  74. package/locales/en/agents.json +5 -5
  75. package/locales/es/agentTranscript.json +2 -10
  76. package/locales/es/agents.json +5 -5
  77. package/locales/ja/agentTranscript.json +2 -10
  78. package/locales/ja/agents.json +5 -5
  79. package/locales/ko/agentTranscript.json +2 -10
  80. package/locales/ko/agents.json +5 -5
  81. package/locales/zh/agentTranscript.json +2 -10
  82. package/locales/zh/agents.json +5 -5
  83. package/package.json +3 -3
package/README.md CHANGED
@@ -15,8 +15,10 @@ pnpm add @parallelworks/code @parallelworks/ui react openapi-fetch swr use-intl
15
15
  ```
16
16
 
17
17
  `@parallelworks/ui`, `react`, `openapi-fetch`, `swr` and `use-intl` are peer
18
- dependencies. Only `@parallelworks/ui/ai/headless` is imported from the ui
19
- package, for the message and part types and the reducers that build them.
18
+ dependencies. Only the ui package's two entries without a DOM are imported:
19
+ `@parallelworks/ui/ai/headless`, for the message and part types and the
20
+ reducers that build them, and `@parallelworks/ui/headless`, for its duration
21
+ format, its strings and its clock.
20
22
 
21
23
  ## What is in it
22
24
 
@@ -48,17 +50,47 @@ package, for the message and part types and the reducers that build them.
48
50
  (`isMachineDown`, `canStartHere`), the folders a machine's sessions suggest
49
51
  (`recentDirectories`), and the command that picks a session up in a terminal
50
52
  (`terminalHandoff`).
53
+ - Starting a session, as hooks a host draws its own start screen over:
54
+ where it starts (`useStartLocation`, `startMachines`), the permission mode
55
+ it starts in (`useStartPermissionMode`, `startingMode`), its model,
56
+ allocation and Claude Code account (`useStartModel`), and the start itself
57
+ with its first prompt and images (`useStartSession`). The host passes in its
58
+ saved preferences and opens the session once it starts.
59
+ - The models a session can run (`isClaudeModel`, `runsClaude`, `canRunModel`,
60
+ `modelLabel`), the picker a typed command opens (`pickerCommand`), and the
61
+ machine's Claude models a model picker offers (`useModelCatalog`).
62
+ - A session's working directories: the path helpers that cut a long path to
63
+ fit (`pathSegments`, `shortestPath`, `cutToFit`, `cutSpacing`,
64
+ `lastSegmentAt`), where a directory is saved (`isSavedDirectory`,
65
+ `directoryScopes`), what an approval allowed in one (`allowedAccess`), and
66
+ closing one added for the session only (`useRemoveSessionDirectory`).
67
+ - The choice to keep or remove a session's worktree when the session is
68
+ deleted (`useWorktreeChoice`), and what removing it would delete
69
+ (`worktreeWork`).
51
70
  - Where typed text goes (`slashAction`, `shellCommand`) and the commands a
52
71
  session offers (`paletteOptions`), read from the structural `PwCodePalette`.
53
72
  - The short label of a pull or merge request link (`pullRequestLabel`,
54
- `pastedPullRequestLabel`).
73
+ `pastedPullRequestLabel`), and how a session's pull requests are listed:
74
+ their order (`orderPullRequests`), which fold into a count and how the
75
+ counts read (`foldPullRequests`, `donePullRequestsToFold`,
76
+ `pullRequestGroupState`, `pullRequestWords`), and the row of directories
77
+ and pull requests under a session's title (`sessionContextRow`).
78
+ - What a session's header offers: picking the session up in a terminal
79
+ (`terminalHandoffPanel`), the line a turn shows while it waits for a usage
80
+ limit (`useUsageLimitWait`), the worktree the session works in, read again
81
+ when it moves (`useFollowedWorktree`), and how sessions get listed
82
+ (`howSessionsAppear`).
55
83
  - The messages a session is shown in, in English, Spanish, Japanese, Korean
56
84
  and Chinese (`loadPwCodeMessages`), and the words built from them: a
57
85
  session's label and status (`sessionLabel`, `sessionStateText`), why a
58
86
  machine can't be reached (`machineHint`), what the composer says while it is
59
87
  locked (`composerState`), and the transcript's own lines
60
- (`useTranscriptWords`, `useCompactionNotice`, `useRecapNotice`,
61
- `useToolStrings`).
88
+ (`useTranscriptWords`, `useGoalNotice`, `useCompactionNotice`,
89
+ `useRecapNotice`, `useToolStrings`).
90
+ - How long ago something happened, as "5m", for labels passed as strings
91
+ (`useCompactAgo`). It reads `@parallelworks/ui`'s `time` strings, which a
92
+ host sets on `UIProvider`, or on `UIStringsProvider` where there is no DOM,
93
+ and re-reads every 30 seconds on the ui package's clock.
62
94
 
63
95
  ## Messages
64
96
 
@@ -184,9 +216,9 @@ function useSession(machine: string, sessionId: string) {
184
216
  `steer` hands text to the turn that is running and `withdraw` takes a queued
185
217
  message back; without them every message sent during a turn waits for it to
186
218
  end. `goalNotice`, `compactionNotice`, `recapNotice` and `words` supply the
187
- transcript's own lines in the reader's language: `useCompactionNotice()`,
188
- `useRecapNotice()` and `useTranscriptWords()` give them from this package's
189
- messages. `imageUrl` turns an image's `ref` into the URL the host serves it
219
+ transcript's own lines in the reader's language: `useGoalNotice()`,
220
+ `useCompactionNotice()`, `useRecapNotice()` and `useTranscriptWords()` give
221
+ them from this package's messages. `imageUrl` turns an image's `ref` into the URL the host serves it
190
222
  from.
191
223
 
192
224
  On the web, `SessionView` from `@parallelworks/ui/ai` draws these messages. A
@@ -195,8 +227,9 @@ host with its own components renders `ChatMessage` and its parts itself.
195
227
  ## No DOM
196
228
 
197
229
  The build imports `react`, `luxon`, `swr`, `use-intl`, `gemoji` (for the
198
- emoji shortcodes in a session's name) and `@parallelworks/ui/ai/headless`, and
199
- its declarations `openapi-fetch` too, and nothing else, so it loads where there
230
+ emoji shortcodes in a session's name), `@parallelworks/ui/ai/headless` and
231
+ `@parallelworks/ui/headless`, and its declarations `openapi-fetch` too, and
232
+ nothing else, so it loads where there
200
233
  is no DOM: a React Native bundle, a server, a test. It opens sockets only
201
234
  through the host's `openSocket`. The reducers need no React at all.
202
235
 
package/dist/ago.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** "5m" since a time, in `@parallelworks/ui`'s `time` strings as a compact
2
+ * RelativeTime reads, for labels built into sentences and passed as strings.
3
+ * It re-reads every 30 seconds. */
4
+ export declare function useCompactAgo(): {
5
+ now: number;
6
+ compact: (iso: string | undefined) => string;
7
+ compactMinutes: (minutes: number) => string;
8
+ };
package/dist/ago.js ADDED
@@ -0,0 +1,26 @@
1
+ import { useCallback, useMemo } from "react";
2
+ import { DateTime } from "luxon";
3
+ import { useClock, useStrings } from "@parallelworks/ui/headless";
4
+ // src/ago.ts
5
+ /** "5m" since a time, in `@parallelworks/ui`'s `time` strings as a compact
6
+ * RelativeTime reads, for labels built into sentences and passed as strings.
7
+ * It re-reads every 30 seconds. */
8
+ function useCompactAgo() {
9
+ const t = useStrings().time;
10
+ const tick = useClock((current) => Math.floor(current / 3e4));
11
+ const now = useMemo(() => DateTime.now().toMillis(), [tick]);
12
+ const compactMinutes = useCallback((minutes) => {
13
+ if (!Number.isFinite(minutes) || minutes < 1) return t.now;
14
+ if (minutes < 60) return t.minutes(minutes);
15
+ const hours = Math.floor(minutes / 60);
16
+ if (hours < 24) return t.hours(hours);
17
+ const days = Math.floor(hours / 24);
18
+ return days < 365 ? t.days(days) : t.years(Math.floor(days / 365));
19
+ }, [t]);
20
+ return {
21
+ now,
22
+ compact: useCallback((iso) => iso ? compactMinutes(Math.floor((now - DateTime.fromISO(iso).toMillis()) / 6e4)) : "", [now, compactMinutes]),
23
+ compactMinutes
24
+ };
25
+ }
26
+ export { useCompactAgo };
package/dist/api.d.ts CHANGED
@@ -722,6 +722,28 @@ export interface paths {
722
722
  patch?: never;
723
723
  trace?: never;
724
724
  };
725
+ "/api/code/machines/{machine}/sessions/{id}/settings": {
726
+ parameters: {
727
+ query?: never;
728
+ header?: never;
729
+ path?: never;
730
+ cookie?: never;
731
+ };
732
+ get?: never;
733
+ put?: never;
734
+ post?: never;
735
+ delete?: never;
736
+ options?: never;
737
+ head?: never;
738
+ /**
739
+ * Change a running pw code session's model, effort, allocation or authority
740
+ * @description > This is a user-centric route, so the response will always be in the context of the currently authenticated user.
741
+ *
742
+ * Changes what a live session runs as, and answers with its new state. The machine's daemon decides whether it is allowed: the session must be live, an org provider model needs an allocation, and a session already running above the remote permission ceiling can only be changed from the machine itself.
743
+ */
744
+ patch: operations["update-agent-session-settings"];
745
+ trace?: never;
746
+ };
725
747
  "/api/code/machines/{machine}/sessions/{id}/shell": {
726
748
  parameters: {
727
749
  query?: never;
@@ -1321,6 +1343,24 @@ export interface components {
1321
1343
  /** @description Id of one of the reader's groups, as their preferences name it. */
1322
1344
  group: string;
1323
1345
  };
1346
+ AgentSessionSettingsBody: {
1347
+ /** @description Allocation to bill; the daemon requires one for org provider models. */
1348
+ allocation?: string;
1349
+ /** @description An existing Claude Code account on the machine; applies after the current turn. */
1350
+ claudeAccount?: string;
1351
+ /**
1352
+ * @description Reasoning effort from the session's next turn on: low, medium, high, xhigh or max, which a model runs at the nearest level it takes. default, none and minimal are earlier names for high, low and low.
1353
+ * @enum {string}
1354
+ */
1355
+ effort?: "default" | "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
1356
+ /** @description Model id to switch the session to. */
1357
+ model?: string;
1358
+ /**
1359
+ * @description Authority the session runs with; the machine refuses anything above its remoteMaxPermissionMode.
1360
+ * @enum {string}
1361
+ */
1362
+ permissionMode?: "read-only" | "accept-edits" | "auto" | "bypass-permissions";
1363
+ };
1324
1364
  AgentSessionWorktree: {
1325
1365
  /** @description The branch git made for the worktree. */
1326
1366
  branch?: string;
@@ -3050,6 +3090,44 @@ export interface operations {
3050
3090
  };
3051
3091
  };
3052
3092
  };
3093
+ "update-agent-session-settings": {
3094
+ parameters: {
3095
+ query?: never;
3096
+ header?: never;
3097
+ path: {
3098
+ /** @description Machine id from the machines list. */
3099
+ machine: string;
3100
+ /** @description Session id as the daemon reports it. */
3101
+ id: string;
3102
+ };
3103
+ cookie?: never;
3104
+ };
3105
+ requestBody: {
3106
+ content: {
3107
+ "application/json": components["schemas"]["AgentSessionSettingsBody"];
3108
+ };
3109
+ };
3110
+ responses: {
3111
+ /** @description OK */
3112
+ 200: {
3113
+ headers: {
3114
+ [name: string]: unknown;
3115
+ };
3116
+ content: {
3117
+ "application/json": components["schemas"]["SessionState"];
3118
+ };
3119
+ };
3120
+ /** @description Error */
3121
+ default: {
3122
+ headers: {
3123
+ [name: string]: unknown;
3124
+ };
3125
+ content: {
3126
+ "application/json": components["schemas"]["Error"];
3127
+ };
3128
+ };
3129
+ };
3130
+ };
3053
3131
  "run-agent-session-shell": {
3054
3132
  parameters: {
3055
3133
  query?: never;
@@ -0,0 +1,3 @@
1
+ export declare function bytesToBase64(bytes: Uint8Array): string;
2
+ /** Decodes base64, URL-safe or not, padded or not. */
3
+ export declare function base64ToBytes(data: string): Uint8Array;
package/dist/base64.js ADDED
@@ -0,0 +1,15 @@
1
+ // src/base64.ts
2
+ function bytesToBase64(bytes) {
3
+ let binary = "";
4
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
5
+ return btoa(binary);
6
+ }
7
+ /** Decodes base64, URL-safe or not, padded or not. */
8
+ function base64ToBytes(data) {
9
+ const base64 = data.replace(/-/g, "+").replace(/_/g, "/");
10
+ const binary = atob(base64 + "=".repeat((4 - base64.length % 4) % 4));
11
+ const bytes = new Uint8Array(binary.length);
12
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
13
+ return bytes;
14
+ }
15
+ export { base64ToBytes, bytesToBase64 };
@@ -0,0 +1,12 @@
1
+ import type { PwCodeTranslator } from './messages.js';
2
+ /** The parts of an AI chat conversation a session started from it reads. */
3
+ export interface PwCodeHandoffChat {
4
+ title?: string | null | undefined;
5
+ messages?: readonly {
6
+ role: string;
7
+ content?: string | null | undefined;
8
+ }[] | null | undefined;
9
+ }
10
+ /** The first turn of a session started from a chat: the reader's task, then
11
+ * the conversation it continues, newest messages kept when it is long. */
12
+ export declare function chatHandoffPrompt(conversation: PwCodeHandoffChat, task: string, t: PwCodeTranslator<'agents'>): string;
@@ -0,0 +1,27 @@
1
+ // src/chatHandoff.ts
2
+ var HANDOFF_MAX_CHARS = 5e4;
3
+ /** The first turn of a session started from a chat: the reader's task, then
4
+ * the conversation it continues, newest messages kept when it is long. */
5
+ function chatHandoffPrompt(conversation, task, t) {
6
+ const turns = (conversation.messages ?? []).flatMap((m) => {
7
+ const text = m.content?.trim();
8
+ if (!text || m.role !== "user" && m.role !== "assistant") return [];
9
+ return [`## ${m.role === "user" ? t("start.handoffUser") : t("start.handoffAssistant")}\n\n${text}`];
10
+ });
11
+ const kept = [];
12
+ let size = 0;
13
+ for (let i = turns.length - 1; i >= 0; i--) {
14
+ const turn = turns[i] ?? "";
15
+ if (kept.length > 0 && size + turn.length > HANDOFF_MAX_CHARS) break;
16
+ kept.unshift(turn);
17
+ size += turn.length;
18
+ }
19
+ const omitted = turns.length - kept.length;
20
+ return [
21
+ task.trim() || t("start.handoffDefaultTask"),
22
+ t("start.handoffIntro", { title: conversation.title || "" }),
23
+ ...omitted > 0 ? [t("start.handoffOmitted", { count: omitted })] : [],
24
+ kept.join("\n\n")
25
+ ].join("\n\n");
26
+ }
27
+ export { chatHandoffPrompt };
@@ -0,0 +1,112 @@
1
+ import type { BoundSetting } from '@parallelworks/ui/ai/headless';
2
+ import type { Schemas } from './apiClient.js';
3
+ import type { claudeApi } from './claudeApi.js';
4
+ export type ClaudeAccount = Schemas['AgentClaudeAccount'];
5
+ /** The account hooks of `createPwCodeApi`. */
6
+ export type ClaudeAccountCalls = Pick<ReturnType<typeof claudeApi>, 'useClaudeAccounts' | 'useRefreshClaudeModels' | 'useRemoveClaudeAccount'>;
7
+ /** What the account panel shows: the list, or one step taken from it. */
8
+ export type ClaudeAccountView = {
9
+ kind: 'list';
10
+ } | {
11
+ kind: 'add';
12
+ } | {
13
+ kind: 'signIn';
14
+ account: string;
15
+ } | {
16
+ kind: 'remove';
17
+ account: string;
18
+ };
19
+ export interface ClaudeAccountAction {
20
+ kind: 'use' | 'signIn' | 'signInAgain' | 'remove';
21
+ label: string;
22
+ destructive: boolean;
23
+ run: () => void;
24
+ }
25
+ export interface ClaudeAccountPanelState {
26
+ /** Claude Code is allowed and installed on the machine. */
27
+ available: boolean;
28
+ view: ClaudeAccountView;
29
+ accounts: ClaudeAccount[];
30
+ loading: boolean;
31
+ loadedUsage: boolean;
32
+ /** Why the list or its last refresh failed. */
33
+ error: unknown;
34
+ /** Loaded, without error, and holding no account. */
35
+ empty: boolean;
36
+ refreshing: boolean;
37
+ canAdd: boolean;
38
+ isDisabled: (account: ClaudeAccount) => boolean;
39
+ /** Picks a row: an account that needs signing in opens its sign-in. */
40
+ choose: (account: ClaudeAccount) => void;
41
+ /** Makes the account the setting's value and closes the panel. */
42
+ select: (name: string) => void;
43
+ /** What a row's menu offers, empty while the setting can't change. */
44
+ actions: (account: ClaudeAccount) => ClaudeAccountAction[];
45
+ add: () => void;
46
+ startSignIn: (name: string) => void;
47
+ /** Reloads the list and models once the sign-in shown has completed. */
48
+ finishSignIn: () => void;
49
+ /** Selects the account just signed in, unless the setting can't change. */
50
+ selectSignedIn: (() => void) | undefined;
51
+ /** Leaves the step shown for the list; leaving a sign-in reloads it. */
52
+ back: () => void;
53
+ refresh: () => Promise<void>;
54
+ /** Signs the account out and deletes it, then returns to the list. A
55
+ * selected account falls back to `default`. */
56
+ removeAccount: (name: string) => Promise<void>;
57
+ }
58
+ /** The refusal of a read that needs the account signed in first. */
59
+ export declare function claudeSignInRequired(error: unknown): boolean;
60
+ /** The account name `input` gives once trimmed, or null when Claude Code
61
+ * can't take it. */
62
+ export declare function claudeAccountName(input: string): string | null;
63
+ /** The Claude Code accounts on a machine, and the steps a panel listing them
64
+ * takes: adding, signing in, removing after a confirmation the host shows,
65
+ * and choosing one for the `account` setting. */
66
+ export declare function useClaudeAccountPanel(calls: ClaudeAccountCalls, { machine, sessionId, claudeInstalled, claudeAllowed, claudeLogin, claudeAccountRemove, account, onClose, }: {
67
+ machine: string;
68
+ sessionId?: string | undefined;
69
+ claudeInstalled: boolean;
70
+ claudeAllowed: boolean;
71
+ /** The machine can sign accounts in from here. */
72
+ claudeLogin?: boolean | undefined;
73
+ /** The machine can remove accounts from here. */
74
+ claudeAccountRemove?: boolean | undefined;
75
+ account: BoundSetting;
76
+ onClose: () => void;
77
+ }): ClaudeAccountPanelState;
78
+ /** The confirmation of a removal: whether it runs, and why it last failed. */
79
+ export declare function useClaudeAccountRemoval(remove: () => Promise<void>): {
80
+ pending: boolean;
81
+ error: unknown;
82
+ confirm: () => Promise<void>;
83
+ };
84
+ /** The name field of a new account, which continues to its sign-in only with
85
+ * a name Claude Code can take. */
86
+ export declare function useClaudeAccountName(onContinue: (name: string) => void): {
87
+ name: string;
88
+ invalid: boolean;
89
+ change: (value: string) => void;
90
+ submit: () => void;
91
+ };
92
+ export interface ClaudeUsageReset {
93
+ /** When, as "resets Fri, Oct 30, 5:00 PM". */
94
+ at: string;
95
+ countdown: string;
96
+ /** The countdown for a narrow row. */
97
+ shortCountdown: string;
98
+ }
99
+ export interface ClaudeUsageLimit {
100
+ window: 'fiveHour' | 'week';
101
+ label: string;
102
+ /** Percent of the window used; undefined when not reported. */
103
+ used: number | undefined;
104
+ reset: ClaudeUsageReset | null;
105
+ }
106
+ export interface ClaudeAccountUsage {
107
+ /** Shown in place of the limits, which are then empty. */
108
+ status: string | null;
109
+ limits: ClaudeUsageLimit[];
110
+ }
111
+ /** An account's usage limits as its row words them. */
112
+ export declare function useClaudeAccountUsage(account: ClaudeAccount, loaded: boolean): ClaudeAccountUsage;
@@ -0,0 +1,234 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { DateTime } from "luxon";
4
+ import { useFormatter } from "use-intl";
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
+ /** The Claude Code accounts on a machine, and the steps a panel listing them
19
+ * takes: adding, signing in, removing after a confirmation the host shows,
20
+ * and choosing one for the `account` setting. */
21
+ function useClaudeAccountPanel(calls, { machine, sessionId, claudeInstalled, claudeAllowed, claudeLogin = false, claudeAccountRemove = false, account, onClose }) {
22
+ const t = usePwCodeTranslations("agents");
23
+ const [adding, setAdding] = useState(false);
24
+ const [signIn, setSignIn] = useState(null);
25
+ const [removing, setRemoving] = useState(null);
26
+ const [refreshError, setRefreshError] = useState(null);
27
+ const [refreshingModels, setRefreshingModels] = useState(false);
28
+ const available = claudeAllowed && claudeInstalled;
29
+ const catalog = calls.useClaudeAccounts(machine, sessionId, available);
30
+ const refreshModels = calls.useRefreshClaudeModels(machine, sessionId);
31
+ const deleteAccount = calls.useRemoveClaudeAccount(machine, sessionId);
32
+ const selected = account.value || void 0;
33
+ const disabled = useRef(account.disabled);
34
+ disabled.current = account.disabled;
35
+ useEffect(() => {
36
+ if (!available || !claudeLogin) {
37
+ setSignIn(null);
38
+ setAdding(false);
39
+ }
40
+ }, [available, claudeLogin]);
41
+ useEffect(() => {
42
+ if (!available || !claudeAccountRemove) setRemoving(null);
43
+ }, [available, claudeAccountRemove]);
44
+ const refresh = async (signedInAccount) => {
45
+ const signedInSelected = signedInAccount !== void 0 && signedInAccount === selected;
46
+ setRefreshError(null);
47
+ setRefreshingModels(true);
48
+ try {
49
+ await Promise.all([
50
+ catalog.refresh(),
51
+ claudeLogin && refreshModels(selected).catch((cause) => {
52
+ if (signedInSelected || !claudeSignInRequired(cause)) throw cause;
53
+ }),
54
+ ...signedInAccount !== void 0 && !signedInSelected && claudeLogin ? [refreshModels(signedInAccount)] : []
55
+ ]);
56
+ } catch (cause) {
57
+ setRefreshError(cause);
58
+ } finally {
59
+ setRefreshingModels(false);
60
+ }
61
+ };
62
+ const select = (name) => {
63
+ account.onChange(name);
64
+ onClose();
65
+ };
66
+ const unlessDisabled = (run) => () => {
67
+ if (!disabled.current) run();
68
+ };
69
+ const actions = (a) => {
70
+ if (account.disabled) return [];
71
+ const entries = [];
72
+ if (!a.signInRequired) entries.push({
73
+ kind: "use",
74
+ label: t("claude.useAccount"),
75
+ destructive: false,
76
+ run: unlessDisabled(() => select(a.name))
77
+ });
78
+ if (claudeLogin) entries.push({
79
+ kind: a.signInRequired ? "signIn" : "signInAgain",
80
+ label: a.signInRequired ? t("claude.signIn") : t("claude.signInAgain"),
81
+ destructive: false,
82
+ run: unlessDisabled(() => setSignIn(a.name))
83
+ });
84
+ if (claudeAccountRemove && a.name !== "default") entries.push({
85
+ kind: "remove",
86
+ label: t("claude.remove"),
87
+ destructive: true,
88
+ run: unlessDisabled(() => setRemoving(a.name))
89
+ });
90
+ return entries;
91
+ };
92
+ const view = signIn !== null && claudeLogin ? {
93
+ kind: "signIn",
94
+ account: signIn
95
+ } : adding ? { kind: "add" } : removing !== null ? {
96
+ kind: "remove",
97
+ account: removing
98
+ } : { kind: "list" };
99
+ return {
100
+ available,
101
+ view,
102
+ accounts: catalog.accounts,
103
+ loading: catalog.loading,
104
+ loadedUsage: catalog.loadedUsage,
105
+ error: catalog.error || refreshError,
106
+ empty: !catalog.loading && !catalog.error && catalog.accounts.length === 0,
107
+ refreshing: catalog.refreshing || refreshingModels,
108
+ canAdd: claudeLogin && !account.disabled,
109
+ isDisabled: (a) => !!account.disabled || !!a.signInRequired && !claudeLogin,
110
+ choose: (a) => {
111
+ if (a.signInRequired && claudeLogin) {
112
+ setSignIn(a.name);
113
+ return;
114
+ }
115
+ select(a.name);
116
+ },
117
+ select,
118
+ actions,
119
+ add: () => setAdding(true),
120
+ startSignIn: (name) => {
121
+ setSignIn(name);
122
+ setAdding(false);
123
+ },
124
+ finishSignIn: () => {
125
+ if (signIn !== null) refresh(signIn);
126
+ },
127
+ selectSignedIn: view.kind === "signIn" && !account.disabled ? () => select(view.account) : void 0,
128
+ back: () => {
129
+ if (view.kind === "signIn") {
130
+ setSignIn(null);
131
+ refresh();
132
+ } else if (view.kind === "remove") setRemoving(null);
133
+ else setAdding(false);
134
+ },
135
+ refresh: () => refresh(),
136
+ removeAccount: async (name) => {
137
+ await deleteAccount(name);
138
+ if (account.value === name && !account.disabled) account.onChange("default");
139
+ setRemoving(null);
140
+ }
141
+ };
142
+ }
143
+ /** The confirmation of a removal: whether it runs, and why it last failed. */
144
+ function useClaudeAccountRemoval(remove) {
145
+ const [pending, setPending] = useState(false);
146
+ const [error, setError] = useState(null);
147
+ const confirm = async () => {
148
+ setPending(true);
149
+ setError(null);
150
+ try {
151
+ await remove();
152
+ } catch (cause) {
153
+ setError(cause);
154
+ } finally {
155
+ setPending(false);
156
+ }
157
+ };
158
+ return {
159
+ pending,
160
+ error,
161
+ confirm
162
+ };
163
+ }
164
+ /** The name field of a new account, which continues to its sign-in only with
165
+ * a name Claude Code can take. */
166
+ function useClaudeAccountName(onContinue) {
167
+ const [name, setName] = useState("");
168
+ const [invalid, setInvalid] = useState(false);
169
+ return {
170
+ name,
171
+ invalid,
172
+ change: (value) => {
173
+ setName(value);
174
+ setInvalid(false);
175
+ },
176
+ submit: () => {
177
+ const valid = claudeAccountName(name);
178
+ if (valid === null) {
179
+ setInvalid(true);
180
+ return;
181
+ }
182
+ setInvalid(false);
183
+ onContinue(valid);
184
+ }
185
+ };
186
+ }
187
+ /** An account's usage limits as its row words them. */
188
+ function useClaudeAccountUsage(account, loaded) {
189
+ const t = usePwCodeTranslations("agents");
190
+ const format = useFormatter();
191
+ const status = account.signInRequired ? t("claude.signedOut") : account.error ? t("claude.usageUnavailable") : !loaded ? t("claude.loadingUsage") : null;
192
+ if (status) return {
193
+ status,
194
+ limits: []
195
+ };
196
+ const reset = (resetsAt) => {
197
+ const at = resetsAt ? DateTime.fromISO(resetsAt) : null;
198
+ if (!at?.isValid) return null;
199
+ const minutes = Math.max(0, Math.ceil(at.diffNow("minutes").minutes));
200
+ const unit = minutes >= 1440 ? "day" : minutes >= 60 ? "hour" : "minute";
201
+ const duration = format.number(Math.ceil(minutes / (unit === "day" ? 1440 : unit === "hour" ? 60 : 1)), {
202
+ style: "unit",
203
+ unit,
204
+ unitDisplay: "narrow"
205
+ });
206
+ return {
207
+ at: t("claude.resets", { time: format.dateTime(at.toJSDate(), {
208
+ weekday: "short",
209
+ month: "short",
210
+ day: "numeric",
211
+ hour: "numeric",
212
+ minute: "2-digit",
213
+ timeZoneName: "short"
214
+ }) }),
215
+ countdown: t("claude.resetsIn", { time: duration }),
216
+ shortCountdown: t("claude.resetsInShort", { time: duration })
217
+ };
218
+ };
219
+ return {
220
+ status: null,
221
+ limits: [{
222
+ window: "fiveHour",
223
+ label: t("claude.fiveHourColumn"),
224
+ used: account.fiveHourUsedPercent,
225
+ reset: reset(account.fiveHourResetsAt)
226
+ }, {
227
+ window: "week",
228
+ label: t("claude.weekColumn"),
229
+ used: account.weeklyUsedPercent,
230
+ reset: reset(account.weeklyResetsAt)
231
+ }]
232
+ };
233
+ }
234
+ export { claudeAccountName, claudeSignInRequired, useClaudeAccountName, useClaudeAccountPanel, useClaudeAccountRemoval, useClaudeAccountUsage };