@parallelworks/code 0.0.0-stage → 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 (73) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +205 -2
  3. package/dist/api.d.ts +3469 -0
  4. package/dist/apiClient.d.ts +26 -0
  5. package/dist/apiClient.js +5 -0
  6. package/dist/claudeApi.d.ts +27 -0
  7. package/dist/claudeApi.js +250 -0
  8. package/dist/command.d.ts +47 -0
  9. package/dist/command.js +64 -0
  10. package/dist/commandsApi.d.ts +64 -0
  11. package/dist/commandsApi.js +267 -0
  12. package/dist/createPwCodeApi.d.ts +688 -0
  13. package/dist/createPwCodeApi.js +31 -0
  14. package/dist/images.d.ts +7 -0
  15. package/dist/images.js +22 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +18 -0
  18. package/dist/locales/en/agentTranscript.js +170 -0
  19. package/dist/locales/en/agents.js +380 -0
  20. package/dist/locales/en.d.ts +531 -0
  21. package/dist/locales/en.js +8 -0
  22. package/dist/locales/es/agentTranscript.js +170 -0
  23. package/dist/locales/es/agents.js +380 -0
  24. package/dist/locales/es.d.ts +3 -0
  25. package/dist/locales/es.js +8 -0
  26. package/dist/locales/ja/agentTranscript.js +170 -0
  27. package/dist/locales/ja/agents.js +380 -0
  28. package/dist/locales/ja.d.ts +3 -0
  29. package/dist/locales/ja.js +8 -0
  30. package/dist/locales/ko/agentTranscript.js +170 -0
  31. package/dist/locales/ko/agents.js +380 -0
  32. package/dist/locales/ko.d.ts +3 -0
  33. package/dist/locales/ko.js +8 -0
  34. package/dist/locales/zh/agentTranscript.js +170 -0
  35. package/dist/locales/zh/agents.js +380 -0
  36. package/dist/locales/zh.d.ts +3 -0
  37. package/dist/locales/zh.js +8 -0
  38. package/dist/machine.d.ts +49 -0
  39. package/dist/machine.js +60 -0
  40. package/dist/messages.d.ts +17 -0
  41. package/dist/messages.js +31 -0
  42. package/dist/notices.d.ts +11 -0
  43. package/dist/notices.js +94 -0
  44. package/dist/pullRequest.d.ts +8 -0
  45. package/dist/pullRequest.js +29 -0
  46. package/dist/query.d.ts +28 -0
  47. package/dist/query.js +25 -0
  48. package/dist/session.d.ts +72 -0
  49. package/dist/session.js +111 -0
  50. package/dist/sessionEvents.d.ts +27 -0
  51. package/dist/sessionEvents.js +212 -0
  52. package/dist/sessionsApi.d.ts +105 -0
  53. package/dist/sessionsApi.js +513 -0
  54. package/dist/toolStrings.d.ts +4 -0
  55. package/dist/toolStrings.js +95 -0
  56. package/dist/transcript.d.ts +151 -0
  57. package/dist/transcript.js +1315 -0
  58. package/dist/types.d.ts +234 -0
  59. package/dist/useTranscript.d.ts +63 -0
  60. package/dist/useTranscript.js +243 -0
  61. package/dist/wording.d.ts +43 -0
  62. package/dist/wording.js +101 -0
  63. package/locales/en/agentTranscript.json +162 -0
  64. package/locales/en/agents.json +366 -0
  65. package/locales/es/agentTranscript.json +162 -0
  66. package/locales/es/agents.json +366 -0
  67. package/locales/ja/agentTranscript.json +162 -0
  68. package/locales/ja/agents.json +366 -0
  69. package/locales/ko/agentTranscript.json +162 -0
  70. package/locales/ko/agents.json +366 -0
  71. package/locales/zh/agentTranscript.json +162 -0
  72. package/locales/zh/agents.json +366 -0
  73. package/package.json +68 -3
@@ -0,0 +1,234 @@
1
+ export type PwCodeSessionStatus = 'idle' | 'running' | 'awaiting_approval' | 'live_elsewhere';
2
+ export type PwCodeHistoryKind = 'user' | 'assistant' | 'thinking' | 'tool_call' | 'tool_result' | 'notice' | 'warning' | 'error' | 'plan_view' | 'goal_view' | 'goal_progress' | 'turn_end' | 'recap' | 'compaction';
3
+ export interface PwCodePasteView {
4
+ placeholder: string;
5
+ id: number;
6
+ lines: number;
7
+ bytes: number;
8
+ inline?: boolean;
9
+ text?: string;
10
+ }
11
+ /** How a call that needed an answer was settled, as pw code records it. */
12
+ export interface PwCodeToolDecision {
13
+ callId: string;
14
+ by: 'user' | 'auto-reviewer';
15
+ username?: string;
16
+ status: 'reviewing' | 'approved' | 'denied' | 'timed_out' | 'failed' | 'aborted';
17
+ note?: string;
18
+ rationale?: string;
19
+ /** What was decided on, such as the command, in the decider's words. */
20
+ action?: string;
21
+ at: string;
22
+ answers?: PwCodeAskAnswer[] | null;
23
+ }
24
+ /** One question's answer: the options picked, the user's own words, and their notes on a question with previews. */
25
+ export interface PwCodeAskAnswer {
26
+ question?: string;
27
+ picked?: string[] | null;
28
+ text?: string;
29
+ notes?: string;
30
+ }
31
+ export interface PwCodeHistoryItem {
32
+ kind: PwCodeHistoryKind;
33
+ text?: string;
34
+ turnId?: string;
35
+ toolName?: string;
36
+ toolArgs?: string;
37
+ callId?: string;
38
+ decision?: PwCodeToolDecision;
39
+ planBody?: string;
40
+ fromMain?: boolean;
41
+ pastes?: PwCodePasteView[] | null;
42
+ images?: PwCodeImage[] | null;
43
+ turnEnd?: PwCodeTurnEnd;
44
+ /** On an EditFile call: the line its hunk begins on, as a live tool_start carries it. */
45
+ startLine?: number;
46
+ }
47
+ /** A preview of an image a message carried, base64-encoded; ref names the
48
+ * full-size image when the daemon can serve it, and originalMime and
49
+ * originalSize describe that image. */
50
+ export interface PwCodeImage {
51
+ mime: string;
52
+ data: string;
53
+ ref?: string;
54
+ originalMime?: string;
55
+ originalSize?: number;
56
+ }
57
+ /** An image the session saved, sent with the message that names its placeholder. */
58
+ export interface PwCodeImageRef {
59
+ placeholder: string;
60
+ path: string;
61
+ mime: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp';
62
+ }
63
+ export interface PwCodeAskOption {
64
+ label: string;
65
+ description?: string;
66
+ preview?: string;
67
+ }
68
+ export interface PwCodeAskQuestion {
69
+ question: string;
70
+ header?: string;
71
+ multiSelect?: boolean;
72
+ options?: PwCodeAskOption[] | null;
73
+ }
74
+ export interface PwCodeApprovalRequest {
75
+ id: string;
76
+ kind: 'confirm' | 'ask' | 'plan';
77
+ createdAt: string;
78
+ agent?: string;
79
+ callId?: string;
80
+ tool?: string;
81
+ command?: string;
82
+ mode?: string;
83
+ plan?: string;
84
+ planPath?: string;
85
+ questions?: PwCodeAskQuestion[] | null;
86
+ reason?: string;
87
+ subagentId?: string;
88
+ /** The directory "Yes, and allow this directory for the session" would open. */
89
+ allowDir?: PwCodeAllowedDirectory;
90
+ }
91
+ /** A directory open to the file tools besides the working directory; its
92
+ * scopes name the settings files listing it, none meaning this session only. */
93
+ export interface PwCodeAddedDirectory {
94
+ path: string;
95
+ scopes?: string[] | null;
96
+ }
97
+ /** A directory an approval opened for the session: only that directory
98
+ * without `subtree`, and for reading only without `edit`. */
99
+ export interface PwCodeAllowedDirectory {
100
+ path: string;
101
+ subtree?: boolean;
102
+ edit?: boolean;
103
+ }
104
+ /** The settings a session reports on its state frames, as far as a
105
+ * transcript's host reads them back. */
106
+ export interface PwCodeSessionState {
107
+ name?: string;
108
+ autoName?: string;
109
+ claudeAccount?: string;
110
+ model: string;
111
+ /** The names to show in place of model IDs; an ID it leaves out has none. */
112
+ modelNames?: Record<string, string>;
113
+ /** A level on pw code's scale; empty from a daemon that predates it. */
114
+ effort?: string;
115
+ allocation?: string;
116
+ permissionMode?: string;
117
+ inputTokens?: number;
118
+ outputTokens?: number;
119
+ /** Pastes up to this size reach the model inline; unset from a daemon that
120
+ * cannot store pastes. */
121
+ pasteInlineMaxBytes?: number;
122
+ goal?: PwCodeGoalStatus;
123
+ /** The directories open to the file tools besides the working directory. */
124
+ addDirs?: PwCodeAddedDirectory[] | null;
125
+ /** The directories approvals opened for the session. */
126
+ allowedDirs?: PwCodeAllowedDirectory[] | null;
127
+ /** The session's directory in the git worktree it moved into; unset while it works where it launched. */
128
+ worktree?: string;
129
+ /** Each subagent's own tokens, by its id; one that has used none is left out. */
130
+ subagentUsage?: Record<string, PwCodeSubagentUsage>;
131
+ }
132
+ export interface PwCodeSubagentUsage {
133
+ inputTokens?: number;
134
+ outputTokens?: number;
135
+ /** Its latest request's input, cached tokens included. */
136
+ latestInputTokens?: number;
137
+ }
138
+ /** Where a session's /goal loop stands; unset when it has no goal. */
139
+ export interface PwCodeGoalStatus {
140
+ active?: boolean;
141
+ paused?: boolean;
142
+ /** An evaluation is in flight, which spends tokens with no turn to show. */
143
+ checking?: boolean;
144
+ }
145
+ /** One step of a /goal loop, as the daemon files and announces it. */
146
+ export interface PwCodeGoalProgress {
147
+ turns?: number;
148
+ condition?: string;
149
+ reason?: string;
150
+ outcome?: string;
151
+ err?: string;
152
+ /** Set when a usage limit stopped the check; the goal is checked again then. */
153
+ resumeAt?: string;
154
+ elapsedMs?: number;
155
+ tokens?: number;
156
+ }
157
+ /** The line a main-conversation turn ends with. */
158
+ export interface PwCodeTurnEnd {
159
+ durationMs: number;
160
+ endedAt: string;
161
+ pendingAgents?: number;
162
+ }
163
+ export interface PwCodeStreamEvent {
164
+ seq: number;
165
+ type: string;
166
+ agentType?: string;
167
+ goalProgress?: PwCodeGoalProgress;
168
+ /** On the frame that ends a main-conversation turn nobody stopped. */
169
+ turnEnd?: PwCodeTurnEnd;
170
+ approval?: PwCodeApprovalRequest;
171
+ approvalId?: string;
172
+ args?: string;
173
+ callId?: string;
174
+ decision?: PwCodeToolDecision;
175
+ background?: boolean;
176
+ color?: string;
177
+ content?: string;
178
+ id?: string;
179
+ /** On the error that ends a turn someone stopped. */
180
+ interrupted?: boolean;
181
+ /** On a notice or warning the session's history also holds. */
182
+ recorded?: boolean;
183
+ isError?: boolean;
184
+ name?: string;
185
+ newId?: string;
186
+ result?: string;
187
+ startLine?: number;
188
+ state?: PwCodeSessionState;
189
+ turnId?: string;
190
+ pastes?: PwCodePasteView[] | null;
191
+ images?: PwCodeImage[] | null;
192
+ /** On a usage_limit_wait that starts a wait: when the limit resets. */
193
+ resumeAt?: string;
194
+ /** On subagent_delivered: the line the main conversation was handed. */
195
+ notice?: string;
196
+ }
197
+ export interface PwCodeSessionDetail {
198
+ status: PwCodeSessionStatus;
199
+ history?: PwCodeHistoryItem[] | null;
200
+ approvals?: PwCodeApprovalRequest[] | null;
201
+ lastSeq?: number;
202
+ /** The turn in flight as of lastSeq, cleared with that turn's last frame. */
203
+ turnId?: string;
204
+ /** When the running turn began; only the daemon knows for a turn that was
205
+ * already running when the session was opened. */
206
+ turnStartedAt?: string;
207
+ /** The running turn is waiting for a usage limit to reset. */
208
+ waitingForUsageLimit?: boolean;
209
+ /** When that usage limit resets. */
210
+ usageLimitResumeAt?: string;
211
+ goal?: PwCodeGoalStatus;
212
+ addDirs?: PwCodeAddedDirectory[] | null;
213
+ allowedDirs?: PwCodeAllowedDirectory[] | null;
214
+ }
215
+ /** A subagent's transcript, read at lastSeq of its session's feed. */
216
+ export interface PwCodeSubagentDetail {
217
+ id: string;
218
+ status: 'running' | 'done' | 'failed' | 'stopped';
219
+ /** When its latest run began: the task it was given, or a turn someone prompted on it. */
220
+ startedAt?: string;
221
+ history?: PwCodeHistoryItem[] | null;
222
+ /** The approvals it is waiting on. */
223
+ approvals?: PwCodeApprovalRequest[] | null;
224
+ lastSeq?: number;
225
+ }
226
+ /** The body the daemon accepts as the answer to an approval. */
227
+ export interface PwCodeApprovalAnswer {
228
+ allowed?: boolean;
229
+ allowDir?: boolean;
230
+ denyMessage?: string;
231
+ /** One per question, its picks, text and notes only: the platform takes free text in just those fields. */
232
+ answers?: Pick<PwCodeAskAnswer, 'picked' | 'text' | 'notes'>[];
233
+ chat?: boolean;
234
+ }
@@ -0,0 +1,63 @@
1
+ import { type CompactionNotice, type GoalNotice, type ImageUrl, type RecapNotice, type TranscriptWords, type StreamEffect, type TranscriptState } from './transcript.js';
2
+ import type { PwCodeImage, PwCodeImageRef, PwCodeSessionDetail, PwCodeStreamEvent } from './types.js';
3
+ import type { MessagePaste } from '@parallelworks/ui/ai/headless';
4
+ export type PwCodeSendResult = {
5
+ turnId?: string | undefined;
6
+ queued?: boolean | undefined;
7
+ } | {
8
+ error: string;
9
+ };
10
+ /** lost: no answer came, so the direction may have reached the turn. */
11
+ export type PwCodeSteerResult = {
12
+ delivered: boolean;
13
+ } | {
14
+ error: string;
15
+ } | {
16
+ lost: string;
17
+ };
18
+ export type PwCodeWithdrawResult = {
19
+ error?: string;
20
+ };
21
+ interface SendOptions {
22
+ steer?: boolean;
23
+ pastes?: MessagePaste[] | undefined;
24
+ images?: PwCodeImageRef[] | undefined;
25
+ /** Drawn on the message until its echo brings the daemon's; a note can wait a whole tool call for that. */
26
+ previews?: PwCodeImage[] | undefined;
27
+ }
28
+ /** Holds the live transcript for one session. The host still owns the socket
29
+ * and the fetch: it feeds events to `onEvent` and posts through `send`. */
30
+ export declare function usePwCodeTranscript({ sessionId, subagent, detail, send, steer, withdraw, onEffect, goalNotice, compactionNotice, recapNotice, words, imageUrl, }: {
31
+ /** The session shown, so frames from the conversation it cleared are dropped. */
32
+ sessionId?: string | undefined;
33
+ /** Shows this subagent's conversation instead of the main one: the frames
34
+ * are still the session's, and `detail`, `send` and `steer` are the subagent's. */
35
+ subagent?: string | undefined;
36
+ detail: PwCodeSessionDetail | undefined;
37
+ send: (text: string, pastes?: MessagePaste[], images?: PwCodeImageRef[]) => Promise<PwCodeSendResult>;
38
+ /** Hands text to the running turn, as typing into a busy terminal does. */
39
+ steer?: (text: string, pastes?: MessagePaste[], images?: PwCodeImageRef[]) => Promise<PwCodeSteerResult>;
40
+ /** Takes back a queued message, by the turn it was accepted as. */
41
+ withdraw?: (turnId: string) => Promise<PwCodeWithdrawResult>;
42
+ onEffect: (effect: StreamEffect) => void;
43
+ goalNotice?: GoalNotice;
44
+ compactionNotice?: CompactionNotice;
45
+ recapNotice?: RecapNotice;
46
+ words?: TranscriptWords;
47
+ imageUrl?: ImageUrl;
48
+ }): {
49
+ transcript: TranscriptState | null;
50
+ sending: boolean;
51
+ onEvent: (ev: PwCodeStreamEvent) => void;
52
+ /** Resolves to the refusal, or null once accepted; `steer: false` queues it. */
53
+ sendMessage: (text: string, options?: SendOptions) => Promise<string | null>;
54
+ resolveApproval: (approvalId: string) => void;
55
+ noteShellRun: (command: string, output: string) => void;
56
+ /** Queued messages the daemon has named a turn for can be taken back. */
57
+ canRemoveQueued: (id: string) => boolean;
58
+ /** Resolves to the refusal, or null once the message is gone. */
59
+ removeQueued: (id: string) => Promise<string | null>;
60
+ /** Where a reconnect resumes from: the last seq applied, read outside render. */
61
+ cursor: () => number;
62
+ };
63
+ export {};
@@ -0,0 +1,243 @@
1
+ import { appendOwnMessage, appendShellRun, appendSteeredMessage, appendTurnMessage, applyStreamEvent, dropMessage, initialTranscript, markQueued, pendingMessages, resolveApprovalEverywhere, subagentFrame, turnRunning } from "./transcript.js";
2
+ import { useCallback, useEffect, useRef, useState } from "react";
3
+ // src/useTranscript.ts
4
+ var MAX_REPLAY_FRAMES = 5e3;
5
+ function keepForSeed(frames, ev) {
6
+ frames.push(ev);
7
+ if (frames.length > MAX_REPLAY_FRAMES) frames.shift();
8
+ }
9
+ /** Matches the way the echo is recognised: by turn once the send has named it,
10
+ * by text before then. */
11
+ function echoedSend(unechoed, ev) {
12
+ if (ev.type !== "user_message" && ev.type !== "user_note") return;
13
+ const steered = ev.type === "user_note";
14
+ for (const [localId, sent] of unechoed) {
15
+ if (!!sent.steered !== steered) continue;
16
+ if (sent.turnId ? sent.turnId === ev.turnId : sent.text === ev.content) return localId;
17
+ }
18
+ }
19
+ /** Discarded, or placed by an older daemon's turn end: no echo is coming. */
20
+ function forgetSettled(unechoed, before, after) {
21
+ const count = (s) => s.notes.length + s.steered.length + s.queued.length;
22
+ if (count(after) >= count(before)) return;
23
+ const still = new Set(pendingMessages(after).map((m) => m.id));
24
+ for (const m of pendingMessages(before)) if (!still.has(m.id)) unechoed.delete(m.id);
25
+ }
26
+ /** A turn prompted on a subagent echoes no user_message, so its history places
27
+ * the message: once it reaches the turn's first frame, or ends on the same words. */
28
+ function forgetPlaced(unechoed, detail) {
29
+ const last = detail.history?.findLast((h) => h.kind === "user" && !h.fromMain)?.text;
30
+ for (const [localId, sent] of unechoed) {
31
+ const reached = sent.placedSeq !== void 0 && (detail.lastSeq ?? 0) >= sent.placedSeq;
32
+ if (!sent.steered && (reached || sent.text === last)) unechoed.delete(localId);
33
+ }
34
+ }
35
+ /** Holds the live transcript for one session. The host still owns the socket
36
+ * and the fetch: it feeds events to `onEvent` and posts through `send`. */
37
+ function usePwCodeTranscript({ sessionId, subagent, detail, send, steer, withdraw, onEffect, goalNotice, compactionNotice, recapNotice, words, imageUrl }) {
38
+ const [transcript, setTranscript] = useState(null);
39
+ const transcriptRef = useRef(null);
40
+ const [sending, setSending] = useState(false);
41
+ const ownTurnIds = useRef(/* @__PURE__ */ new Set());
42
+ const ownTexts = useRef(/* @__PURE__ */ new Set());
43
+ const ownSeq = useRef(0);
44
+ const unechoed = useRef(/* @__PURE__ */ new Map());
45
+ const appliedSinceSeed = useRef([]);
46
+ const sendRef = useRef(send);
47
+ const steerRef = useRef(steer);
48
+ const withdrawRef = useRef(withdraw);
49
+ const onEffectRef = useRef(onEffect);
50
+ sendRef.current = send;
51
+ steerRef.current = steer;
52
+ withdrawRef.current = withdraw;
53
+ onEffectRef.current = onEffect;
54
+ const goalNoticeRef = useRef(goalNotice);
55
+ goalNoticeRef.current = goalNotice;
56
+ const compactionNoticeRef = useRef(compactionNotice);
57
+ compactionNoticeRef.current = compactionNotice;
58
+ const recapNoticeRef = useRef(recapNotice);
59
+ recapNoticeRef.current = recapNotice;
60
+ const wordsRef = useRef(words);
61
+ wordsRef.current = words;
62
+ const imageUrlRef = useRef(imageUrl);
63
+ imageUrlRef.current = imageUrl;
64
+ useEffect(() => {
65
+ if (!detail) return;
66
+ const { lastSeq } = detail;
67
+ if (lastSeq === void 0 && appliedSinceSeed.current.length > 0) {
68
+ appliedSinceSeed.current = [];
69
+ onEffectRef.current({ type: "refetch" });
70
+ return;
71
+ }
72
+ if (subagent) forgetPlaced(unechoed.current, detail);
73
+ let next = initialTranscript(detail, {
74
+ goalNotice: goalNoticeRef.current,
75
+ compactionNotice: compactionNoticeRef.current,
76
+ recapNotice: recapNoticeRef.current,
77
+ words: wordsRef.current,
78
+ imageUrl: imageUrlRef.current
79
+ });
80
+ if (subagent) {
81
+ for (const [localId, sent] of unechoed.current) if (!sent.steered) {
82
+ const { text, pastes, previews } = sent;
83
+ next = appendTurnMessage(next, text, localId, pastes, previews);
84
+ }
85
+ }
86
+ const replay = appliedSinceSeed.current.filter((ev) => ev.seq > (lastSeq ?? 0));
87
+ appliedSinceSeed.current = replay;
88
+ for (const ev of replay) next = applyStreamEvent(next, ev, {
89
+ goalNotice: goalNoticeRef.current,
90
+ recapNotice: recapNoticeRef.current,
91
+ words: wordsRef.current,
92
+ imageUrl: imageUrlRef.current
93
+ }).state;
94
+ for (const [localId, sent] of unechoed.current) {
95
+ const { text, pastes, previews, steered } = sent;
96
+ if (steered) next = appendSteeredMessage(next, text, localId, pastes, previews);
97
+ else if (!subagent) next = appendOwnMessage(next, text, localId, pastes, previews);
98
+ }
99
+ const cursor = Math.max(next.cursor, transcriptRef.current?.cursor ?? 0);
100
+ next = cursor === next.cursor ? next : {
101
+ ...next,
102
+ cursor
103
+ };
104
+ transcriptRef.current = next;
105
+ setTranscript(next);
106
+ }, [detail, subagent]);
107
+ const apply = useCallback((change) => {
108
+ const current = transcriptRef.current;
109
+ if (!current) return;
110
+ const next = change(current);
111
+ transcriptRef.current = next;
112
+ setTranscript(next);
113
+ }, []);
114
+ const onEvent = useCallback((frame) => {
115
+ const ev = subagent ? subagentFrame(frame, subagent) : frame;
116
+ if (ev === "refetch") {
117
+ onEffectRef.current({ type: "refetch" });
118
+ return;
119
+ }
120
+ if (!ev) return;
121
+ const current = transcriptRef.current;
122
+ if (!current) {
123
+ if (subagent) keepForSeed(appliedSinceSeed.current, ev);
124
+ return;
125
+ }
126
+ if (subagent && ev.turnId) {
127
+ for (const sent of unechoed.current.values()) if (sent.turnId === ev.turnId) sent.placedSeq ??= ev.seq;
128
+ }
129
+ const echoOf = echoedSend(unechoed.current, ev);
130
+ const { state, effects } = applyStreamEvent(current, ev, {
131
+ ownTurnIds: ownTurnIds.current,
132
+ ownTexts: ownTexts.current,
133
+ sessionId,
134
+ echoOf,
135
+ goalNotice: goalNoticeRef.current,
136
+ recapNotice: recapNoticeRef.current,
137
+ words: wordsRef.current,
138
+ imageUrl: imageUrlRef.current
139
+ });
140
+ if (ev.type === "replay_truncated") appliedSinceSeed.current = [];
141
+ else if (state.cursor > current.cursor) {
142
+ keepForSeed(appliedSinceSeed.current, ev);
143
+ if (echoOf) unechoed.current.delete(echoOf);
144
+ forgetSettled(unechoed.current, current, state);
145
+ }
146
+ apply(() => state);
147
+ for (const effect of effects) onEffectRef.current(effect);
148
+ if (subagent && frame.type === "subagent_user_note") onEffectRef.current({ type: "refetch" });
149
+ }, [
150
+ apply,
151
+ sessionId,
152
+ subagent
153
+ ]);
154
+ /** True once the running turn took the text, or the refusal if it may have.
155
+ * Commands and shell escapes change the next turn, so like the TUI they wait. */
156
+ const trySteer = useCallback(async (text, { pastes, images, previews }) => {
157
+ const steerTo = steerRef.current;
158
+ if (!steerTo || !turnRunning(transcriptRef.current) || /^[/!]/.test(text.trimStart())) return false;
159
+ ownSeq.current += 1;
160
+ const localId = `own-${ownSeq.current}`;
161
+ unechoed.current.set(localId, {
162
+ text,
163
+ pastes,
164
+ previews,
165
+ steered: true
166
+ });
167
+ apply((state) => appendSteeredMessage(state, text, localId, pastes, previews));
168
+ const result = await steerTo(text, pastes, images);
169
+ if ("delivered" in result && result.delivered) return true;
170
+ unechoed.current.delete(localId);
171
+ apply((state) => dropMessage(state, localId));
172
+ return "lost" in result ? result.lost : false;
173
+ }, [apply]);
174
+ const sendMessage = useCallback(async (text, options = {}) => {
175
+ const { pastes, images, previews } = options;
176
+ setSending(true);
177
+ const steered = options.steer !== false && await trySteer(text, options);
178
+ if (steered) {
179
+ setSending(false);
180
+ return steered === true ? null : steered;
181
+ }
182
+ ownTexts.current.add(text);
183
+ ownSeq.current += 1;
184
+ const localId = `own-${ownSeq.current}`;
185
+ unechoed.current.set(localId, {
186
+ text,
187
+ pastes,
188
+ previews
189
+ });
190
+ const append = subagent ? appendTurnMessage : appendOwnMessage;
191
+ apply((state) => append(state, text, localId, pastes, previews));
192
+ const result = await sendRef.current(text, pastes, images);
193
+ setSending(false);
194
+ if ("error" in result) {
195
+ ownTexts.current.delete(text);
196
+ unechoed.current.delete(localId);
197
+ apply((state) => dropMessage(state, localId));
198
+ if (subagent) onEffectRef.current({ type: "refetch" });
199
+ return result.error;
200
+ }
201
+ if (result.queued && unechoed.current.has(localId)) apply((state) => markQueued(state, localId));
202
+ if (result.turnId) {
203
+ ownTurnIds.current.add(result.turnId);
204
+ ownTexts.current.delete(text);
205
+ const pending = unechoed.current.get(localId);
206
+ if (pending) pending.turnId = result.turnId;
207
+ }
208
+ return null;
209
+ }, [
210
+ apply,
211
+ trySteer,
212
+ subagent
213
+ ]);
214
+ const resolveApproval = useCallback((approvalId) => apply((state) => resolveApprovalEverywhere(state, approvalId)), [apply]);
215
+ const noteShellRun = useCallback((command, output) => apply((state) => appendShellRun(state, command, output)), [apply]);
216
+ const queuedTurn = (id) => {
217
+ const sent = unechoed.current.get(id);
218
+ const queued = transcriptRef.current?.queued.some((m) => m.id === id);
219
+ return sent && !sent.steered && queued ? sent.turnId : void 0;
220
+ };
221
+ return {
222
+ transcript,
223
+ sending,
224
+ onEvent,
225
+ sendMessage,
226
+ resolveApproval,
227
+ noteShellRun,
228
+ canRemoveQueued: useCallback((id) => !!withdrawRef.current && !!queuedTurn(id), []),
229
+ removeQueued: useCallback(async (id) => {
230
+ const turnId = queuedTurn(id);
231
+ const withdrawFrom = withdrawRef.current;
232
+ if (!turnId || !withdrawFrom) return null;
233
+ const result = await withdrawFrom(turnId);
234
+ if (result.error) return result.error;
235
+ unechoed.current.delete(id);
236
+ ownTurnIds.current.delete(turnId);
237
+ apply((state) => dropMessage(state, id));
238
+ return null;
239
+ }, [apply]),
240
+ cursor: useCallback(() => transcriptRef.current?.cursor ?? 0, [])
241
+ };
242
+ }
243
+ export { usePwCodeTranscript };
@@ -0,0 +1,43 @@
1
+ import { type PwCodeMachine } from './machine.js';
2
+ import type { PwCodeTranslator } from './messages.js';
3
+ import { type PwCodePendingApprovals, type PwCodeSession } from './session.js';
4
+ import type { PwCodeSessionStatus } from './types.js';
5
+ type Translate = PwCodeTranslator<'agents'>;
6
+ /** How a prompt refers to an image sent with it: `[Image #1]`. */
7
+ export declare const IMAGE_PLACEHOLDER: RegExp;
8
+ /** Mirrors the machine's preview of a first prompt, so the label does not
9
+ * change when the listed one arrives. */
10
+ export declare function rememberSentPrompt(machine: string, id: string, text: string): void;
11
+ /** The id is never a label: it is a timestamp the reader did not choose. */
12
+ export declare function sessionLabel(s: Pick<PwCodeSession, 'machineId' | 'id' | 'name' | 'autoName' | 'preview'>, t: Translate): string;
13
+ export declare function sessionStatusText(s: {
14
+ status: PwCodeSessionStatus;
15
+ liveHost?: string | undefined;
16
+ approvals?: PwCodePendingApprovals;
17
+ }, t: Translate): string;
18
+ /** A dropped machine outranks the session's own state. */
19
+ export declare function sessionStateText(s: Parameters<typeof sessionStatusText>[0], machine: Pick<PwCodeMachine, 'status'> | undefined, t: Translate): string;
20
+ export declare function machineHint(machine: Pick<PwCodeMachine, 'status' | 'error' | 'agentVersion'>, t: Translate): {
21
+ text: string;
22
+ detail?: string;
23
+ } | null;
24
+ export declare function composerState(args: {
25
+ unreachable: boolean;
26
+ /** Anything sent to an archived session would attach it, which restores it. */
27
+ archived: boolean;
28
+ machineName: string;
29
+ /** How long ago the transcript was last read, already abbreviated. */
30
+ staleFor: string;
31
+ status: PwCodeSessionStatus | null;
32
+ liveHost: string | undefined;
33
+ /** What the session is waiting on while it awaits approval. */
34
+ approvals?: PwCodePendingApprovals;
35
+ /** The `!` command this client is running on the machine, if any. */
36
+ shellRun?: string | undefined;
37
+ t: Translate;
38
+ }): {
39
+ placeholder: string;
40
+ hint: string;
41
+ locked: boolean;
42
+ };
43
+ export {};
@@ -0,0 +1,101 @@
1
+ import { isMachineDown } from "./machine.js";
2
+ import { sessionKey, waitsOnAnswer } from "./session.js";
3
+ import { nameToEmoji } from "gemoji";
4
+ // src/wording.ts
5
+ /** How a prompt refers to an image sent with it: `[Image #1]`. */
6
+ var IMAGE_PLACEHOLDER = /\[Image #(\d+)\]/g;
7
+ var sentPreviews = /* @__PURE__ */ new Map();
8
+ var PREVIEW_MAX = 80;
9
+ /** Mirrors the machine's preview of a first prompt, so the label does not
10
+ * change when the listed one arrives. */
11
+ function rememberSentPrompt(machine, id, text) {
12
+ const words = (text.replace(IMAGE_PLACEHOLDER, "").trim() || text).split(/\s+/).filter(Boolean).join(" ");
13
+ if (words) sentPreviews.set(sessionKey({
14
+ machineId: machine,
15
+ id
16
+ }), words.length > PREVIEW_MAX ? `${words.slice(0, PREVIEW_MAX)}...` : words);
17
+ }
18
+ /** The id is never a label: it is a timestamp the reader did not choose. */
19
+ function sessionLabel(s, t) {
20
+ return (s.name || s.autoName || s.preview || sentPreviews.get(sessionKey(s)) || t("sidebar.untitled")).replace(/:([\w+-]+):/g, (match, name) => {
21
+ const key = name.toLowerCase();
22
+ return Object.hasOwn(nameToEmoji, key) ? nameToEmoji[key] ?? match : match;
23
+ });
24
+ }
25
+ function sessionStatusText(s, t) {
26
+ if (s.status === "awaiting_approval" && waitsOnAnswer(s.approvals)) return t("status.awaiting_answer");
27
+ return t(`status.${s.status}`, { host: s.liveHost ?? "" });
28
+ }
29
+ var DOWN_STATUSES = [
30
+ "no_daemon",
31
+ "no_agent",
32
+ "unreachable",
33
+ "unsupported_agent"
34
+ ];
35
+ function isDownStatus(status) {
36
+ return DOWN_STATUSES.includes(status);
37
+ }
38
+ /** A dropped machine outranks the session's own state. */
39
+ function sessionStateText(s, machine, t) {
40
+ if (!isMachineDown(machine)) return sessionStatusText(s, t);
41
+ return t(`machine.${isDownStatus(machine.status) ? machine.status : "unreachable"}`);
42
+ }
43
+ function machineHint(machine, t) {
44
+ const detail = machine.error ? { detail: machine.error } : {};
45
+ switch (machine.status) {
46
+ case "connected": return null;
47
+ case "no_daemon": return {
48
+ text: t("machine.noDaemonHint"),
49
+ ...detail
50
+ };
51
+ case "no_agent": return {
52
+ text: t("machine.noAgentHint"),
53
+ ...detail
54
+ };
55
+ case "unsupported_agent": return {
56
+ text: machine.agentVersion ? t("machine.unsupportedHintVersion", { version: machine.agentVersion }) : t("machine.unsupportedHint"),
57
+ ...detail
58
+ };
59
+ default: return {
60
+ text: t("machine.unreachableHint"),
61
+ ...detail
62
+ };
63
+ }
64
+ }
65
+ function composerState(args) {
66
+ const { unreachable, archived, machineName, staleFor, status, liveHost, approvals, shellRun, t } = args;
67
+ if (unreachable) return {
68
+ placeholder: t("detail.composerUnreachable", { machine: machineName }),
69
+ hint: t("detail.footerUnreachable", { when: staleFor }),
70
+ locked: true
71
+ };
72
+ if (archived) return {
73
+ placeholder: t("detail.composerArchived"),
74
+ hint: t("detail.footerArchived"),
75
+ locked: true
76
+ };
77
+ if (status === "live_elsewhere") return {
78
+ placeholder: t("detail.composerLiveElsewhere", { host: liveHost ?? "" }),
79
+ hint: t("detail.footerLiveElsewhere"),
80
+ locked: true
81
+ };
82
+ if (status === "awaiting_approval") {
83
+ const answer = waitsOnAnswer(approvals);
84
+ return {
85
+ placeholder: t(answer ? "detail.composerAwaitingAnswer" : "detail.composerAwaiting"),
86
+ hint: t(answer ? "detail.footerAwaitingAnswer" : "detail.footerAwaiting"),
87
+ locked: true
88
+ };
89
+ }
90
+ if (shellRun) return {
91
+ placeholder: t("detail.composerShellRunning"),
92
+ hint: t("detail.footerShellRunning", { command: shellRun }),
93
+ locked: true
94
+ };
95
+ return {
96
+ placeholder: t("detail.composerPlaceholder"),
97
+ hint: "",
98
+ locked: false
99
+ };
100
+ }
101
+ export { IMAGE_PLACEHOLDER, composerState, machineHint, rememberSentPrompt, sessionLabel, sessionStateText, sessionStatusText };