@parallelworks/code 0.1.0 → 0.2.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 (70) hide show
  1. package/README.md +138 -24
  2. package/dist/api.d.ts +3469 -0
  3. package/dist/apiClient.d.ts +26 -0
  4. package/dist/apiClient.js +5 -0
  5. package/dist/claudeApi.d.ts +27 -0
  6. package/dist/claudeApi.js +250 -0
  7. package/dist/command.d.ts +47 -0
  8. package/dist/command.js +64 -0
  9. package/dist/commandsApi.d.ts +64 -0
  10. package/dist/commandsApi.js +267 -0
  11. package/dist/createPwCodeApi.d.ts +688 -0
  12. package/dist/createPwCodeApi.js +31 -0
  13. package/dist/index.d.ts +16 -3
  14. package/dist/index.js +16 -3
  15. package/dist/locales/en/agentTranscript.js +170 -0
  16. package/dist/locales/en/agents.js +380 -0
  17. package/dist/locales/en.d.ts +531 -0
  18. package/dist/locales/en.js +8 -0
  19. package/dist/locales/es/agentTranscript.js +170 -0
  20. package/dist/locales/es/agents.js +380 -0
  21. package/dist/locales/es.d.ts +3 -0
  22. package/dist/locales/es.js +8 -0
  23. package/dist/locales/ja/agentTranscript.js +170 -0
  24. package/dist/locales/ja/agents.js +380 -0
  25. package/dist/locales/ja.d.ts +3 -0
  26. package/dist/locales/ja.js +8 -0
  27. package/dist/locales/ko/agentTranscript.js +170 -0
  28. package/dist/locales/ko/agents.js +380 -0
  29. package/dist/locales/ko.d.ts +3 -0
  30. package/dist/locales/ko.js +8 -0
  31. package/dist/locales/zh/agentTranscript.js +170 -0
  32. package/dist/locales/zh/agents.js +380 -0
  33. package/dist/locales/zh.d.ts +3 -0
  34. package/dist/locales/zh.js +8 -0
  35. package/dist/machine.d.ts +49 -0
  36. package/dist/machine.js +60 -0
  37. package/dist/messages.d.ts +17 -0
  38. package/dist/messages.js +31 -0
  39. package/dist/notices.d.ts +11 -0
  40. package/dist/notices.js +94 -0
  41. package/dist/pullRequest.d.ts +8 -0
  42. package/dist/pullRequest.js +29 -0
  43. package/dist/query.d.ts +28 -0
  44. package/dist/query.js +25 -0
  45. package/dist/session.d.ts +70 -1
  46. package/dist/session.js +101 -1
  47. package/dist/sessionEvents.d.ts +27 -0
  48. package/dist/sessionEvents.js +212 -0
  49. package/dist/sessionsApi.d.ts +105 -0
  50. package/dist/sessionsApi.js +513 -0
  51. package/dist/toolStrings.d.ts +4 -0
  52. package/dist/toolStrings.js +95 -0
  53. package/dist/transcript.d.ts +12 -1
  54. package/dist/transcript.js +40 -2
  55. package/dist/types.d.ts +20 -1
  56. package/dist/useTranscript.d.ts +4 -1
  57. package/dist/useTranscript.js +54 -11
  58. package/dist/wording.d.ts +43 -0
  59. package/dist/wording.js +101 -0
  60. package/locales/en/agentTranscript.json +162 -0
  61. package/locales/en/agents.json +366 -0
  62. package/locales/es/agentTranscript.json +162 -0
  63. package/locales/es/agents.json +366 -0
  64. package/locales/ja/agentTranscript.json +162 -0
  65. package/locales/ja/agents.json +366 -0
  66. package/locales/ko/agentTranscript.json +162 -0
  67. package/locales/ko/agents.json +366 -0
  68. package/locales/zh/agentTranscript.json +162 -0
  69. package/locales/zh/agents.json +366 -0
  70. package/package.json +23 -8
@@ -0,0 +1,212 @@
1
+ import { isConnected } from "./machine.js";
2
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
3
+ // src/sessionEvents.ts
4
+ var INITIAL_RETRY_MS = 1e3;
5
+ var MAX_RETRY_MS = 3e4;
6
+ var SOCKET_OPEN = 1;
7
+ var SOCKET_CLOSED = 3;
8
+ /** The path a session's event feed is served at, resuming after frame `after`. */
9
+ function sessionEventsPath(machine, id, after) {
10
+ return `/ws/code/machines/${encodeURIComponent(machine)}/sessions/${encodeURIComponent(id)}/events?after=${after}`;
11
+ }
12
+ /** Frames after which the list of subagents may read differently: one started
13
+ * or ended, one asked for or got an approval, or a turn began or closed. */
14
+ function changesSubagents(ev) {
15
+ return ev.type === "subagent_start" || ev.type === "subagent_end" || ev.type === "approval_request" || ev.type === "approval_resolved" || ev.type === "user_message" || ev.type === "done" || ev.type === "error";
16
+ }
17
+ /** `machines` with each one in `fed` that the listing lost counted as connected. */
18
+ function reachedByFeed(machines, fed) {
19
+ const lost = (m) => fed.has(m.id) && !isConnected(m);
20
+ if (!machines.some(lost)) return machines;
21
+ return machines.map((m) => {
22
+ if (!lost(m)) return m;
23
+ const { error: _, ...reached } = m;
24
+ return {
25
+ ...reached,
26
+ status: "connected"
27
+ };
28
+ });
29
+ }
30
+ /** Holds one socket open while `enabled`, reopening it with backoff after it
31
+ * drops, and from scratch whenever `connectionKey` changes. */
32
+ function useReconnectingSocket({ open, path, connectionKey, enabled, onOpen, onMessage, onClose }) {
33
+ const [connected, setConnected] = useState(false);
34
+ const latest = useRef({
35
+ open,
36
+ path,
37
+ onOpen,
38
+ onMessage,
39
+ onClose
40
+ });
41
+ latest.current = {
42
+ open,
43
+ path,
44
+ onOpen,
45
+ onMessage,
46
+ onClose
47
+ };
48
+ useEffect(() => {
49
+ if (!enabled || !latest.current.open) return;
50
+ let stopped = false;
51
+ let socket = null;
52
+ let attempts = 0;
53
+ let timer;
54
+ const retry = () => {
55
+ const delay = Math.min(INITIAL_RETRY_MS * 2 ** attempts, MAX_RETRY_MS);
56
+ attempts += 1;
57
+ timer = setTimeout(connect, delay);
58
+ };
59
+ const failed = () => {
60
+ if (stopped) return;
61
+ latest.current.onClose();
62
+ retry();
63
+ };
64
+ const attach = (ws) => {
65
+ if (stopped) {
66
+ ws.close();
67
+ return;
68
+ }
69
+ socket = ws;
70
+ const opened = () => {
71
+ if (socket !== ws) return;
72
+ attempts = 0;
73
+ setConnected(true);
74
+ latest.current.onOpen();
75
+ };
76
+ const closed = () => {
77
+ if (socket !== ws) return;
78
+ socket = null;
79
+ setConnected(false);
80
+ latest.current.onClose();
81
+ if (!stopped) retry();
82
+ };
83
+ ws.addEventListener("open", opened);
84
+ ws.addEventListener("message", (event) => {
85
+ if (socket === ws) latest.current.onMessage(event.data);
86
+ });
87
+ ws.addEventListener("close", closed);
88
+ if (ws.readyState === SOCKET_OPEN) opened();
89
+ else if (ws.readyState === SOCKET_CLOSED) closed();
90
+ };
91
+ function connect() {
92
+ timer = void 0;
93
+ const opener = latest.current.open;
94
+ if (!opener) return;
95
+ let made;
96
+ try {
97
+ made = opener(latest.current.path());
98
+ } catch {
99
+ failed();
100
+ return;
101
+ }
102
+ if ("then" in made) made.then(attach, failed);
103
+ else attach(made);
104
+ }
105
+ connect();
106
+ return () => {
107
+ stopped = true;
108
+ clearTimeout(timer);
109
+ const ws = socket;
110
+ socket = null;
111
+ ws?.close();
112
+ setConnected(false);
113
+ };
114
+ }, [enabled, connectionKey]);
115
+ return connected;
116
+ }
117
+ function sessionEvents({ openSocket, hidden }) {
118
+ const openFeeds = /* @__PURE__ */ new Map();
119
+ const listeners = /* @__PURE__ */ new Set();
120
+ let fedMachines = /* @__PURE__ */ new Set();
121
+ function countFeed(machine, by) {
122
+ const open = (openFeeds.get(machine) ?? 0) + by;
123
+ const fed = open > 0;
124
+ if (fed) openFeeds.set(machine, open);
125
+ else openFeeds.delete(machine);
126
+ if (fed !== fedMachines.has(machine)) {
127
+ fedMachines = new Set(openFeeds.keys());
128
+ for (const notify of listeners) notify();
129
+ }
130
+ }
131
+ function subscribe(notify) {
132
+ listeners.add(notify);
133
+ return () => {
134
+ listeners.delete(notify);
135
+ };
136
+ }
137
+ /** The machines a session feed is open to. */
138
+ function useFedMachines() {
139
+ return useSyncExternalStore(subscribe, () => fedMachines);
140
+ }
141
+ /** The transcript owns the cursor; this only reconnects from it. Frames are
142
+ * applied once per animation frame: the backlog a reconnect catches up on
143
+ * arrives in a burst, and rendering each frame of it plays the turn back. */
144
+ function useSessionEvents(machine, id, cursor, onEvent) {
145
+ const key = `${machine}/${id}`;
146
+ const [feed, setFeed] = useState(null);
147
+ const pending = useRef([]);
148
+ const frame = useRef(null);
149
+ const onEventRef = useRef(onEvent);
150
+ onEventRef.current = onEvent;
151
+ const flush = useCallback(() => {
152
+ if (frame.current !== null) {
153
+ cancelAnimationFrame(frame.current);
154
+ frame.current = null;
155
+ }
156
+ const frames = pending.current;
157
+ pending.current = [];
158
+ for (const ev of frames) onEventRef.current(ev);
159
+ }, []);
160
+ useEffect(() => () => {
161
+ if (frame.current !== null) {
162
+ cancelAnimationFrame(frame.current);
163
+ frame.current = null;
164
+ }
165
+ pending.current = [];
166
+ }, [key]);
167
+ const connected = useReconnectingSocket({
168
+ open: openSocket,
169
+ path: () => sessionEventsPath(machine, id, cursor?.() ?? 0),
170
+ connectionKey: key,
171
+ enabled: cursor !== void 0,
172
+ onOpen: () => setFeed({
173
+ key,
174
+ open: true
175
+ }),
176
+ onClose: () => {
177
+ flush();
178
+ setFeed({
179
+ key,
180
+ open: false
181
+ });
182
+ },
183
+ onMessage: (data) => {
184
+ let parsed;
185
+ try {
186
+ parsed = JSON.parse(String(data));
187
+ } catch {
188
+ return;
189
+ }
190
+ pending.current.push(parsed);
191
+ if (hidden?.()) flush();
192
+ else if (frame.current === null) frame.current = requestAnimationFrame(flush);
193
+ }
194
+ });
195
+ const open = feed?.key === key ? feed.open : void 0;
196
+ const reading = connected && open === true;
197
+ useEffect(() => {
198
+ if (!reading) return;
199
+ countFeed(machine, 1);
200
+ return () => countFeed(machine, -1);
201
+ }, [reading, machine]);
202
+ return {
203
+ connected: reading,
204
+ disconnected: open === false
205
+ };
206
+ }
207
+ return {
208
+ useSessionEvents,
209
+ useFedMachines
210
+ };
211
+ }
212
+ export { changesSubagents, reachedByFeed, sessionEvents, sessionEventsPath };
@@ -0,0 +1,105 @@
1
+ import type { ApprovalAnswerValue, MessagePaste } from '@parallelworks/ui/ai/headless';
2
+ import { DateTime } from 'luxon';
3
+ import type { KeyedMutator } from 'swr';
4
+ import { type PwCodeApiError, type PwCodeClient, type PwCodeQuery, type PwCodeResult, type Schemas } from './apiClient.js';
5
+ type Session = Schemas['AgentSession'];
6
+ type SessionDetail = Schemas['AgentSessionDetail'];
7
+ type SessionsResponse = Schemas['AgentSessionsResponse'];
8
+ type PullRequest = Schemas['AgentPullRequest'];
9
+ export declare const SESSIONS_REFRESH_MS = 5000;
10
+ /** Whether a copy cached by an earlier visit still holds everything the
11
+ * session's listed row reports. A running session's copy trails its turn. */
12
+ export declare function cachedCopyCurrent(listed: Session | undefined, cached: SessionDetail): boolean;
13
+ /** Each session listed from `machine` that links a pull request in `read` takes its state, as the machine stores it for every one of them. */
14
+ export declare function patchPullRequestStates(current: SessionsResponse | undefined, machine: string, read: PullRequest[]): SessionsResponse | undefined;
15
+ type PullRequestStates = {
16
+ pullRequests?: PullRequest[] | null;
17
+ };
18
+ /** Every minute while any of `urls` may still change or has no state yet, hourly once all are merged or closed, and never once all are merged. */
19
+ export declare function pullRequestsRefreshMs(data: PullRequestStates | undefined, urls: string[]): number;
20
+ /** When this client last read the session from its machine: its fetch, or the
21
+ * moment its open feed closed, since an open feed is still reading. */
22
+ export declare function useLastReadAt(detail: SessionDetail | undefined, feedOpen: boolean): DateTime | null;
23
+ export declare function patchSessionNames(current: SessionsResponse | undefined, machine: string, id: string, names: Pick<Session, 'name' | 'autoName'>): SessionsResponse | undefined;
24
+ /** The part of a paste a message names it by. */
25
+ export declare function pasteRefs(pastes: MessagePaste[] | undefined): {
26
+ pastes: {
27
+ placeholder: string;
28
+ id: number;
29
+ }[];
30
+ } | {
31
+ pastes?: never;
32
+ };
33
+ export type PwCodePasteUpload = {
34
+ paste: Schemas['AgentPasteSaved'];
35
+ } | {
36
+ error: string;
37
+ } | {
38
+ unsupported: true;
39
+ };
40
+ export declare function sessionsApi(client: PwCodeClient): {
41
+ useSessions: () => PwCodeQuery<SessionsResponse>;
42
+ useWaitingSessionCount: (enabled: boolean) => number;
43
+ useSessionDetail: (machine: string, id: string, listed: Session | undefined) => {
44
+ data: SessionDetail | undefined;
45
+ error: PwCodeApiError | undefined;
46
+ isLoading: boolean;
47
+ mutate: KeyedMutator<SessionDetail>;
48
+ fresh: boolean;
49
+ };
50
+ usePullRequests: (machine: string, id: string, urls: string[], onRead?: (read: PullRequest[]) => void) => PwCodeQuery<Schemas['AgentPullRequests']>;
51
+ useSessionPullRequestStates: (machine: string, id: string, urls: string[]) => {
52
+ url: string;
53
+ state: string | undefined;
54
+ }[] | undefined;
55
+ useMachine: (machine: string) => {
56
+ machine: Schemas['AgentMachine'] | undefined;
57
+ recheck: () => void;
58
+ };
59
+ useSubagents: (machine: string, id: string, enabled: boolean) => {
60
+ subagents: Schemas['Subagent'][];
61
+ refresh: () => void;
62
+ };
63
+ useSubagentDetail: (machine: string, id: string, subId: string) => {
64
+ data: Schemas['SubagentDetail'] | undefined;
65
+ error: unknown;
66
+ refresh: () => void;
67
+ };
68
+ stopSubagent: (machine: string, id: string, subId: string) => Promise<unknown>;
69
+ stopAllSubagents: (machine: string, id: string) => Promise<unknown>;
70
+ useSessionWorktree: (s: Session | undefined) => PwCodeQuery<Schemas['AgentSessionWorktree']>;
71
+ leaveWorktree: (s: Session, removeRoot?: string) => Promise<{
72
+ left?: Schemas['AgentWorktreeLeft'];
73
+ refusal?: unknown;
74
+ }>;
75
+ useSessionMutations: () => {
76
+ /** Given the root of the worktree the session works in, removes that worktree too. */
77
+ deleteSession: (s: Session, removeWorktree?: string) => Promise<unknown>;
78
+ renameSession: (s: Session, name: string) => Promise<unknown>;
79
+ archiveSession: (s: Session) => Promise<unknown>;
80
+ archiveAfterTurn: (s: Session) => Promise<{
81
+ refusal: unknown;
82
+ deferred: boolean;
83
+ }>;
84
+ restoreSession: (s: Session) => Promise<unknown>;
85
+ pinSession: (s: Session, pinned: boolean) => Promise<unknown>;
86
+ /** `group` is the id of one of the reader's groups, or null for none. */
87
+ groupSession: (s: Session, group: string | null) => Promise<unknown>;
88
+ stopSession: (s: Session) => Promise<unknown>;
89
+ forkSession: (s: Session) => Promise<{
90
+ forked?: Schemas['AgentSessionForked'];
91
+ refusal?: unknown;
92
+ }>;
93
+ };
94
+ createSession: (machine: string, body: Schemas['CreateSessionBody']) => Promise<PwCodeResult<SessionDetail>>;
95
+ sendMessage: (machine: string, id: string, body: Schemas['SendMessageBody']) => Promise<PwCodeResult<Schemas['AgentMessageAccepted']>>;
96
+ steer: (machine: string, id: string, body: Schemas['AgentDirectionBody']) => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>;
97
+ withdrawQueued: (machine: string, id: string, turnId: string) => Promise<PwCodeResult<undefined>>;
98
+ messageSubagent: (machine: string, id: string, subId: string, body: Schemas['SendMessageBody']) => Promise<PwCodeResult<Schemas['AgentMessageAccepted']>>;
99
+ steerSubagent: (machine: string, id: string, subId: string, body: Schemas['AgentDirectionBody']) => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>;
100
+ saveImage: (machine: string, id: string, body: Schemas['AgentImageBody']) => Promise<PwCodeResult<Schemas['AgentImageSaved']>>;
101
+ answerApproval: (machine: string, sessionId: string, approvalId: string, answer: ApprovalAnswerValue) => Promise<unknown>;
102
+ removeSessionDirectory: (machine: string, sessionId: string, path: string) => Promise<unknown>;
103
+ uploadPaste: (machine: string, sessionId: string, text: string, describe: (error: unknown) => string) => Promise<PwCodePasteUpload>;
104
+ };
105
+ export {};