@parallelworks/code 0.5.0 → 0.6.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 (69) hide show
  1. package/README.md +53 -12
  2. package/dist/api.d.ts +67 -5
  3. package/dist/chatStrings.d.ts +3 -0
  4. package/dist/chatStrings.js +4 -1
  5. package/dist/command.d.ts +2 -0
  6. package/dist/command.js +5 -1
  7. package/dist/commandsApi.d.ts +8 -3
  8. package/dist/commandsApi.js +25 -4
  9. package/dist/createPwCodeApi.d.ts +26 -61
  10. package/dist/index.d.ts +6 -5
  11. package/dist/index.js +3 -2
  12. package/dist/locales/en/agentTranscript.js +5 -2
  13. package/dist/locales/en/agents.js +35 -4
  14. package/dist/locales/en.d.ts +33 -0
  15. package/dist/locales/es/agentTranscript.js +5 -2
  16. package/dist/locales/es/agents.js +35 -4
  17. package/dist/locales/ja/agentTranscript.js +5 -2
  18. package/dist/locales/ja/agents.js +30 -4
  19. package/dist/locales/ko/agentTranscript.js +5 -2
  20. package/dist/locales/ko/agents.js +35 -4
  21. package/dist/locales/zh/agentTranscript.js +5 -2
  22. package/dist/locales/zh/agents.js +35 -4
  23. package/dist/machine.d.ts +27 -2
  24. package/dist/machine.js +23 -2
  25. package/dist/notices.js +9 -1
  26. package/dist/pwUpdate.d.ts +52 -0
  27. package/dist/pwUpdate.js +115 -0
  28. package/dist/session.d.ts +1 -1
  29. package/dist/session.js +1 -1
  30. package/dist/sessionActions.js +5 -2
  31. package/dist/sessionEvents.d.ts +10 -3
  32. package/dist/sessionEvents.js +27 -11
  33. package/dist/sessionScreen.d.ts +3 -2
  34. package/dist/sessionScreen.js +8 -2
  35. package/dist/sessionsApi.d.ts +8 -2
  36. package/dist/sessionsApi.js +28 -5
  37. package/dist/startPage.d.ts +6 -3
  38. package/dist/startPage.js +34 -12
  39. package/dist/startSession.d.ts +31 -11
  40. package/dist/startSession.js +126 -44
  41. package/dist/terminalHandoffPanel.js +8 -1
  42. package/dist/transcript.d.ts +26 -3
  43. package/dist/transcript.js +87 -12
  44. package/dist/transcriptRead.d.ts +1 -0
  45. package/dist/transcriptRead.js +2 -1
  46. package/dist/types.d.ts +13 -1
  47. package/dist/useComposer.d.ts +22 -10
  48. package/dist/useComposer.js +75 -25
  49. package/dist/useComposerImages.d.ts +38 -1
  50. package/dist/useComposerImages.js +59 -4
  51. package/dist/useConversation.d.ts +10 -0
  52. package/dist/useConversation.js +14 -11
  53. package/dist/useSubagent.d.ts +20 -5
  54. package/dist/useSubagent.js +39 -17
  55. package/dist/useTranscript.d.ts +27 -1
  56. package/dist/useTranscript.js +217 -45
  57. package/dist/wording.d.ts +1 -1
  58. package/dist/wording.js +14 -2
  59. package/locales/en/agentTranscript.json +5 -2
  60. package/locales/en/agents.json +32 -2
  61. package/locales/es/agentTranscript.json +5 -2
  62. package/locales/es/agents.json +32 -2
  63. package/locales/ja/agentTranscript.json +5 -2
  64. package/locales/ja/agents.json +32 -2
  65. package/locales/ko/agentTranscript.json +5 -2
  66. package/locales/ko/agents.json +32 -2
  67. package/locales/zh/agentTranscript.json +5 -2
  68. package/locales/zh/agents.json +32 -2
  69. package/package.json +3 -3
@@ -1,17 +1,25 @@
1
- import { canStartHere, isMachineDown, splitMachines } from "./machine.js";
1
+ import { slashAction } from "./command.js";
2
+ import { canStartHere, isMachineDown, isStarting, isWorkspace, splitMachines } from "./machine.js";
3
+ import { usePwCodeTranslations } from "./messages.js";
2
4
  import { canRunModel, isClaudeModel, runsClaude } from "./models.js";
3
5
  import { recentDirectories } from "./session.js";
6
+ import { withImagePlaceholders } from "./useComposerImages.js";
4
7
  import { rememberSentPrompt } from "./wording.js";
5
8
  import { useEffect, useMemo, useRef, useState } from "react";
6
9
  import { clampPermissionMode } from "@parallelworks/ui/ai/headless";
7
10
  // src/startSession.ts
8
11
  /** The machines a session can start on, then those listed but not answering,
9
- * each with computers before resources. A resource with no agent on it is
10
- * one the reader has not touched, so it is not counted as down. */
12
+ * each with the workspace first, then computers, then resources. A resource
13
+ * with no agent on it is one the reader has not touched, so it is not
14
+ * counted as down. */
11
15
  function startMachines(machines) {
12
16
  const ordered = (list) => {
13
17
  const { computers, resources } = splitMachines(list);
14
- return [...computers, ...resources];
18
+ return [
19
+ ...resources.filter(isWorkspace),
20
+ ...computers,
21
+ ...resources.filter((m) => !isWorkspace(m))
22
+ ];
15
23
  };
16
24
  return {
17
25
  startable: ordered(machines.filter(canStartHere)),
@@ -29,7 +37,10 @@ function useStartLocation(machines, sessions, preference) {
29
37
  const { startable, down } = useMemo(() => startMachines(machines), [machines]);
30
38
  const [machineId, setMachineId] = useState("");
31
39
  const wanted = machineId || preference?.saved;
32
- const machine = startable.find((m) => m.id === wanted) ?? (startable.length === 1 ? startable[0] : void 0);
40
+ const chosen = startable.find((m) => m.id === wanted);
41
+ const starting = down.find((m) => isWorkspace(m) && isStarting(m));
42
+ const pending = chosen ? void 0 : starting;
43
+ const machine = chosen ?? (pending ? void 0 : startable.find(isWorkspace) ?? (startable.length === 1 ? startable[0] : void 0));
33
44
  const directories = useMemo(() => recentDirectories(sessions, machine?.id), [sessions, machine]);
34
45
  const [dir, setDir] = useState("");
35
46
  const [typing, setTyping] = useState(false);
@@ -40,7 +51,7 @@ function useStartLocation(machines, sessions, preference) {
40
51
  setDir("");
41
52
  setTyping(false);
42
53
  }, [machine?.id]);
43
- const directory = typing ? dir : dir || directories[0]?.path || "";
54
+ const directory = typing ? dir : dir || directories[0]?.path || machine?.home || "";
44
55
  const typeDirectory = (path) => {
45
56
  setTyping(true);
46
57
  setDir(path);
@@ -48,6 +59,7 @@ function useStartLocation(machines, sessions, preference) {
48
59
  return {
49
60
  startable,
50
61
  down,
62
+ pending,
51
63
  machine,
52
64
  pickMachine: (id) => {
53
65
  setMachineId(id);
@@ -159,32 +171,36 @@ function sessionBody(machine, { directory, mode, model, effort, allocation, acco
159
171
  ...prompt ? { prompt } : {}
160
172
  };
161
173
  }
162
- /** The prompt, then each image it does not name already. */
163
- function withPlaceholders(prompt, images) {
164
- return [prompt, ...images.map((image) => image.placeholder).filter((placeholder) => !prompt.includes(placeholder))].filter(Boolean).join(" ");
174
+ /** `/goal` or `/plan` typed as the first prompt. The machine refuses either as
175
+ * a message, since each has a route of its own, as typed in an open session. */
176
+ function startCommand(typed) {
177
+ const action = slashAction(typed, {});
178
+ return action.kind === "goal" || action.kind === "plan" ? action : null;
165
179
  }
166
180
  /** Starts a session, reads the listing again so it shows there, and hands it
167
- * to `onStarted` once its first prompt is sent. With images, the session is
168
- * created first and they are saved with it; a retry after they fail reuses
169
- * that session while nothing it started with has changed. */
181
+ * to `onStarted` once its first prompt is sent. With images, or for a typed
182
+ * `/goal` or `/plan`, the session is created empty first, then the images go
183
+ * with the prompt or the command runs; a session whose start fails after that
184
+ * is deleted, so nothing is left behind and a retry starts afresh. */
170
185
  function useStartSession(api, options) {
171
186
  const { machine, directory, images, firstPrompt, onStarted } = options;
187
+ const t = usePwCodeTranslations("agents");
172
188
  const { mutate } = api.useSessions();
189
+ const { deleteSession, groupSession } = api.useSessionMutations();
173
190
  const [starting, setStarting] = useState(false);
174
191
  const [error, setError] = useState(null);
175
- const pendingSession = useRef(null);
176
- const config = JSON.stringify([
177
- machine?.id,
178
- directory,
179
- options.mode,
180
- options.model,
181
- options.effort,
182
- options.allocation,
183
- options.account
184
- ]);
192
+ const [blocked, setBlocked] = useState(null);
185
193
  const ready = !!machine && directory.startsWith("/") && !starting && !options.waiting;
186
- const started = (machineId, id, text) => {
194
+ const started = async (machineId, id, text) => {
187
195
  rememberSentPrompt(machineId, id, text);
196
+ const { group, onGroupRefused } = options;
197
+ if (group) {
198
+ const refusal = await groupSession({
199
+ machineId,
200
+ id
201
+ }, group).catch((thrown) => thrown);
202
+ if (refusal) onGroupRefused?.(refusal);
203
+ }
188
204
  mutate();
189
205
  onStarted(machineId, id);
190
206
  };
@@ -200,7 +216,7 @@ function useStartSession(api, options) {
200
216
  const send = async (on, id, first) => {
201
217
  const saved = images ? await images.saveTo(on.id, id) : [];
202
218
  if (saved === null) return false;
203
- const text = withPlaceholders(first, saved);
219
+ const text = withImagePlaceholders(first, saved);
204
220
  const { error: failed } = await api.sendMessage(on.id, id, {
205
221
  text,
206
222
  images: saved
@@ -209,36 +225,55 @@ function useStartSession(api, options) {
209
225
  setError(failed);
210
226
  return false;
211
227
  }
212
- started(on.id, id, text);
228
+ await started(on.id, id, text);
229
+ return true;
230
+ };
231
+ /** Runs the command, as typed in an open session, and sends the task `/plan`
232
+ * hands back as the first message. False once its refusal is kept. */
233
+ const run = async (on, id, typed, command) => {
234
+ const outcome = await api.runSlashAction(on.id, id, command, (path) => t("detail.planOnMachine", { path }));
235
+ if (outcome.kind === "refused") {
236
+ setError(outcome.error);
237
+ return false;
238
+ }
239
+ if (outcome.kind === "send") return send(on, id, outcome.text);
240
+ await started(on.id, id, command.kind === "goal" ? typed : "");
213
241
  return true;
214
242
  };
243
+ const filled = async (on, id, fill) => {
244
+ let done = false;
245
+ try {
246
+ done = await fill();
247
+ } finally {
248
+ if (!done) await deleteSession({
249
+ machineId: on.id,
250
+ id
251
+ }).catch(() => {});
252
+ }
253
+ return done;
254
+ };
215
255
  const attempt = async (on, prompt) => {
216
- const pending = pendingSession.current?.config === config ? pendingSession.current.id : "";
256
+ const command = startCommand(prompt);
257
+ if (command && (images?.count || firstPrompt)) {
258
+ setBlocked(t("start.commandAlone", { command: `/${command.kind}` }));
259
+ return false;
260
+ }
217
261
  const first = firstPrompt ? firstPrompt(prompt) : prompt;
218
- const withImages = !!images?.count;
219
- if (withImages) pendingSession.current = {
220
- id: pending,
221
- config
222
- };
223
- if (pending) return send(on, pending, first);
224
- const id = await create(on, withImages ? "" : first);
262
+ const createsEmpty = !!images?.count || command !== null;
263
+ const id = await create(on, createsEmpty ? "" : first);
225
264
  if (!id) return false;
226
- if (!withImages) {
227
- started(on.id, id, first);
265
+ if (!createsEmpty) {
266
+ await started(on.id, id, first);
228
267
  return true;
229
268
  }
230
- pendingSession.current = {
231
- id,
232
- config
233
- };
234
- return send(on, id, first);
269
+ return filled(on, id, () => command ? run(on, id, prompt, command) : send(on, id, first));
235
270
  };
236
- const start = async (prompt) => {
237
- if (!ready || !machine) return false;
271
+ const begin = async (on, prompt) => {
238
272
  setStarting(true);
239
273
  setError(null);
274
+ setBlocked(null);
240
275
  try {
241
- return await attempt(machine, prompt);
276
+ return await attempt(on, prompt);
242
277
  } catch (thrown) {
243
278
  setError(thrown);
244
279
  return false;
@@ -246,11 +281,58 @@ function useStartSession(api, options) {
246
281
  setStarting(false);
247
282
  }
248
283
  };
284
+ const [held, setHeld] = useState(null);
285
+ const canHold = !machine && !!options.pending && !held && !starting && !options.waiting;
286
+ const start = async (prompt) => {
287
+ if (ready && machine) return begin(machine, prompt);
288
+ if (canHold && options.pending) {
289
+ setHeld({
290
+ text: prompt,
291
+ on: options.pending,
292
+ state: "waiting"
293
+ });
294
+ return true;
295
+ }
296
+ return false;
297
+ };
298
+ useEffect(() => {
299
+ if (held?.state !== "waiting") return;
300
+ if (machine ? machine.id !== held.on : !options.pending) {
301
+ setHeld({
302
+ ...held,
303
+ state: "failed"
304
+ });
305
+ return;
306
+ }
307
+ if (!ready || !machine) return;
308
+ setHeld({
309
+ ...held,
310
+ state: "sending"
311
+ });
312
+ begin(machine, held.text).then((done) => setHeld(done ? null : {
313
+ ...held,
314
+ state: "failed"
315
+ }));
316
+ }, [
317
+ held,
318
+ ready,
319
+ machine,
320
+ options.pending
321
+ ]);
249
322
  return {
250
323
  ready,
251
324
  starting,
252
325
  error,
253
- start
326
+ blocked,
327
+ start,
328
+ canHold,
329
+ held: held && held.state !== "failed" ? held.text : null,
330
+ heldFailed: held?.state === "failed",
331
+ takeHeld: () => {
332
+ if (!held || held.state === "sending") return null;
333
+ setHeld(null);
334
+ return held.text;
335
+ }
254
336
  };
255
337
  }
256
338
  export { startControls, startMachines, startingMode, useStartLocation, useStartModel, useStartPermissionMode, useStartSession };
@@ -15,12 +15,19 @@ function terminalHandoffPanel(listing, machine, sessionId, username, t) {
15
15
  return {
16
16
  status: "ready",
17
17
  handoff,
18
- body: handoff.on === "resource" ? t("terminal.resourceBody", { machine: found.name }) : t("terminal.computerBody", { host: handoff.host }),
18
+ body: handoffBody(handoff, found, t),
19
19
  commandLabel: t("terminal.commandLabel"),
20
20
  anyTerminal: handoff.on === "resource" ? t("terminal.anyTerminal") : void 0,
21
21
  archived: session && isArchived(session) ? t("terminal.archived") : void 0
22
22
  };
23
23
  }
24
+ function handoffBody(handoff, machine, t) {
25
+ switch (handoff.on) {
26
+ case "resource": return t("terminal.resourceBody", { machine: machine.name });
27
+ case "workspace": return t("terminal.workspaceBody");
28
+ case "computer": return t("terminal.computerBody", { host: handoff.host });
29
+ }
30
+ }
24
31
  /** A handoff command split before the session it names, which a narrow
25
32
  * panel keeps whole rather than breaking at a hyphen in its id. */
26
33
  function handoffCommandParts(command) {
@@ -1,5 +1,5 @@
1
1
  import { type ApprovalAnswerValue, type ApprovalPart, type ChatMessage, type MessagePart, type MessagePaste, type SubagentNotice, type TodoItem, type ToolDecision } from '@parallelworks/ui/ai/headless';
2
- import type { PwCodeAllowedDirectory, PwCodeApprovalAnswer, PwCodeApprovalRequest, PwCodeGoalStatus, PwCodeHistoryItem, PwCodeImage, PwCodeSessionDetail, PwCodeSessionState, PwCodeSessionStatus, PwCodeGoalProgress, PwCodeStreamEvent, PwCodeSubagentDetail, PwCodeToolDecision, PwCodeTurnEnd } from './types.js';
2
+ import type { PwCodeAllowedDirectory, PwCodeApprovalAnswer, PwCodeApprovalRequest, PwCodeGoalStatus, PwCodeHistoryItem, PwCodeImage, PwCodeSessionDetail, PwCodeSessionState, PwCodeSessionStatus, PwCodeGoalProgress, PwCodeScheduledRun, PwCodeStreamEvent, PwCodeSubagentDetail, PwCodeToolDecision, PwCodeTurnEnd } from './types.js';
3
3
  export interface TranscriptState {
4
4
  messages: ChatMessage[];
5
5
  streaming: ChatMessage | null;
@@ -45,10 +45,12 @@ export declare function approvalToPart(req: PwCodeApprovalRequest, words?: Pick<
45
45
  export declare function approvalAnswerBody(answer: ApprovalAnswerValue): PwCodeApprovalAnswer;
46
46
  /** A review still under way, or one the turn cut short, settled nothing. */
47
47
  export declare function toolDecision(d: PwCodeToolDecision): ToolDecision | null;
48
- /** Ids come from the item's position, so a refetch keeps message identity and
49
- * React does not remount (and collapse) the whole transcript. */
48
+ /** Ids come from each item's position in the session's whole history, which
49
+ * `historyStart` says this part of it begins at: the end of a transcript drawn
50
+ * early and every read after it name a message alike, so React keeps its row. */
50
51
  export declare function historyToMessages(history: PwCodeHistoryItem[], options?: {
51
52
  finalizeOpen?: boolean;
53
+ historyStart?: number | undefined;
52
54
  goalNotice?: GoalNotice | undefined;
53
55
  compactionNotice?: CompactionNotice | undefined;
54
56
  recapNotice?: RecapNotice | undefined;
@@ -83,11 +85,15 @@ export declare function resolveApprovalEverywhere(state: TranscriptState, id: st
83
85
  * short, so the page must not close the turn either: its open tool calls
84
86
  * would read as interrupted while they are still running. */
85
87
  export declare function appendOwnMessage(state: TranscriptState, text: string, id?: string, pastes?: MessagePaste[], previews?: PwCodeImage[]): TranscriptState;
88
+ /** Waits for its own turn, which its echo begins. */
89
+ export declare function queueOwnMessage(state: TranscriptState, text: string, id?: string, pastes?: MessagePaste[], previews?: PwCodeImage[]): TranscriptState;
86
90
  /** A subagent runs one turn at a time, so a message sent to it starts its next:
87
91
  * a turn the transcript still shows running has ended. */
88
92
  export declare function appendTurnMessage(state: TranscriptState, text: string, id?: string, pastes?: MessagePaste[], previews?: PwCodeImage[]): TranscriptState;
89
93
  /** Held apart until the daemon reports the model was handed it. */
90
94
  export declare function appendSteeredMessage(state: TranscriptState, text: string, id?: string, pastes?: MessagePaste[], previews?: PwCodeImage[]): TranscriptState;
95
+ /** A command the machine is running, as it was typed; it opens no turn. */
96
+ export declare function appendCommand(state: TranscriptState, command: string, id: string): TranscriptState;
91
97
  /** The daemon queued a message this page had shown as sent, because the turn
92
98
  * ahead of it had not reached the page yet. */
93
99
  export declare function markQueued(state: TranscriptState, id: string): TranscriptState;
@@ -100,6 +106,9 @@ export declare function pendingMessages(state: TranscriptState): ChatMessage[];
100
106
  export declare function turnRunning(state: TranscriptState | null): boolean;
101
107
  /** Whether the turn waits on a Bash call, which the machine can move to the background. */
102
108
  export declare function bashRunning(state: TranscriptState | null): boolean;
109
+ /** Daemons before the interrupted flag close a stopped turn with the
110
+ * cancelled context's error. */
111
+ export declare function stoppedTurn(ev: PwCodeStreamEvent): boolean;
103
112
  /** What the agent records for a call a stop cut off (serverapi.UserInterruptedTool), so a stopped call reads live as it replays. */
104
113
  export declare function userInterruptedTool(name: string): string;
105
114
  /** How a /goal loop step reads, in the reader's language. */
@@ -127,6 +136,20 @@ export interface TranscriptWords {
127
136
  allowDirectory: (dir: PwCodeAllowedDirectory) => string;
128
137
  /** Who wrote a subagent's prompt: the conversation that started it. */
129
138
  mainConversation: string;
139
+ /** What a skill's /name answers, under the person's message. */
140
+ skillActivated: (activation: SkillActivation) => string;
141
+ /** The line a turn a scheduled task started opens with, in place of the person's message. */
142
+ scheduledRun: (run: PwCodeScheduledRun) => string;
143
+ }
144
+ /** A skill the person started with /name, as the session announces it. */
145
+ export interface SkillActivation {
146
+ name: string;
147
+ /** Where the skill was found; null when the session couldn't say. */
148
+ source: 'project' | 'user' | 'built-in' | null;
149
+ /** Its shell commands and allowed tools stay off until /skills trust. */
150
+ untrusted: boolean;
151
+ /** The line as the session wrote it. */
152
+ line: string;
130
153
  }
131
154
  /** The verb the terminal picks for a turn, so the same turn reads the same in both. */
132
155
  export declare function turnVerb(endedAt: string): TurnVerb;
@@ -1,3 +1,4 @@
1
+ import { invocationName } from "./command.js";
1
2
  import { runsInBackgroundTool } from "./commandsApi.js";
2
3
  import { sessionImagePreviewUrl } from "./images.js";
3
4
  import { pinnedTodos, todosFromHistory } from "./todos.js";
@@ -171,10 +172,12 @@ function toolDecision(d) {
171
172
  ...d.action ? { action: d.action } : {}
172
173
  };
173
174
  }
174
- /** Ids come from the item's position, so a refetch keeps message identity and
175
- * React does not remount (and collapse) the whole transcript. */
175
+ /** Ids come from each item's position in the session's whole history, which
176
+ * `historyStart` says this part of it begins at: the end of a transcript drawn
177
+ * early and every read after it name a message alike, so React keeps its row. */
176
178
  function historyToMessages(history, options = {}) {
177
179
  const finalizeOpen = options.finalizeOpen ?? true;
180
+ const start = options.historyStart ?? 0;
178
181
  const { words } = options;
179
182
  const lastSettledTurnEnd = history.findLastIndex((item) => item.kind === "turn_end" && !item.turnEnd?.pendingAgents);
180
183
  const messages = [];
@@ -222,8 +225,8 @@ function historyToMessages(history, options = {}) {
222
225
  });
223
226
  };
224
227
  const pending = [];
225
- const settle = (call, result) => {
226
- open(-1);
228
+ const settle = (call, result, index) => {
229
+ open(index);
227
230
  const at = call.kind === "tool" ? running.shift() : call.kind === "hidden" ? void 0 : cards.get(call.id);
228
231
  const part = at === void 0 ? void 0 : parts[at];
229
232
  if (at !== void 0 && part) parts[at] = settledPart(part, result);
@@ -232,10 +235,15 @@ function historyToMessages(history, options = {}) {
232
235
  const waiting = new Set(pending.flatMap((call) => call.kind === "ask" ? [call.id] : []));
233
236
  if (current && waiting.size > 0) parts = parts.filter((p) => !(p.kind === "approval" && waiting.has(p.id)));
234
237
  };
235
- history.forEach((item, index) => {
238
+ history.forEach((item, at) => {
239
+ const index = start + at;
236
240
  switch (item.kind) {
237
241
  case "user": {
238
242
  flush(true);
243
+ if (item.scheduled) {
244
+ append(scheduledRunPart(item.scheduled, item.text ?? "", words), index);
245
+ return;
246
+ }
239
247
  const shell = parseShellRecord(item.text ?? "");
240
248
  if (shell) {
241
249
  append(shellRunPart(shell.command, shell.output), index);
@@ -315,7 +323,7 @@ function historyToMessages(history, options = {}) {
315
323
  }
316
324
  case "tool_result": {
317
325
  const call = pending.shift();
318
- if (call) settle(call, item.text ?? "");
326
+ if (call) settle(call, item.text ?? "", index);
319
327
  const images = imageAttachments(item.images, options.imageUrl);
320
328
  if (images.length) append({
321
329
  kind: "image",
@@ -333,6 +341,11 @@ function historyToMessages(history, options = {}) {
333
341
  }
334
342
  case "notice": {
335
343
  const text = item.text ?? "";
344
+ const answered = answeredSkillPrompt(messages.at(-1), text, words);
345
+ if (answered) {
346
+ messages[messages.length - 1] = answered;
347
+ return;
348
+ }
336
349
  const delivery = readDelivery(text);
337
350
  if (delivery?.silent) return;
338
351
  const detail = delivery ? deliveryDetail(delivery) : void 0;
@@ -383,7 +396,7 @@ function historyToMessages(history, options = {}) {
383
396
  case "turn_end": {
384
397
  const te = item.turnEnd;
385
398
  if (te && words) {
386
- const waiting = index > lastSettledTurnEnd && (te.pendingAgents ?? 0) > 0;
399
+ const waiting = at > lastSettledTurnEnd && (te.pendingAgents ?? 0) > 0;
387
400
  append({
388
401
  kind: "notice",
389
402
  text: words.turnEnd(te, turnVerb(te.endedAt), waiting)
@@ -462,6 +475,7 @@ function initialTranscript(detail, options = {}) {
462
475
  const running = detail.status === "awaiting_approval" || !!detail.turnId;
463
476
  const messages = historyToMessages(detail.history ?? [], {
464
477
  ...options,
478
+ historyStart: detail.historyStart,
465
479
  finalizeOpen: !running
466
480
  });
467
481
  let streaming = null;
@@ -572,11 +586,8 @@ function resolveApprovalEverywhere(state, id) {
572
586
  * short, so the page must not close the turn either: its open tool calls
573
587
  * would read as interrupted while they are still running. */
574
588
  function appendOwnMessage(state, text, id, pastes, previews) {
589
+ if (turnRunning(state)) return queueOwnMessage(state, text, id, pastes, previews);
575
590
  const message = userMessage(text, void 0, id, pastes, previews);
576
- if (turnRunning(state)) return {
577
- ...state,
578
- queued: [...state.queued, message]
579
- };
580
591
  return {
581
592
  ...state,
582
593
  messages: [...state.messages, message],
@@ -586,6 +597,14 @@ function appendOwnMessage(state, text, id, pastes, previews) {
586
597
  opening: message.id
587
598
  };
588
599
  }
600
+ /** Waits for its own turn, which its echo begins. */
601
+ function queueOwnMessage(state, text, id, pastes, previews) {
602
+ const message = userMessage(text, void 0, id, pastes, previews);
603
+ return {
604
+ ...state,
605
+ queued: [...state.queued, message]
606
+ };
607
+ }
589
608
  /** A subagent runs one turn at a time, so a message sent to it starts its next:
590
609
  * a turn the transcript still shows running has ended. */
591
610
  function appendTurnMessage(state, text, id, pastes, previews) {
@@ -612,6 +631,13 @@ function appendSteeredMessage(state, text, id, pastes, previews) {
612
631
  steered: [...state.steered, userMessage(text, void 0, id, pastes, previews)]
613
632
  };
614
633
  }
634
+ /** A command the machine is running, as it was typed; it opens no turn. */
635
+ function appendCommand(state, command, id) {
636
+ return {
637
+ ...state,
638
+ messages: [...state.messages, userMessage(command, void 0, id)]
639
+ };
640
+ }
615
641
  /** The daemon queued a message this page had shown as sent, because the turn
616
642
  * ahead of it had not reached the page yet. */
617
643
  function markQueued(state, id) {
@@ -812,6 +838,36 @@ var TURN_VERBS = [
812
838
  "sauteed",
813
839
  "worked"
814
840
  ];
841
+ var SKILL_ACTIVATION = /^⚡ activated skill \/(\S+) · (?:(project|user|built-in) skill|unknown source)( · shell and grants disabled until trusted \(\/skills trust \S+\))?$/;
842
+ function parseSkillActivation(text) {
843
+ const line = text.trim();
844
+ const match = SKILL_ACTIVATION.exec(line);
845
+ if (!match?.[1]) return null;
846
+ return {
847
+ name: match[1],
848
+ source: match[2] ?? null,
849
+ untrusted: !!match[3],
850
+ line
851
+ };
852
+ }
853
+ /** The /name message a skill's line answers, with the line hung under it; null for any other line. */
854
+ function answeredSkillPrompt(prompt, notice, words) {
855
+ const skill = parseSkillActivation(notice);
856
+ if (!skill || prompt?.role !== "user" || prompt.commandAnswer || invocationName(prompt.content ?? "") !== skill.name) return null;
857
+ return {
858
+ ...prompt,
859
+ commandAnswer: { text: words ? words.skillActivated(skill) : skill.line }
860
+ };
861
+ }
862
+ /** A scheduled task's turn opens with a line naming the task, its prompt behind it, not as the person's message. */
863
+ function scheduledRunPart(run, prompt, words) {
864
+ const detail = prompt.trim();
865
+ return {
866
+ kind: "notice",
867
+ text: words?.scheduledRun(run) ?? (run.taskId ? `✻ Started by scheduled task ${run.taskId}` : "✻ Started by a /loop wakeup"),
868
+ ...detail ? { detail } : {}
869
+ };
870
+ }
815
871
  function deliveryLine(n, words) {
816
872
  return words ? words.deliveryLine(n) : subagentDeliveryLine(n);
817
873
  }
@@ -1221,6 +1277,16 @@ function applyStreamEvent(state, ev, options = {}) {
1221
1277
  effects: []
1222
1278
  };
1223
1279
  next = timeThought(next, ev, now);
1280
+ if (ev.type === "notice") {
1281
+ const answered = answeredSkillPrompt(next.messages.at(-1), ev.content ?? "", options.words);
1282
+ if (answered) return {
1283
+ state: {
1284
+ ...next,
1285
+ messages: [...next.messages.slice(0, -1), answered]
1286
+ },
1287
+ effects: []
1288
+ };
1289
+ }
1224
1290
  const parts = applyPartEvent(next.streaming?.parts ?? [], ev, options.imageUrl, options.words);
1225
1291
  if (parts !== null && (next.streaming !== null || parts.length > 0)) {
1226
1292
  const streaming = next.streaming ?? assistantMessage();
@@ -1241,6 +1307,15 @@ function applyStreamEvent(state, ev, options = {}) {
1241
1307
  }
1242
1308
  switch (ev.type) {
1243
1309
  case "user_message": {
1310
+ if (ev.scheduled) {
1311
+ next = {
1312
+ ...finishTurn(next),
1313
+ streaming: assistantMessage([scheduledRunPart(ev.scheduled, ev.content ?? "", options.words)]),
1314
+ turnEnded: false,
1315
+ turnStartedAt: now()
1316
+ };
1317
+ break;
1318
+ }
1244
1319
  const ownEcho = !!options.echoOf || !!ev.turnId && !!options.ownTurnIds?.has(ev.turnId) || !!ev.content && !!options.ownTexts?.has(ev.content);
1245
1320
  next = finishTurn(next);
1246
1321
  next = ownEcho ? takeEcho(next, options.echoOf, ev, options.imageUrl) : {
@@ -1309,4 +1384,4 @@ function applyStreamEvent(state, ev, options = {}) {
1309
1384
  effects: controlEffects(ev)
1310
1385
  };
1311
1386
  }
1312
- export { TURN_VERBS, appendOwnMessage, appendShellRun, appendSteeredMessage, appendTurnMessage, applyStreamEvent, approvalAnswerBody, approvalToPart, bashRunning, dropMessage, historyToMessages, initialTranscript, liveSessionStatus, markQueued, pendingApprovals, pendingMessages, resolveApprovalEverywhere, resumeCursor, reviewingCount, subagentFrame, subagentSessionDetail, toolDecision, turnRunning, turnVerb, userInterruptedTool };
1387
+ export { TURN_VERBS, appendCommand, appendOwnMessage, appendShellRun, appendSteeredMessage, appendTurnMessage, applyStreamEvent, approvalAnswerBody, approvalToPart, bashRunning, dropMessage, historyToMessages, initialTranscript, liveSessionStatus, markQueued, pendingApprovals, pendingMessages, queueOwnMessage, resolveApprovalEverywhere, resumeCursor, reviewingCount, stoppedTurn, subagentFrame, subagentSessionDetail, toolDecision, turnRunning, turnVerb, userInterruptedTool };
@@ -22,6 +22,7 @@ export declare function createTranscriptReads(client: PwCodeClient, previewsByRe
22
22
  goal?: import("./api.js").components["schemas"]["GoalStatus"];
23
23
  group?: string;
24
24
  history: import("./api.js").components["schemas"]["HistoryItem"][] | null;
25
+ historyStart?: number;
25
26
  id: string;
26
27
  inputTokens?: number;
27
28
  lastError?: string;
@@ -106,8 +106,9 @@ function createTranscriptReads(client, previewsByRef) {
106
106
  tell();
107
107
  });
108
108
  const { tail, older } = JSON.parse(text);
109
+ const { historyStart: _, ...session } = tail;
109
110
  return {
110
- ...tail,
111
+ ...session,
111
112
  history: [...older ?? [], ...tail.history ?? []]
112
113
  };
113
114
  } finally {
package/dist/types.d.ts CHANGED
@@ -21,7 +21,7 @@ export interface PwCodeToolDecision {
21
21
  at: string;
22
22
  answers?: PwCodeAskAnswer[] | null;
23
23
  }
24
- /** One question's answer: the options picked, the user's own words, and their notes on a question with previews. */
24
+ /** One question's answer: the options picked, the user's own words, and their notes on a single-select question. */
25
25
  export interface PwCodeAskAnswer {
26
26
  question?: string;
27
27
  picked?: string[] | null;
@@ -45,6 +45,12 @@ export interface PwCodeHistoryItem {
45
45
  startLine?: number;
46
46
  /** On a thinking item: how long the thought took, when the session recorded it. */
47
47
  durationMs?: number;
48
+ /** On a user item a scheduled task sent rather than a person. */
49
+ scheduled?: PwCodeScheduledRun;
50
+ }
51
+ /** The scheduled task that started a turn; a self-paced loop's wakeup has no taskId. */
52
+ export interface PwCodeScheduledRun {
53
+ taskId?: string;
48
54
  }
49
55
  /** A preview of an image a message carried, base64-encoded; ref names the
50
56
  * full-size image when the daemon can serve it, and originalMime and
@@ -199,14 +205,20 @@ export interface PwCodeStreamEvent {
199
205
  turnId?: string;
200
206
  pastes?: PwCodePasteView[] | null;
201
207
  images?: PwCodeImage[] | null;
208
+ /** On a user_message a scheduled task sent rather than a person. */
209
+ scheduled?: PwCodeScheduledRun;
202
210
  /** On a usage_limit_wait that starts a wait: when the limit resets. */
203
211
  resumeAt?: string;
204
212
  /** On subagent_delivered: the line the main conversation was handed. */
205
213
  notice?: string;
214
+ /** On command_started: the request id the command was sent with. */
215
+ client?: string;
206
216
  }
207
217
  export interface PwCodeSessionDetail {
208
218
  status: PwCodeSessionStatus;
209
219
  history?: PwCodeHistoryItem[] | null;
220
+ /** Where history begins in the session's whole history, when it is only the end of it. */
221
+ historyStart?: number;
210
222
  approvals?: PwCodeApprovalRequest[] | null;
211
223
  lastSeq?: number;
212
224
  /** The turn in flight as of lastSeq, cleared with that turn's last frame. */