@parallelworks/code 0.3.0 → 0.5.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 (118) hide show
  1. package/README.md +625 -113
  2. package/dist/accountApi.d.ts +31 -0
  3. package/dist/accountApi.js +182 -0
  4. package/dist/agentSwitcher.d.ts +120 -0
  5. package/dist/agentSwitcher.js +187 -0
  6. package/dist/ago.d.ts +1 -3
  7. package/dist/ago.js +8 -10
  8. package/dist/allocations.d.ts +41 -0
  9. package/dist/allocations.js +76 -0
  10. package/dist/api.d.ts +1319 -50
  11. package/dist/chatStrings.d.ts +189 -0
  12. package/dist/chatStrings.js +218 -0
  13. package/dist/claudeAccounts.d.ts +57 -2
  14. package/dist/claudeAccounts.js +144 -6
  15. package/dist/claudeApi.d.ts +2 -1
  16. package/dist/claudeApi.js +50 -4
  17. package/dist/claudeSignIn.d.ts +19 -1
  18. package/dist/claudeSignIn.js +12 -2
  19. package/dist/command.d.ts +5 -1
  20. package/dist/command.js +6 -1
  21. package/dist/commandsApi.d.ts +11 -1
  22. package/dist/commandsApi.js +24 -5
  23. package/dist/createPwCodeApi.d.ts +114 -6
  24. package/dist/createPwCodeApi.js +21 -3
  25. package/dist/directories.d.ts +161 -0
  26. package/dist/directories.js +301 -0
  27. package/dist/goal.d.ts +89 -0
  28. package/dist/goal.js +164 -0
  29. package/dist/imageFit.d.ts +23 -0
  30. package/dist/imageFit.js +27 -0
  31. package/dist/images.d.ts +28 -0
  32. package/dist/images.js +38 -6
  33. package/dist/index.d.ts +31 -15
  34. package/dist/index.js +29 -14
  35. package/dist/loadError.d.ts +8 -0
  36. package/dist/loadError.js +19 -0
  37. package/dist/locales/en/agentTranscript.js +74 -12
  38. package/dist/locales/en/agents.js +86 -11
  39. package/dist/locales/en.d.ts +137 -8
  40. package/dist/locales/es/agentTranscript.js +74 -12
  41. package/dist/locales/es/agents.js +86 -11
  42. package/dist/locales/ja/agentTranscript.js +77 -15
  43. package/dist/locales/ja/agents.js +60 -122
  44. package/dist/locales/ko/agentTranscript.js +74 -12
  45. package/dist/locales/ko/agents.js +86 -11
  46. package/dist/locales/zh/agentTranscript.js +72 -10
  47. package/dist/locales/zh/agents.js +86 -11
  48. package/dist/machine.d.ts +2 -0
  49. package/dist/modelPicker.d.ts +79 -0
  50. package/dist/modelPicker.js +107 -0
  51. package/dist/notices.d.ts +2 -0
  52. package/dist/notices.js +67 -32
  53. package/dist/platformDefaults.d.ts +22 -0
  54. package/dist/platformDefaults.js +30 -0
  55. package/dist/preferences.d.ts +78 -0
  56. package/dist/preferences.js +128 -0
  57. package/dist/pullRequestList.d.ts +10 -2
  58. package/dist/pullRequestList.js +41 -22
  59. package/dist/query.d.ts +9 -2
  60. package/dist/query.js +91 -10
  61. package/dist/session.d.ts +11 -2
  62. package/dist/session.js +16 -8
  63. package/dist/sessionActions.d.ts +11 -1
  64. package/dist/sessionActions.js +14 -6
  65. package/dist/sessionEvents.d.ts +37 -5
  66. package/dist/sessionEvents.js +196 -77
  67. package/dist/sessionGroups.d.ts +5 -4
  68. package/dist/sessionGroups.js +6 -5
  69. package/dist/sessionHeader.js +6 -2
  70. package/dist/sessionList.d.ts +68 -15
  71. package/dist/sessionList.js +91 -19
  72. package/dist/sessionScreen.d.ts +197 -0
  73. package/dist/sessionScreen.js +218 -0
  74. package/dist/sessionsApi.d.ts +29 -3
  75. package/dist/sessionsApi.js +180 -33
  76. package/dist/sessionsFeed.d.ts +22 -0
  77. package/dist/sessionsFeed.js +125 -0
  78. package/dist/settingsApi.d.ts +3 -1
  79. package/dist/startPage.d.ts +153 -0
  80. package/dist/startPage.js +174 -0
  81. package/dist/startSession.d.ts +41 -7
  82. package/dist/startSession.js +26 -4
  83. package/dist/todos.d.ts +42 -0
  84. package/dist/todos.js +104 -0
  85. package/dist/transcript.d.ts +1 -2
  86. package/dist/transcript.js +111 -117
  87. package/dist/transcriptRead.d.ts +56 -0
  88. package/dist/transcriptRead.js +121 -0
  89. package/dist/types.d.ts +11 -1
  90. package/dist/useComposer.d.ts +39 -6
  91. package/dist/useComposer.js +73 -9
  92. package/dist/useComposerImages.d.ts +5 -0
  93. package/dist/useComposerImages.js +27 -5
  94. package/dist/useComposerPastes.d.ts +70 -0
  95. package/dist/useComposerPastes.js +125 -0
  96. package/dist/useConversation.d.ts +16 -1
  97. package/dist/useConversation.js +104 -10
  98. package/dist/useMounted.d.ts +3 -0
  99. package/dist/useMounted.js +14 -0
  100. package/dist/useSubagent.d.ts +51 -3
  101. package/dist/useSubagent.js +72 -7
  102. package/dist/useTranscript.d.ts +23 -3
  103. package/dist/useTranscript.js +76 -19
  104. package/dist/wording.d.ts +5 -2
  105. package/dist/wording.js +8 -6
  106. package/dist/workingDirectories.d.ts +31 -0
  107. package/dist/workingDirectories.js +25 -1
  108. package/locales/en/agentTranscript.json +68 -11
  109. package/locales/en/agents.json +82 -10
  110. package/locales/es/agentTranscript.json +68 -11
  111. package/locales/es/agents.json +82 -10
  112. package/locales/ja/agentTranscript.json +71 -14
  113. package/locales/ja/agents.json +82 -10
  114. package/locales/ko/agentTranscript.json +68 -11
  115. package/locales/ko/agents.json +82 -10
  116. package/locales/zh/agentTranscript.json +66 -9
  117. package/locales/zh/agents.json +82 -10
  118. package/package.json +6 -3
@@ -0,0 +1,31 @@
1
+ import { type Dispatch, type SetStateAction } from 'react';
2
+ import type { PwCodeApiError, PwCodeClient, PwCodeQuery, Schemas } from './apiClient.js';
3
+ /** The preview that turns pw code on, for the reader or the whole platform. */
4
+ export declare const PW_CODE_PREVIEW = "agents";
5
+ /** Whether pw code is on for the reader: its preview is, for them or for the
6
+ * whole platform. Its routes answer 404 otherwise. */
7
+ export declare function pwCodeEnabled(previews: readonly Pick<Schemas['Preview'], 'preview'>[] | null | undefined): boolean;
8
+ /** The platform's models, as the gateway offers them to the reader. */
9
+ export interface PwCodePlatformModels {
10
+ /** Empty until they load. */
11
+ models: Schemas['ModelEntry'][];
12
+ /** The connections that cannot serve their models, such as one whose key
13
+ * is rejected. */
14
+ providerIssues: Schemas['ProviderIssue'][];
15
+ /** The list has answered, or failed to. */
16
+ loaded: boolean;
17
+ isLoading: boolean;
18
+ error: PwCodeApiError | undefined;
19
+ /** Asks for the list again. */
20
+ refresh: () => void;
21
+ }
22
+ export interface PwCodeAccountOptions {
23
+ /** Called when a preference failed to save; it shows its saved value again. */
24
+ onPreferenceError?: ((error: unknown) => void) | undefined;
25
+ }
26
+ export declare function accountApi(client: PwCodeClient, { onPreferenceError }?: PwCodeAccountOptions): {
27
+ usePlatformModels: () => PwCodePlatformModels;
28
+ useAllocations: (read?: boolean) => PwCodeQuery<Schemas['Allocation'][] | null>;
29
+ usePwCodeEnabled: () => boolean | undefined;
30
+ usePreference: <T>(key: string, fallback: T) => [T, Dispatch<SetStateAction<T>>];
31
+ };
@@ -0,0 +1,182 @@
1
+ import { preferenceKey } from "./preferences.js";
2
+ import { createQuery } from "./query.js";
3
+ import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
4
+ import useSWR from "swr";
5
+ // src/accountApi.ts
6
+ /** The preview that turns pw code on, for the reader or the whole platform. */
7
+ var PW_CODE_PREVIEW = "agents";
8
+ /** Whether pw code is on for the reader: its preview is, for them or for the
9
+ * whole platform. Its routes answer 404 otherwise. */
10
+ function pwCodeEnabled(previews) {
11
+ return previews?.some((p) => p.preview === "agents") ?? false;
12
+ }
13
+ var WRITE_DELAY_MS = 500;
14
+ var READ_RETRY_MS = 5e3;
15
+ var PREFERENCES_INIT = {};
16
+ function accountApi(client, { onPreferenceError } = {}) {
17
+ const useQuery = createQuery(client);
18
+ function usePlatformModels() {
19
+ const { data, error, isLoading, mutate } = useQuery("/api/openai/v1/models", void 0);
20
+ const refresh = useCallback(() => void mutate(), [mutate]);
21
+ return {
22
+ models: data?.data ?? [],
23
+ providerIssues: data?.provider_issues ?? [],
24
+ loaded: data !== void 0 || error !== void 0,
25
+ isLoading,
26
+ error,
27
+ refresh
28
+ };
29
+ }
30
+ /** The reader's allocations, every kind, once `read`. */
31
+ function useAllocations(read = true) {
32
+ return useQuery("/api/allocations", read ? void 0 : null);
33
+ }
34
+ const readPreviews = async () => {
35
+ const { data, error } = await client.GET("/api/previews");
36
+ if (error) throw error;
37
+ return data;
38
+ };
39
+ /** Whether pw code is on for the reader; undefined until the previews load. */
40
+ function usePwCodeEnabled() {
41
+ const { data } = useSWR("/api/previews", readPreviews);
42
+ return data === void 0 ? void 0 : pwCodeEnabled(data);
43
+ }
44
+ const unsaved = /* @__PURE__ */ new Map();
45
+ const waiting = /* @__PURE__ */ new Map();
46
+ const pending = /* @__PURE__ */ new Map();
47
+ const listeners = /* @__PURE__ */ new Set();
48
+ let revision = 0;
49
+ let flushTimer;
50
+ let retryTimer;
51
+ let writing = false;
52
+ let mutateCopy;
53
+ function changed() {
54
+ revision += 1;
55
+ for (const listener of listeners) listener();
56
+ }
57
+ function subscribe(listener) {
58
+ listeners.add(listener);
59
+ return () => {
60
+ listeners.delete(listener);
61
+ if (listeners.size === 0) stopRetry();
62
+ };
63
+ }
64
+ function current(key, copy, fallback) {
65
+ if (unsaved.has(key)) return unsaved.get(key);
66
+ const saved = copy?.preferences[key];
67
+ return saved === void 0 ? fallback : saved;
68
+ }
69
+ function settled(batch) {
70
+ for (const [key, value] of Object.entries(batch)) if (!pending.has(key) && unsaved.get(key) === value) unsaved.delete(key);
71
+ changed();
72
+ }
73
+ async function flush() {
74
+ flushTimer = void 0;
75
+ if (pending.size === 0 || writing) return;
76
+ const batch = Object.fromEntries(pending);
77
+ pending.clear();
78
+ writing = true;
79
+ try {
80
+ const { data, error } = await client.PATCH("/api/user/preferences", { body: { preferences: batch } });
81
+ if (error) {
82
+ settled(batch);
83
+ onPreferenceError?.(error);
84
+ return;
85
+ }
86
+ await mutateCopy?.(data, { revalidate: false });
87
+ settled(batch);
88
+ } catch (thrown) {
89
+ settled(batch);
90
+ onPreferenceError?.(thrown);
91
+ } finally {
92
+ writing = false;
93
+ if (pending.size > 0 && !flushTimer) flushTimer = setTimeout(flush, 0);
94
+ }
95
+ }
96
+ function save(key, value) {
97
+ unsaved.set(key, value);
98
+ pending.set(key, value);
99
+ if (flushTimer) clearTimeout(flushTimer);
100
+ flushTimer = setTimeout(flush, WRITE_DELAY_MS);
101
+ }
102
+ function applyWaiting(copy) {
103
+ stopRetry();
104
+ if (waiting.size === 0) return;
105
+ for (const [key, { fallback, updates }] of waiting) save(key, updates.reduce((previous, update) => update(previous), current(key, copy, fallback)));
106
+ waiting.clear();
107
+ changed();
108
+ }
109
+ function retryRead(read) {
110
+ if (retryTimer) return;
111
+ retryTimer = setTimeout(() => {
112
+ retryTimer = void 0;
113
+ if (waiting.size > 0) read().catch(() => {});
114
+ }, READ_RETRY_MS);
115
+ }
116
+ function stopRetry() {
117
+ clearTimeout(retryTimer);
118
+ retryTimer = void 0;
119
+ }
120
+ function hold(key, update, fallback) {
121
+ const held = waiting.get(key) ?? {
122
+ fallback,
123
+ updates: []
124
+ };
125
+ waiting.set(key, {
126
+ ...held,
127
+ updates: [...held.updates, update]
128
+ });
129
+ }
130
+ function update(key, step, fallback, copy) {
131
+ if (!copy && !unsaved.has(key)) {
132
+ hold(key, step, fallback);
133
+ return;
134
+ }
135
+ save(key, step(current(key, copy, fallback)));
136
+ }
137
+ function change(key, next, fallback, copy, mutate) {
138
+ mutateCopy = mutate;
139
+ if (copy) applyWaiting(copy);
140
+ if (typeof next === "function") update(key, next, fallback, copy);
141
+ else {
142
+ waiting.delete(key);
143
+ save(key, next);
144
+ }
145
+ changed();
146
+ }
147
+ /** A choice kept in the reader's account, as `useState` returns it: the
148
+ * value saved under `key`, or `fallback` until one is, and a setter that
149
+ * shows the change at once and saves it shortly after. An update computed
150
+ * from the previous value waits for the account's copy, and is shown and
151
+ * saved once it loads; a read that failed is retried meanwhile. A key
152
+ * with a dot is saved with a colon in its place, which the account
153
+ * requires. */
154
+ function usePreference(key, fallback) {
155
+ const accountKey = preferenceKey(key);
156
+ const { data, error, mutate } = useQuery("/api/user/preferences", PREFERENCES_INIT);
157
+ useSyncExternalStore(subscribe, () => revision);
158
+ const copy = useRef(data);
159
+ copy.current = data;
160
+ const start = useRef(fallback);
161
+ start.current = fallback;
162
+ const holding = waiting.size > 0;
163
+ useEffect(() => {
164
+ if (data) applyWaiting(data);
165
+ else if (error && holding) retryRead(mutate);
166
+ }, [
167
+ data,
168
+ error,
169
+ holding,
170
+ mutate
171
+ ]);
172
+ const set = useCallback((next) => change(accountKey, next, start.current, copy.current, mutate), [accountKey, mutate]);
173
+ return [current(accountKey, data, fallback), set];
174
+ }
175
+ return {
176
+ usePlatformModels,
177
+ useAllocations,
178
+ usePwCodeEnabled,
179
+ usePreference
180
+ };
181
+ }
182
+ export { PW_CODE_PREVIEW, accountApi, pwCodeEnabled };
@@ -0,0 +1,120 @@
1
+ import type { Schemas } from './apiClient.js';
2
+ import type { PwCodeSubagentUsage } from './types.js';
3
+ import type { PwCodeConversation, PwCodeConversationState } from './useConversation.js';
4
+ /** One subagent as the switcher lists it. */
5
+ export interface PwCodeSwitcherAgent {
6
+ id: string;
7
+ /** As the daemon names it; unset for a plain task. */
8
+ agentType?: string | undefined;
9
+ description: string;
10
+ status: 'running' | 'done' | 'failed' | 'stopped';
11
+ awaitingApproval: boolean;
12
+ /** Started in the turn under way or the last one, not an earlier one. */
13
+ current: boolean;
14
+ startedAt?: string | undefined;
15
+ endedAt?: string | undefined;
16
+ tokens: number;
17
+ }
18
+ /** `usage` is the feed's latest count, which the listing trails. As in the
19
+ * terminal, the context is counted once, not each request's rereading of it. */
20
+ export declare function switcherAgent(sub: Schemas['Subagent'], usage?: PwCodeSubagentUsage): PwCodeSwitcherAgent;
21
+ /** How a subagent stands: an approval it waits on outranks its status. */
22
+ export type PwCodeAgentState = PwCodeSwitcherAgent['status'] | 'approval';
23
+ /** The tone a state's word is said in, which the host maps to its own colors. */
24
+ export type PwCodeStateTone = 'warning' | 'error' | 'muted';
25
+ /** An agent at work shows a turning mark, as a session does. Any other shows
26
+ * a dot in its state's tone, pulsing while it waits on the reader and unlit
27
+ * once it was stopped or rests. */
28
+ export declare function agentMark(state: PwCodeAgentState | PwCodeConversationState): {
29
+ working: true;
30
+ } | {
31
+ working: false;
32
+ tone: 'warning' | 'error' | 'success' | 'muted';
33
+ pulse: boolean;
34
+ off: boolean;
35
+ };
36
+ /** `explore`, or the transcript's word for a task with no type of its own. */
37
+ export declare function useAgentTypeLabel(): (agentType: string | undefined) => string;
38
+ /** One subagent wherever it is named: its type, what it was asked, and how it stands. */
39
+ export interface PwCodeAgentLine {
40
+ agent: PwCodeSwitcherAgent;
41
+ type: string;
42
+ description: string;
43
+ state: PwCodeAgentState;
44
+ stateWord: string;
45
+ stateTone: PwCodeStateTone;
46
+ /** The state needs the reader, so it is said in words beside its mark. */
47
+ flagged: boolean;
48
+ /** Still running, so it can be stopped; once it is not, it can be taken off the list instead. */
49
+ stoppable: boolean;
50
+ /** Names the agent, for a stop button among others. */
51
+ stopLabel: string;
52
+ /** Names the agent, for a button among others that takes it off the list. */
53
+ dismissLabel: string;
54
+ }
55
+ export declare function usePwCodeAgentLine(): (agent: PwCodeSwitcherAgent) => PwCodeAgentLine;
56
+ /** Takes an agent that is not running off the session's list, resolving to
57
+ * whether it went. The main conversation comes back into view when the agent
58
+ * that went is the one in view by then, since the reader may have opened
59
+ * another meanwhile, and only while the screen that asked is still open. */
60
+ export declare function useDismissSubagent(conversation: Pick<PwCodeConversation, 'dismissSubagent'>, { viewing, showMain, }: {
61
+ /** The subagent in view; null for the main conversation. */
62
+ viewing: string | null;
63
+ showMain: () => void;
64
+ }): (id: string) => Promise<boolean>;
65
+ /** A subagent's row in the switcher's list. */
66
+ export interface PwCodeSwitcherRow extends PwCodeAgentLine {
67
+ /** How long it has run, or ran; null before it started. */
68
+ elapsed: string | null;
69
+ /** Its tokens, compact; null while it has used none. */
70
+ tokens: string | null;
71
+ viewing: boolean;
72
+ /** From an earlier turn and folded away with the rest of them. */
73
+ folded: boolean;
74
+ }
75
+ /** A count in the switcher's header, and the agent its button opens. */
76
+ export interface PwCodeSwitcherCount {
77
+ count: number;
78
+ label: string;
79
+ first: string;
80
+ }
81
+ export interface PwCodeAgentSwitcher {
82
+ main: {
83
+ state: PwCodeConversationState;
84
+ stateWord: string;
85
+ stateTone: PwCodeStateTone;
86
+ /** Waits on an approval, so it is said in words beside its mark. */
87
+ flagged: boolean;
88
+ viewing: boolean;
89
+ };
90
+ /** This turn's agents, then earlier ones. */
91
+ agents: PwCodeSwitcherRow[];
92
+ /** The row that unfolds the earlier agents; null when there are none. */
93
+ earlier: {
94
+ count: number;
95
+ label: string;
96
+ } | null;
97
+ /** What the turn's agents are doing, in one line. */
98
+ summary: string;
99
+ /** An agent runs without waiting on the reader. */
100
+ working: boolean;
101
+ /** Agents waiting on an approval, from any turn. */
102
+ approvals: PwCodeSwitcherCount | null;
103
+ /** This turn's agents that failed. */
104
+ failed: PwCodeSwitcherCount | null;
105
+ /** Agents still running, approvals pending or not, which stopping all would stop. */
106
+ running: number;
107
+ }
108
+ /** A session's subagents as a switcher shows them, beside its main
109
+ * conversation. While the list is open and an agent runs, the elapsed times
110
+ * tick each second. */
111
+ export declare function usePwCodeAgentSwitcher({ agents, mainState, viewing, open, earlierOpen, }: {
112
+ agents: readonly PwCodeSwitcherAgent[];
113
+ mainState: PwCodeConversationState;
114
+ /** The subagent in view; null for the main conversation. */
115
+ viewing: string | null;
116
+ /** Whether the list is shown. */
117
+ open: boolean;
118
+ /** Whether the earlier turns' agents are unfolded. */
119
+ earlierOpen: boolean;
120
+ }): PwCodeAgentSwitcher;
@@ -0,0 +1,187 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { turnDuration } from "./notices.js";
3
+ import { useMounted } from "./useMounted.js";
4
+ import { useCallback, useMemo, useRef } from "react";
5
+ import { sanitizeLabel } from "@parallelworks/ui/ai/headless";
6
+ import { useFormatter } from "use-intl";
7
+ import { DateTime } from "luxon";
8
+ import { useClock } from "@parallelworks/ui/headless";
9
+ // src/agentSwitcher.ts
10
+ /** `usage` is the feed's latest count, which the listing trails. As in the
11
+ * terminal, the context is counted once, not each request's rereading of it. */
12
+ function switcherAgent(sub, usage) {
13
+ const used = usage ?? sub.usage;
14
+ return {
15
+ id: sub.id,
16
+ agentType: sub.agentType,
17
+ description: sub.description || sub.id,
18
+ status: sub.status,
19
+ awaitingApproval: sub.awaitingApproval === true,
20
+ current: sub.current === true,
21
+ startedAt: sub.startedAt,
22
+ endedAt: sub.endedAt,
23
+ tokens: (used?.latestInputTokens ?? 0) + (used?.outputTokens ?? 0)
24
+ };
25
+ }
26
+ function agentState(agent) {
27
+ return agent.awaitingApproval ? "approval" : agent.status;
28
+ }
29
+ function stateTone(state) {
30
+ return state === "approval" ? "warning" : state === "failed" ? "error" : "muted";
31
+ }
32
+ /** An agent at work shows a turning mark, as a session does. Any other shows
33
+ * a dot in its state's tone, pulsing while it waits on the reader and unlit
34
+ * once it was stopped or rests. */
35
+ function agentMark(state) {
36
+ if (state === "running") return { working: true };
37
+ return {
38
+ working: false,
39
+ tone: state === "done" ? "success" : stateTone(state),
40
+ pulse: state === "approval",
41
+ off: state === "stopped" || state === "idle"
42
+ };
43
+ }
44
+ /** `explore`, or the transcript's word for a task with no type of its own. */
45
+ function useAgentTypeLabel() {
46
+ const t = usePwCodeTranslations("agentTranscript");
47
+ return useCallback((agentType) => agentType && agentType !== "default" ? sanitizeLabel(agentType) : t("transcript.subagent"), [t]);
48
+ }
49
+ var flagged = (state) => state === "approval" || state === "failed";
50
+ function stateWord(state, t) {
51
+ switch (state) {
52
+ case "approval": return t("switcher.approval");
53
+ case "running": return t("switcher.running");
54
+ case "failed": return t("switcher.failed");
55
+ case "stopped": return t("switcher.stopped");
56
+ case "done": return t("switcher.done");
57
+ default: return t("switcher.idle");
58
+ }
59
+ }
60
+ function usePwCodeAgentLine() {
61
+ const t = usePwCodeTranslations("agents");
62
+ const typeLabel = useAgentTypeLabel();
63
+ return useCallback((agent) => {
64
+ const state = agentState(agent);
65
+ const type = typeLabel(agent.agentType);
66
+ const description = sanitizeLabel(agent.description);
67
+ const name = t("switcher.agentName", {
68
+ type,
69
+ description
70
+ });
71
+ return {
72
+ agent,
73
+ type,
74
+ description,
75
+ state,
76
+ stateWord: stateWord(state, t),
77
+ stateTone: stateTone(state),
78
+ flagged: flagged(state),
79
+ stoppable: agent.status === "running",
80
+ stopLabel: t("switcher.stop", { name }),
81
+ dismissLabel: t("switcher.dismiss", { name })
82
+ };
83
+ }, [t, typeLabel]);
84
+ }
85
+ /** Takes an agent that is not running off the session's list, resolving to
86
+ * whether it went. The main conversation comes back into view when the agent
87
+ * that went is the one in view by then, since the reader may have opened
88
+ * another meanwhile, and only while the screen that asked is still open. */
89
+ function useDismissSubagent(conversation, { viewing, showMain }) {
90
+ const inView = useRef(viewing);
91
+ inView.current = viewing;
92
+ const mounted = useMounted();
93
+ const { dismissSubagent } = conversation;
94
+ return useCallback(async (id) => {
95
+ const taken = await dismissSubagent(id);
96
+ if (taken && mounted.current && id === inView.current) showMain();
97
+ return taken;
98
+ }, [
99
+ dismissSubagent,
100
+ mounted,
101
+ showMain
102
+ ]);
103
+ }
104
+ function elapsedMs(agent, nowSeconds) {
105
+ if (!agent.startedAt) return null;
106
+ const started = DateTime.fromISO(agent.startedAt).toMillis();
107
+ const ended = agent.endedAt ? DateTime.fromISO(agent.endedAt).toMillis() : nowSeconds * 1e3;
108
+ return Math.max(0, ended - started);
109
+ }
110
+ /** Failed agents and those awaiting approval are left out: the header counts
111
+ * them on their own. */
112
+ function turnSummary(current, t) {
113
+ const tally = (status) => current.filter((a) => a.status === status && !a.awaitingApproval).length;
114
+ const running = tally("running");
115
+ const done = tally("done");
116
+ const stopped = tally("stopped");
117
+ return [
118
+ running > 0 && t("switcher.runningCount", { count: running }),
119
+ done > 0 && t("switcher.doneCount", { count: done }),
120
+ stopped > 0 && t("switcher.stoppedCount", { count: stopped })
121
+ ].filter(Boolean).join(" · ");
122
+ }
123
+ function switcherCount(agents, label) {
124
+ const [first] = agents;
125
+ return first ? {
126
+ count: agents.length,
127
+ label: label(agents.length),
128
+ first: first.id
129
+ } : null;
130
+ }
131
+ /** A session's subagents as a switcher shows them, beside its main
132
+ * conversation. While the list is open and an agent runs, the elapsed times
133
+ * tick each second. */
134
+ function usePwCodeAgentSwitcher({ agents, mainState, viewing, open, earlierOpen }) {
135
+ const t = usePwCodeTranslations("agents");
136
+ const format = useFormatter();
137
+ const line = usePwCodeAgentLine();
138
+ const anyRunning = agents.some((a) => a.status === "running");
139
+ const now = useClock((ms) => Math.floor(ms / 1e3), open && anyRunning);
140
+ return useMemo(() => {
141
+ const current = agents.filter((a) => a.current);
142
+ const earlier = agents.filter((a) => !a.current);
143
+ const running = agents.filter((a) => a.status === "running");
144
+ const row = (agent) => {
145
+ const elapsed = elapsedMs(agent, now);
146
+ return {
147
+ ...line(agent),
148
+ elapsed: elapsed === null ? null : turnDuration(t, elapsed),
149
+ tokens: agent.tokens > 0 ? t("switcher.tokens", { tokens: format.number(agent.tokens, {
150
+ notation: "compact",
151
+ maximumFractionDigits: 1
152
+ }) }) : null,
153
+ viewing: agent.id === viewing,
154
+ folded: !agent.current && !earlierOpen && agent.id !== viewing
155
+ };
156
+ };
157
+ return {
158
+ main: {
159
+ state: mainState,
160
+ stateWord: stateWord(mainState, t),
161
+ stateTone: stateTone(mainState),
162
+ flagged: flagged(mainState),
163
+ viewing: viewing === null
164
+ },
165
+ agents: [...current, ...earlier].map(row),
166
+ earlier: earlier.length > 0 ? {
167
+ count: earlier.length,
168
+ label: earlierOpen ? t("switcher.hideEarlier", { count: earlier.length }) : t("switcher.showEarlier", { count: earlier.length })
169
+ } : null,
170
+ summary: current.length === 0 && earlier.length > 0 ? t("switcher.earlierOnly", { count: earlier.length }) : turnSummary(current, t),
171
+ working: running.some((a) => !a.awaitingApproval),
172
+ approvals: switcherCount(agents.filter((a) => a.awaitingApproval), (count) => t("switcher.approvals", { count })),
173
+ failed: switcherCount(current.filter((a) => a.status === "failed"), (count) => t("switcher.failedCount", { count })),
174
+ running: running.length
175
+ };
176
+ }, [
177
+ agents,
178
+ mainState,
179
+ viewing,
180
+ earlierOpen,
181
+ now,
182
+ t,
183
+ format,
184
+ line
185
+ ]);
186
+ }
187
+ export { agentMark, switcherAgent, useAgentTypeLabel, useDismissSubagent, usePwCodeAgentLine, usePwCodeAgentSwitcher };
package/dist/ago.d.ts CHANGED
@@ -1,6 +1,4 @@
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. */
1
+ /** "5m" since a time, counting days where a compact RelativeTime shows a date. */
4
2
  export declare function useCompactAgo(): {
5
3
  now: number;
6
4
  compact: (iso: string | undefined) => string;
package/dist/ago.js CHANGED
@@ -1,21 +1,19 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
1
2
  import { useCallback, useMemo } from "react";
2
3
  import { DateTime } from "luxon";
3
- import { useClock, useStrings } from "@parallelworks/ui/headless";
4
+ import { useClock } from "@parallelworks/ui/headless";
4
5
  // 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. */
6
+ /** "5m" since a time, counting days where a compact RelativeTime shows a date. */
8
7
  function useCompactAgo() {
9
- const t = useStrings().time;
8
+ const t = usePwCodeTranslations("agents");
10
9
  const tick = useClock((current) => Math.floor(current / 3e4));
11
10
  const now = useMemo(() => DateTime.now().toMillis(), [tick]);
12
11
  const compactMinutes = useCallback((minutes) => {
13
- if (!Number.isFinite(minutes) || minutes < 1) return t.now;
14
- if (minutes < 60) return t.minutes(minutes);
12
+ if (!Number.isFinite(minutes) || minutes < 1) return t("ago.now");
13
+ if (minutes < 60) return t("ago.minutes", { n: minutes });
15
14
  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));
15
+ if (hours < 24) return t("ago.hours", { n: hours });
16
+ return t("ago.days", { n: Math.floor(hours / 24) });
19
17
  }, [t]);
20
18
  return {
21
19
  now,
@@ -0,0 +1,41 @@
1
+ import type { Schemas } from './apiClient.js';
2
+ import type { PwCodeApi } from './createPwCodeApi.js';
3
+ type Allocation = Schemas['Allocation'];
4
+ /** Allocations that may fund `allows`; an empty allowed list means
5
+ * unrestricted. Non-chargeable allocations fund nothing directly. */
6
+ export declare function allocationsForType<A extends Pick<Allocation, 'nonChargeable' | 'allowed'>>(allocations: readonly A[], allows?: string): A[];
7
+ /** The allocations AI usage can bill: the gateway refuses a folder or one
8
+ * restricted to other resource types. */
9
+ export declare function aiAllocations<A extends Pick<Allocation, 'nonChargeable' | 'allowed'>>(allocations: readonly A[]): A[];
10
+ /** An organization model, which the platform bills to an allocation; the
11
+ * gateway refuses one without it. */
12
+ export declare function billsAllocation(model: string | null | undefined): boolean;
13
+ /** Why new usage cannot bill an allocation. */
14
+ export type PwCodeAllocationProblem = 'notRatedInUsd' | 'noBudget' | 'noActivePeriod' | 'budgetSpent' | 'noAccess' | 'budgetExceeded';
15
+ /** Why new usage cannot bill `a`, or null when it can. Where `requireUsd`,
16
+ * one not rated in USD cannot. */
17
+ export declare function allocationProblem(a: Pick<Allocation, 'usable' | 'ratedInUsd' | 'unusableReason'>, requireUsd: boolean): PwCodeAllocationProblem | null;
18
+ /** What `a` has spent of its budget, `used / total unit`, each amount as
19
+ * `amount` writes it. */
20
+ export declare function allocationUsage(a: Pick<Allocation, 'used' | 'estimatedUsed' | 'total' | 'unit'>, amount: (value: number) => string): string;
21
+ /** An allocation as a picker offers it. */
22
+ export interface PwCodeAllocationChoice {
23
+ value: string;
24
+ label: string;
25
+ /** Its spend, after why it cannot be billed when it cannot. */
26
+ description: string;
27
+ disabled: boolean;
28
+ }
29
+ /** `a` as a picker offers it: one usage cannot bill stays listed, disabled,
30
+ * saying why. */
31
+ export declare function allocationChoice(a: Pick<Allocation, 'name' | 'usable' | 'ratedInUsd' | 'unusableReason' | 'used' | 'estimatedUsed' | 'total' | 'unit'>, { requireUsd, describe, amount, }: {
32
+ requireUsd: boolean;
33
+ /** Says why in the reader's language. */
34
+ describe: (problem: PwCodeAllocationProblem) => string;
35
+ amount: (value: number) => string;
36
+ }): PwCodeAllocationChoice;
37
+ /** The allocations the model may bill, as a picker offers them in the
38
+ * reader's language: none for a model that bills none, and undefined while
39
+ * they load. Which one is chosen first is the host's. */
40
+ export declare function useModelAllocations(api: Pick<PwCodeApi, 'useAllocations'>, model: string | null | undefined): PwCodeAllocationChoice[] | undefined;
41
+ export {};
@@ -0,0 +1,76 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { useMemo } from "react";
3
+ import { isOrgModel } from "@parallelworks/ui/ai/headless";
4
+ import { useFormatter } from "use-intl";
5
+ // src/allocations.ts
6
+ /** Allocations that may fund `allows`; an empty allowed list means
7
+ * unrestricted. Non-chargeable allocations fund nothing directly. */
8
+ function allocationsForType(allocations, allows) {
9
+ return allocations.filter((a) => !a.nonChargeable && (!allows || !a.allowed?.length || a.allowed.includes(allows)));
10
+ }
11
+ /** The allocations AI usage can bill: the gateway refuses a folder or one
12
+ * restricted to other resource types. */
13
+ function aiAllocations(allocations) {
14
+ return allocationsForType(allocations, "ai");
15
+ }
16
+ /** An organization model, which the platform bills to an allocation; the
17
+ * gateway refuses one without it. */
18
+ function billsAllocation(model) {
19
+ return isOrgModel(model);
20
+ }
21
+ /** Why new usage cannot bill `a`, or null when it can. Where `requireUsd`,
22
+ * one not rated in USD cannot. */
23
+ function allocationProblem(a, requireUsd) {
24
+ if (requireUsd && a.ratedInUsd === false) return "notRatedInUsd";
25
+ if (a.usable !== false) return null;
26
+ switch (a.unusableReason) {
27
+ case "no-budget": return "noBudget";
28
+ case "no-active-period": return "noActivePeriod";
29
+ case "budget-spent": return "budgetSpent";
30
+ case "no-access": return "noAccess";
31
+ default: return "budgetExceeded";
32
+ }
33
+ }
34
+ /** What `a` has spent of its budget, `used / total unit`, each amount as
35
+ * `amount` writes it. */
36
+ function allocationUsage(a, amount) {
37
+ return `${amount(Math.max(a.used ?? 0, a.estimatedUsed ?? 0))} / ${amount(a.total)} ${a.unit || "USD"}`;
38
+ }
39
+ /** `a` as a picker offers it: one usage cannot bill stays listed, disabled,
40
+ * saying why. */
41
+ function allocationChoice(a, { requireUsd, describe, amount }) {
42
+ const problem = allocationProblem(a, requireUsd);
43
+ const usage = allocationUsage(a, amount);
44
+ return {
45
+ value: a.name,
46
+ label: a.name,
47
+ description: problem ? `${describe(problem)} · ${usage}` : usage,
48
+ disabled: problem !== null
49
+ };
50
+ }
51
+ /** The allocations the model may bill, as a picker offers them in the
52
+ * reader's language: none for a model that bills none, and undefined while
53
+ * they load. Which one is chosen first is the host's. */
54
+ function useModelAllocations(api, model) {
55
+ const bills = billsAllocation(model);
56
+ const { data } = api.useAllocations(bills);
57
+ const t = usePwCodeTranslations("agents");
58
+ const format = useFormatter();
59
+ return useMemo(() => {
60
+ if (!bills) return [];
61
+ if (!data) return;
62
+ const describe = (problem) => t(`allocation.${problem}`);
63
+ const amount = (value) => format.number(value, { maximumFractionDigits: 2 });
64
+ return aiAllocations(data).map((a) => allocationChoice(a, {
65
+ requireUsd: false,
66
+ describe,
67
+ amount
68
+ }));
69
+ }, [
70
+ bills,
71
+ data,
72
+ t,
73
+ format
74
+ ]);
75
+ }
76
+ export { aiAllocations, allocationChoice, allocationProblem, allocationUsage, allocationsForType, billsAllocation, useModelAllocations };