@parallelworks/code 0.4.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 (93) hide show
  1. package/README.md +92 -24
  2. package/dist/agentSwitcher.d.ts +13 -2
  3. package/dist/agentSwitcher.js +28 -6
  4. package/dist/ago.d.ts +1 -3
  5. package/dist/ago.js +1 -3
  6. package/dist/api.d.ts +267 -5
  7. package/dist/chatStrings.d.ts +4 -0
  8. package/dist/chatStrings.js +5 -1
  9. package/dist/claudeAccounts.d.ts +20 -2
  10. package/dist/claudeAccounts.js +51 -7
  11. package/dist/claudeApi.d.ts +2 -1
  12. package/dist/claudeApi.js +49 -3
  13. package/dist/command.d.ts +7 -1
  14. package/dist/command.js +11 -2
  15. package/dist/commandsApi.d.ts +8 -3
  16. package/dist/commandsApi.js +25 -4
  17. package/dist/createPwCodeApi.d.ts +92 -58
  18. package/dist/createPwCodeApi.js +4 -2
  19. package/dist/index.d.ts +11 -9
  20. package/dist/index.js +7 -5
  21. package/dist/locales/en/agentTranscript.js +6 -2
  22. package/dist/locales/en/agents.js +50 -6
  23. package/dist/locales/en.d.ts +46 -0
  24. package/dist/locales/es/agentTranscript.js +6 -2
  25. package/dist/locales/es/agents.js +50 -6
  26. package/dist/locales/ja/agentTranscript.js +6 -2
  27. package/dist/locales/ja/agents.js +45 -6
  28. package/dist/locales/ko/agentTranscript.js +6 -2
  29. package/dist/locales/ko/agents.js +50 -6
  30. package/dist/locales/zh/agentTranscript.js +6 -2
  31. package/dist/locales/zh/agents.js +50 -6
  32. package/dist/machine.d.ts +27 -2
  33. package/dist/machine.js +23 -2
  34. package/dist/notices.d.ts +2 -0
  35. package/dist/notices.js +29 -14
  36. package/dist/pwUpdate.d.ts +52 -0
  37. package/dist/pwUpdate.js +115 -0
  38. package/dist/query.d.ts +4 -1
  39. package/dist/query.js +9 -3
  40. package/dist/session.d.ts +7 -1
  41. package/dist/session.js +6 -2
  42. package/dist/sessionActions.js +5 -2
  43. package/dist/sessionEvents.d.ts +39 -5
  44. package/dist/sessionEvents.js +213 -83
  45. package/dist/sessionGroups.d.ts +3 -3
  46. package/dist/sessionGroups.js +3 -3
  47. package/dist/sessionHeader.js +6 -2
  48. package/dist/sessionList.d.ts +13 -8
  49. package/dist/sessionList.js +20 -10
  50. package/dist/sessionScreen.d.ts +8 -3
  51. package/dist/sessionScreen.js +20 -9
  52. package/dist/sessionsApi.d.ts +27 -5
  53. package/dist/sessionsApi.js +128 -17
  54. package/dist/sessionsFeed.d.ts +22 -0
  55. package/dist/sessionsFeed.js +125 -0
  56. package/dist/startPage.d.ts +6 -3
  57. package/dist/startPage.js +34 -12
  58. package/dist/startSession.d.ts +31 -11
  59. package/dist/startSession.js +126 -44
  60. package/dist/terminalHandoffPanel.js +8 -1
  61. package/dist/todos.d.ts +42 -0
  62. package/dist/todos.js +104 -0
  63. package/dist/transcript.d.ts +27 -5
  64. package/dist/transcript.js +148 -112
  65. package/dist/transcriptRead.d.ts +57 -0
  66. package/dist/transcriptRead.js +122 -0
  67. package/dist/types.d.ts +13 -1
  68. package/dist/useComposer.d.ts +36 -15
  69. package/dist/useComposer.js +94 -31
  70. package/dist/useComposerImages.d.ts +38 -1
  71. package/dist/useComposerImages.js +62 -8
  72. package/dist/useComposerPastes.js +3 -8
  73. package/dist/useConversation.d.ts +16 -0
  74. package/dist/useConversation.js +78 -8
  75. package/dist/useMounted.d.ts +3 -0
  76. package/dist/useMounted.js +14 -0
  77. package/dist/useSubagent.d.ts +22 -5
  78. package/dist/useSubagent.js +41 -17
  79. package/dist/useTranscript.d.ts +27 -1
  80. package/dist/useTranscript.js +217 -45
  81. package/dist/wording.d.ts +6 -3
  82. package/dist/wording.js +20 -6
  83. package/locales/en/agentTranscript.json +6 -2
  84. package/locales/en/agents.json +46 -4
  85. package/locales/es/agentTranscript.json +6 -2
  86. package/locales/es/agents.json +46 -4
  87. package/locales/ja/agentTranscript.json +6 -2
  88. package/locales/ja/agents.json +46 -4
  89. package/locales/ko/agentTranscript.json +6 -2
  90. package/locales/ko/agents.json +46 -4
  91. package/locales/zh/agentTranscript.json +6 -2
  92. package/locales/zh/agents.json +46 -4
  93. package/package.json +3 -3
@@ -1,5 +1,7 @@
1
+ import { invocationName } from "./command.js";
1
2
  import { runsInBackgroundTool } from "./commandsApi.js";
2
3
  import { sessionImagePreviewUrl } from "./images.js";
4
+ import { pinnedTodos, todosFromHistory } from "./todos.js";
3
5
  import { INTERRUPTED_NOTICE, applyPartDelta, askQuestionsFromArgs, classifyPseudoUserMessage, finalizeParts, firstNonEmptyLine, hiddenTranscriptTool, interruptionNotice, parseSubagentNotice, planFromArgs, resultFailed, subagentDeliveryLine, taskCallFromArgs } from "@parallelworks/ui/ai/headless";
4
6
  import { DateTime } from "luxon";
5
7
  // src/transcript.ts
@@ -96,16 +98,6 @@ function appendShellRun(state, command, output) {
96
98
  messages: [...state.messages, assistantMessage([shellRunPart(command, output)])]
97
99
  };
98
100
  }
99
- /** The daemon pairs results to calls positionally; the wire carries no ids. */
100
- function completeOldestRunning(parts, result) {
101
- const idx = parts.findIndex((p) => p.kind === "tool_call" && p.status === "running");
102
- if (idx === -1) return parts;
103
- return parts.map((p, i) => i === idx && p.kind === "tool_call" ? {
104
- ...p,
105
- status: resultFailed(p.name, result) ? "error" : "ok",
106
- result
107
- } : p);
108
- }
109
101
  function approvalSubject(req) {
110
102
  if (req.reason === "file is outside the workspace") return "path";
111
103
  if (req.tool === "NotebookRun" || req.reason === "code in the notebook kernel") return "code";
@@ -180,34 +172,39 @@ function toolDecision(d) {
180
172
  ...d.action ? { action: d.action } : {}
181
173
  };
182
174
  }
183
- /** Ids come from the item's position, so a refetch keeps message identity and
184
- * 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. */
185
178
  function historyToMessages(history, options = {}) {
186
179
  const finalizeOpen = options.finalizeOpen ?? true;
180
+ const start = options.historyStart ?? 0;
187
181
  const { words } = options;
188
182
  const lastSettledTurnEnd = history.findLastIndex((item) => item.kind === "turn_end" && !item.turnEnd?.pendingAgents);
189
183
  const messages = [];
190
184
  let current = null;
185
+ let parts = [];
186
+ const running = [];
187
+ const cards = /* @__PURE__ */ new Map();
191
188
  const flush = (finalize) => {
192
189
  if (current) {
193
- if (finalize) current = {
190
+ messages.push({
194
191
  ...current,
195
- parts: finalizeParts(current.parts ?? [])
196
- };
197
- messages.push(current);
192
+ parts: finalize ? finalizeParts(parts) : parts
193
+ });
198
194
  current = null;
199
195
  }
200
196
  };
201
197
  const open = (index) => {
202
- if (!current) current = assistantMessage([], `h-a-${index}`);
203
- return current;
198
+ if (!current) {
199
+ current = assistantMessage([], `h-a-${index}`);
200
+ parts = [];
201
+ running.length = 0;
202
+ cards.clear();
203
+ }
204
204
  };
205
205
  const append = (part, index) => {
206
- const message = open(index);
207
- current = {
208
- ...message,
209
- parts: [...message.parts ?? [], part]
210
- };
206
+ open(index);
207
+ return parts.push(part) - 1;
211
208
  };
212
209
  const ranCommand = (command, index, answer) => {
213
210
  if (!command) {
@@ -228,24 +225,25 @@ function historyToMessages(history, options = {}) {
228
225
  });
229
226
  };
230
227
  const pending = [];
231
- const settle = (call, result) => {
232
- const message = open(-1);
233
- current = {
234
- ...message,
235
- parts: settleCall(message.parts ?? [], call, result)
236
- };
228
+ const settle = (call, result, index) => {
229
+ open(index);
230
+ const at = call.kind === "tool" ? running.shift() : call.kind === "hidden" ? void 0 : cards.get(call.id);
231
+ const part = at === void 0 ? void 0 : parts[at];
232
+ if (at !== void 0 && part) parts[at] = settledPart(part, result);
237
233
  };
238
234
  const dropWaitingAsks = () => {
239
235
  const waiting = new Set(pending.flatMap((call) => call.kind === "ask" ? [call.id] : []));
240
- if (current && waiting.size > 0) current = {
241
- ...current,
242
- parts: (current.parts ?? []).filter((p) => !(p.kind === "approval" && waiting.has(p.id)))
243
- };
236
+ if (current && waiting.size > 0) parts = parts.filter((p) => !(p.kind === "approval" && waiting.has(p.id)));
244
237
  };
245
- history.forEach((item, index) => {
238
+ history.forEach((item, at) => {
239
+ const index = start + at;
246
240
  switch (item.kind) {
247
241
  case "user": {
248
242
  flush(true);
243
+ if (item.scheduled) {
244
+ append(scheduledRunPart(item.scheduled, item.text ?? "", words), index);
245
+ return;
246
+ }
249
247
  const shell = parseShellRecord(item.text ?? "");
250
248
  if (shell) {
251
249
  append(shellRunPart(shell.command, shell.output), index);
@@ -278,13 +276,13 @@ function historyToMessages(history, options = {}) {
278
276
  const id = `h-${index}`;
279
277
  if (name === "Task") {
280
278
  const { description, agentType } = taskCallFromArgs(args);
281
- append({
279
+ cards.set(id, append({
282
280
  kind: "subagent",
283
281
  id,
284
282
  status: "running",
285
283
  description,
286
284
  ...agentType ? { agentType } : {}
287
- }, index);
285
+ }, index));
288
286
  pending.push({
289
287
  kind: "subagent",
290
288
  id
@@ -293,7 +291,7 @@ function historyToMessages(history, options = {}) {
293
291
  }
294
292
  if (name === "AskUserQuestion") {
295
293
  const [card, call] = askCard(id, args, item.decision);
296
- append(card, index);
294
+ cards.set(id, append(card, index));
297
295
  pending.push(call);
298
296
  return;
299
297
  }
@@ -305,25 +303,12 @@ function historyToMessages(history, options = {}) {
305
303
  pending.push({ kind: "hidden" });
306
304
  return;
307
305
  }
308
- const todos = name === "TodoWrite" ? todosFromArgs(args) : null;
309
- if (todos?.length) {
310
- const message = open(index);
311
- current = {
312
- ...message,
313
- parts: applyPartDelta(message.parts ?? [], {
314
- type: "todo_snapshot",
315
- todos
316
- })
317
- };
318
- pending.push({ kind: "hidden" });
319
- return;
320
- }
321
306
  if (hiddenTranscriptTool(name)) {
322
307
  pending.push({ kind: "hidden" });
323
308
  return;
324
309
  }
325
310
  const decision = item.decision && toolDecision(item.decision);
326
- append({
311
+ running.push(append({
327
312
  kind: "tool_call",
328
313
  id: item.callId || id,
329
314
  name,
@@ -332,13 +317,13 @@ function historyToMessages(history, options = {}) {
332
317
  ...item.startLine ? { startLine: item.startLine } : {},
333
318
  ...planFileEdit(name, args) ? { foldDiff: true } : {},
334
319
  ...decision ? { decision } : {}
335
- }, index);
320
+ }, index));
336
321
  pending.push({ kind: "tool" });
337
322
  return;
338
323
  }
339
324
  case "tool_result": {
340
325
  const call = pending.shift();
341
- if (call) settle(call, item.text ?? "");
326
+ if (call) settle(call, item.text ?? "", index);
342
327
  const images = imageAttachments(item.images, options.imageUrl);
343
328
  if (images.length) append({
344
329
  kind: "image",
@@ -356,6 +341,11 @@ function historyToMessages(history, options = {}) {
356
341
  }
357
342
  case "notice": {
358
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
+ }
359
349
  const delivery = readDelivery(text);
360
350
  if (delivery?.silent) return;
361
351
  const detail = delivery ? deliveryDetail(delivery) : void 0;
@@ -406,7 +396,7 @@ function historyToMessages(history, options = {}) {
406
396
  case "turn_end": {
407
397
  const te = item.turnEnd;
408
398
  if (te && words) {
409
- const waiting = index > lastSettledTurnEnd && (te.pendingAgents ?? 0) > 0;
399
+ const waiting = at > lastSettledTurnEnd && (te.pendingAgents ?? 0) > 0;
410
400
  append({
411
401
  kind: "notice",
412
402
  text: words.turnEnd(te, turnVerb(te.endedAt), waiting)
@@ -449,27 +439,30 @@ function askCard(id, args, d) {
449
439
  }, { kind: "hidden" }];
450
440
  }
451
441
  var BACKGROUND_STARTED_PREFIX = "Started background subagent";
452
- function settleCall(parts, call, result) {
453
- switch (call.kind) {
454
- case "tool": return completeOldestRunning(parts, result);
455
- case "subagent": return parts.map((p) => {
456
- if (p.kind !== "subagent" || p.id !== call.id) return p;
442
+ /** The block a call drew, as its result leaves it. */
443
+ function settledPart(part, result) {
444
+ switch (part.kind) {
445
+ case "tool_call": return {
446
+ ...part,
447
+ status: resultFailed(part.name, result) ? "error" : "ok",
448
+ result
449
+ };
450
+ case "subagent":
457
451
  if (result.startsWith(BACKGROUND_STARTED_PREFIX)) return {
458
- ...p,
452
+ ...part,
459
453
  background: true
460
454
  };
461
455
  return {
462
- ...p,
456
+ ...part,
463
457
  status: resultFailed("Task", result) ? "failed" : "done",
464
458
  summary: firstNonEmptyLine(result, 60)
465
459
  };
466
- });
467
- case "ask": return parts.map((p) => p.kind === "approval" && p.id === call.id ? {
468
- ...p,
460
+ case "approval": return {
461
+ ...part,
469
462
  resolved: true,
470
463
  answer: result.trim()
471
- } : p);
472
- default: return parts;
464
+ };
465
+ default: return part;
473
466
  }
474
467
  }
475
468
  /** A session with no history resumes from the start: the daemon stamps a seq
@@ -482,6 +475,7 @@ function initialTranscript(detail, options = {}) {
482
475
  const running = detail.status === "awaiting_approval" || !!detail.turnId;
483
476
  const messages = historyToMessages(detail.history ?? [], {
484
477
  ...options,
478
+ historyStart: detail.historyStart,
485
479
  finalizeOpen: !running
486
480
  });
487
481
  let streaming = null;
@@ -514,7 +508,8 @@ function initialTranscript(detail, options = {}) {
514
508
  turnStartedAt: running ? detail.turnStartedAt ?? null : null,
515
509
  waitingForUsageLimit: running && !!detail.waitingForUsageLimit,
516
510
  usageLimitResumeAt: running && detail.waitingForUsageLimit ? detail.usageLimitResumeAt ?? null : null,
517
- seededSeq: detail.lastSeq ?? 0
511
+ seededSeq: detail.lastSeq ?? 0,
512
+ todos: todosFromHistory(detail.history ?? [])
518
513
  };
519
514
  }
520
515
  /** A subagent's detail as the session detail its transcript seeds from. Its run
@@ -591,11 +586,8 @@ function resolveApprovalEverywhere(state, id) {
591
586
  * short, so the page must not close the turn either: its open tool calls
592
587
  * would read as interrupted while they are still running. */
593
588
  function appendOwnMessage(state, text, id, pastes, previews) {
589
+ if (turnRunning(state)) return queueOwnMessage(state, text, id, pastes, previews);
594
590
  const message = userMessage(text, void 0, id, pastes, previews);
595
- if (turnRunning(state)) return {
596
- ...state,
597
- queued: [...state.queued, message]
598
- };
599
591
  return {
600
592
  ...state,
601
593
  messages: [...state.messages, message],
@@ -605,6 +597,14 @@ function appendOwnMessage(state, text, id, pastes, previews) {
605
597
  opening: message.id
606
598
  };
607
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
+ }
608
608
  /** A subagent runs one turn at a time, so a message sent to it starts its next:
609
609
  * a turn the transcript still shows running has ended. */
610
610
  function appendTurnMessage(state, text, id, pastes, previews) {
@@ -631,6 +631,13 @@ function appendSteeredMessage(state, text, id, pastes, previews) {
631
631
  steered: [...state.steered, userMessage(text, void 0, id, pastes, previews)]
632
632
  };
633
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
+ }
634
641
  /** The daemon queued a message this page had shown as sent, because the turn
635
642
  * ahead of it had not reached the page yet. */
636
643
  function markQueued(state, id) {
@@ -692,31 +699,6 @@ function interruptRunningCalls(parts) {
692
699
  isError: false
693
700
  }) : settled, parts);
694
701
  }
695
- var TODO_STATUSES = /* @__PURE__ */ new Set([
696
- "pending",
697
- "in_progress",
698
- "completed"
699
- ]);
700
- /** TodoWrite's whole list, which its arguments carry; null when they hold none. */
701
- function todosFromArgs(argsJSON) {
702
- let args;
703
- try {
704
- args = JSON.parse(argsJSON);
705
- } catch {
706
- return null;
707
- }
708
- const raw = args && typeof args === "object" ? args["todos"] : void 0;
709
- if (!Array.isArray(raw)) return null;
710
- return raw.flatMap((t) => {
711
- const { content, status, activeForm } = t && typeof t === "object" ? t : {};
712
- if (typeof content !== "string" || typeof status !== "string" || !TODO_STATUSES.has(status)) return [];
713
- return [{
714
- content,
715
- status,
716
- ...typeof activeForm === "string" ? { activeForm } : {}
717
- }];
718
- });
719
- }
720
702
  function applyPartEvent(parts, ev, imageUrl, words) {
721
703
  switch (ev.type) {
722
704
  case "chunk": return applyPartDelta(parts, {
@@ -729,11 +711,6 @@ function applyPartEvent(parts, ev, imageUrl, words) {
729
711
  });
730
712
  case "retract": return applyPartDelta(parts, { type: "retract" });
731
713
  case "tool_start": {
732
- const todos = ev.name === "TodoWrite" ? todosFromArgs(ev.args ?? "") : null;
733
- if (todos?.length) return applyPartDelta(parts, {
734
- type: "todo_snapshot",
735
- todos
736
- });
737
714
  if (hiddenTranscriptTool(ev.name ?? "")) return parts;
738
715
  const id = ev.callId || String(ev.seq);
739
716
  const started = applyPartDelta(parts, {
@@ -775,14 +752,21 @@ function applyPartEvent(parts, ev, imageUrl, words) {
775
752
  images
776
753
  }] : parts;
777
754
  }
778
- case "subagent_start": return applyPartDelta(parts, {
779
- type: "subagent_start",
780
- id: ev.id ?? String(ev.seq),
781
- ...ev.agentType !== void 0 ? { agentType: ev.agentType } : {},
782
- ...ev.color !== void 0 ? { color: ev.color } : {},
783
- ...ev.background !== void 0 ? { background: ev.background } : {},
784
- ...ev.name !== void 0 ? { description: ev.name } : {}
785
- });
755
+ case "subagent_start": {
756
+ const id = ev.id ?? String(ev.seq);
757
+ const started = applyPartDelta(parts, {
758
+ type: "subagent_start",
759
+ id,
760
+ ...ev.agentType !== void 0 ? { agentType: ev.agentType } : {},
761
+ ...ev.color !== void 0 ? { color: ev.color } : {},
762
+ ...ev.background !== void 0 ? { background: ev.background } : {},
763
+ ...ev.name !== void 0 ? { description: ev.name } : {}
764
+ });
765
+ return ev.turnId ? started : started.map((p) => p.kind === "subagent" && p.id === id ? {
766
+ ...p,
767
+ detached: true
768
+ } : p);
769
+ }
786
770
  case "subagent_action": return applyPartDelta(parts, {
787
771
  type: "subagent_action",
788
772
  id: ev.id ?? "",
@@ -854,6 +838,36 @@ var TURN_VERBS = [
854
838
  "sauteed",
855
839
  "worked"
856
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
+ }
857
871
  function deliveryLine(n, words) {
858
872
  return words ? words.deliveryLine(n) : subagentDeliveryLine(n);
859
873
  }
@@ -1180,7 +1194,8 @@ function applyStreamEvent(state, ev, options = {}) {
1180
1194
  turnStartedAt: null,
1181
1195
  waitingForUsageLimit: false,
1182
1196
  usageLimitResumeAt: null,
1183
- cursor: ev.seq
1197
+ cursor: ev.seq,
1198
+ todos: []
1184
1199
  },
1185
1200
  effects: []
1186
1201
  };
@@ -1217,10 +1232,12 @@ function applyStreamEvent(state, ev, options = {}) {
1217
1232
  },
1218
1233
  effects: []
1219
1234
  };
1235
+ const todos = ev.type === "tool_start" && ev.name === "TodoWrite" ? pinnedTodos(ev.args ?? "") : null;
1220
1236
  let next = {
1221
1237
  ...state,
1222
1238
  cursor: ev.seq,
1223
- ...ev.turnEnd ? { turnEndSeq: ev.seq } : {}
1239
+ ...ev.turnEnd ? { turnEndSeq: ev.seq } : {},
1240
+ ...todos ? { todos } : {}
1224
1241
  };
1225
1242
  if (next.notes.length > 0 && speaks(ev)) next = placeNotes(next);
1226
1243
  if (ev.type === "notice" && DISCARDED_QUEUE.test(ev.content ?? "")) next = {
@@ -1260,6 +1277,16 @@ function applyStreamEvent(state, ev, options = {}) {
1260
1277
  effects: []
1261
1278
  };
1262
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
+ }
1263
1290
  const parts = applyPartEvent(next.streaming?.parts ?? [], ev, options.imageUrl, options.words);
1264
1291
  if (parts !== null && (next.streaming !== null || parts.length > 0)) {
1265
1292
  const streaming = next.streaming ?? assistantMessage();
@@ -1280,6 +1307,15 @@ function applyStreamEvent(state, ev, options = {}) {
1280
1307
  }
1281
1308
  switch (ev.type) {
1282
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
+ }
1283
1319
  const ownEcho = !!options.echoOf || !!ev.turnId && !!options.ownTurnIds?.has(ev.turnId) || !!ev.content && !!options.ownTexts?.has(ev.content);
1284
1320
  next = finishTurn(next);
1285
1321
  next = ownEcho ? takeEcho(next, options.echoOf, ev, options.imageUrl) : {
@@ -1348,4 +1384,4 @@ function applyStreamEvent(state, ev, options = {}) {
1348
1384
  effects: controlEffects(ev)
1349
1385
  };
1350
1386
  }
1351
- export { TURN_VERBS, appendOwnMessage, appendShellRun, appendSteeredMessage, appendTurnMessage, applyStreamEvent, approvalAnswerBody, approvalToPart, bashRunning, dropMessage, historyToMessages, initialTranscript, liveSessionStatus, markQueued, pendingApprovals, pendingMessages, resolveApprovalEverywhere, resumeCursor, reviewingCount, subagentFrame, subagentSessionDetail, todosFromArgs, 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 };
@@ -0,0 +1,57 @@
1
+ import type { PwCodeClient, Schemas } from './apiClient.js';
2
+ type SessionDetail = Schemas['AgentSessionDetail'];
3
+ /** Reads a transcript answered tail first and resolves to its text. `onTail` is
4
+ * handed the tail once it has arrived, if the rest is still on its way a
5
+ * moment later. */
6
+ export declare function readTailFirst(stream: ReadableStream<Uint8Array>, onTail: (tail: SessionDetail) => void): Promise<string>;
7
+ /** Reads sessions' transcripts so the end of one can be shown while the rest
8
+ * of it arrives, which over a slow connection is most of the wait. */
9
+ export declare function createTranscriptReads(client: PwCodeClient, previewsByRef: boolean): {
10
+ /** The end of the transcript being read under `name`, until the read ends. */
11
+ tail: (name: string) => {
12
+ addDirs?: import("./api.js").components["schemas"]["AddedDirectory"][] | null;
13
+ allocation?: string;
14
+ allowedDirs?: import("./api.js").components["schemas"]["AllowedDirectory"][] | null;
15
+ approvals?: import("./api.js").components["schemas"]["ApprovalRequest"][] | null;
16
+ archivedAt?: string;
17
+ autoName?: string;
18
+ branch?: string;
19
+ claudeAccount?: string;
20
+ createdAt: string;
21
+ effort?: string;
22
+ goal?: import("./api.js").components["schemas"]["GoalStatus"];
23
+ group?: string;
24
+ history: import("./api.js").components["schemas"]["HistoryItem"][] | null;
25
+ historyStart?: number;
26
+ id: string;
27
+ inputTokens?: number;
28
+ lastError?: string;
29
+ lastSeq?: number;
30
+ liveHost?: string;
31
+ machineId: string;
32
+ messages: number;
33
+ model: string;
34
+ name?: string;
35
+ outputTokens?: number;
36
+ permissionMode?: string;
37
+ pinnedAt?: string;
38
+ preview: string;
39
+ pullRequestStates?: {
40
+ [key: string]: string;
41
+ };
42
+ pullRequests?: string[] | null;
43
+ remoteControl?: boolean;
44
+ status: "idle" | "running" | "awaiting_approval" | "live_elsewhere";
45
+ turnId?: string;
46
+ turnStartedAt?: string;
47
+ updatedAt: string;
48
+ usageLimitResumeAt?: string;
49
+ waitingForUsageLimit?: boolean;
50
+ workspace: string;
51
+ workspaceUntrusted?: boolean;
52
+ } | undefined;
53
+ subscribe: (listener: () => void) => () => void;
54
+ /** The session, whole. `name` is what its end is kept under meanwhile. */
55
+ read(machine: string, id: string, name: string, signal: AbortSignal | undefined): Promise<SessionDetail>;
56
+ };
57
+ export {};
@@ -0,0 +1,122 @@
1
+ import { PREVIEWS_BY_REF } from "./images.js";
2
+ // src/transcriptRead.ts
3
+ /** About how many history items the end of a transcript holds. */
4
+ var TAIL_ITEMS = 200;
5
+ /** How long the rest of a transcript may take before its end is shown without
6
+ * it: one that arrives whole is drawn once. */
7
+ var TAIL_GRACE_MS = 80;
8
+ var OLDER = ",\"older\":[";
9
+ function tailBefore(text, at) {
10
+ try {
11
+ return JSON.parse(`${text.slice(0, at)}}`).tail;
12
+ } catch {
13
+ return;
14
+ }
15
+ }
16
+ /** Reads a transcript answered tail first and resolves to its text. `onTail` is
17
+ * handed the tail once it has arrived, if the rest is still on its way a
18
+ * moment later. */
19
+ async function readTailFirst(stream, onTail) {
20
+ const reader = stream.getReader();
21
+ const decoder = new TextDecoder();
22
+ let text = "";
23
+ let from = 0;
24
+ let found = false;
25
+ let grace;
26
+ try {
27
+ for (;;) {
28
+ const { done, value } = await reader.read();
29
+ if (done) break;
30
+ text += decoder.decode(value, { stream: true });
31
+ while (!found) {
32
+ const at = text.indexOf(OLDER, from);
33
+ if (at < 0) {
34
+ from = Math.max(0, text.length - 10);
35
+ break;
36
+ }
37
+ const tail = tailBefore(text, at);
38
+ if (tail) {
39
+ found = true;
40
+ grace = setTimeout(() => onTail(tail), TAIL_GRACE_MS);
41
+ } else from = at + 1;
42
+ }
43
+ }
44
+ } finally {
45
+ clearTimeout(grace);
46
+ }
47
+ return text + decoder.decode();
48
+ }
49
+ /** Reads sessions' transcripts so the end of one can be shown while the rest
50
+ * of it arrives, which over a slow connection is most of the wait. */
51
+ function createTranscriptReads(client, previewsByRef) {
52
+ const tails = /* @__PURE__ */ new Map();
53
+ const listeners = /* @__PURE__ */ new Set();
54
+ const tell = () => {
55
+ for (const listener of listeners) listener();
56
+ };
57
+ const query = previewsByRef ? { previews: PREVIEWS_BY_REF } : {};
58
+ const readWhole = async (machine, id, aborts) => {
59
+ const { data, error } = await client.GET("/api/code/machines/{machine}/sessions/{id}", {
60
+ params: {
61
+ path: {
62
+ machine,
63
+ id
64
+ },
65
+ ...previewsByRef ? { query } : {}
66
+ },
67
+ ...aborts
68
+ });
69
+ if (error !== void 0) throw error;
70
+ return data;
71
+ };
72
+ return {
73
+ /** The end of the transcript being read under `name`, until the read ends. */
74
+ tail: (name) => tails.get(name),
75
+ subscribe: (listener) => {
76
+ listeners.add(listener);
77
+ return () => {
78
+ listeners.delete(listener);
79
+ };
80
+ },
81
+ /** The session, whole. `name` is what its end is kept under meanwhile. */
82
+ async read(machine, id, name, signal) {
83
+ const aborts = signal ? { signal } : {};
84
+ const { data, error, response } = await client.GET("/api/code/machines/{machine}/sessions/{id}/transcript", {
85
+ params: {
86
+ path: {
87
+ machine,
88
+ id
89
+ },
90
+ query: {
91
+ ...query,
92
+ tail: TAIL_ITEMS
93
+ }
94
+ },
95
+ parseAs: "stream",
96
+ ...aborts
97
+ });
98
+ if (error !== void 0) {
99
+ if (response.status !== 404 && response.status !== 405) throw error;
100
+ return readWhole(machine, id, aborts);
101
+ }
102
+ if (!data) return readWhole(machine, id, aborts);
103
+ try {
104
+ const text = await readTailFirst(data, (tail) => {
105
+ tails.set(name, tail);
106
+ tell();
107
+ });
108
+ const { tail, older } = JSON.parse(text);
109
+ const { historyStart: _, ...session } = tail;
110
+ return {
111
+ ...session,
112
+ history: [...older ?? [], ...tail.history ?? []]
113
+ };
114
+ } finally {
115
+ setTimeout(() => {
116
+ if (tails.delete(name)) tell();
117
+ }, 0);
118
+ }
119
+ }
120
+ };
121
+ }
122
+ export { createTranscriptReads, readTailFirst };