@intentic/sandbox-contract 1.370.0 → 1.371.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 (82) hide show
  1. package/dist/contracts/agent.contract.d.ts +9 -0
  2. package/dist/contracts/agent.contract.d.ts.map +1 -1
  3. package/dist/contracts/agents.contract.d.ts +2 -0
  4. package/dist/contracts/agents.contract.d.ts.map +1 -1
  5. package/dist/contracts/runner.contract.d.ts +29 -0
  6. package/dist/contracts/runner.contract.d.ts.map +1 -1
  7. package/dist/contracts/sessions.contract.d.ts +1 -0
  8. package/dist/contracts/sessions.contract.d.ts.map +1 -1
  9. package/dist/contracts/system.contract.d.ts +3 -0
  10. package/dist/contracts/system.contract.d.ts.map +1 -1
  11. package/dist/events/agent-events.d.ts +16 -0
  12. package/dist/events/agent-events.d.ts.map +1 -1
  13. package/dist/events/agent-events.js +2 -0
  14. package/dist/events/agent-events.js.map +1 -1
  15. package/dist/events/agent-transcript.d.ts +1 -0
  16. package/dist/events/agent-transcript.d.ts.map +1 -1
  17. package/dist/events/agent-words.d.ts +1 -0
  18. package/dist/events/agent-words.d.ts.map +1 -1
  19. package/dist/events/agent-words.js +9 -1
  20. package/dist/events/agent-words.js.map +1 -1
  21. package/dist/events/refusal-incidents.d.ts +13 -0
  22. package/dist/events/refusal-incidents.d.ts.map +1 -0
  23. package/dist/events/refusal-incidents.js +57 -0
  24. package/dist/events/refusal-incidents.js.map +1 -0
  25. package/dist/events/sandbox-notice.d.ts +27 -0
  26. package/dist/events/sandbox-notice.d.ts.map +1 -1
  27. package/dist/events/sandbox-notice.js +15 -0
  28. package/dist/events/sandbox-notice.js.map +1 -1
  29. package/dist/events/system-events.d.ts +2 -0
  30. package/dist/events/system-events.d.ts.map +1 -1
  31. package/dist/events/system-events.js +1 -0
  32. package/dist/events/system-events.js.map +1 -1
  33. package/dist/events/transcript.d.ts +6 -0
  34. package/dist/events/transcript.d.ts.map +1 -1
  35. package/dist/events/transcript.js +1 -0
  36. package/dist/events/transcript.js.map +1 -1
  37. package/dist/index.d.ts +45 -30
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/models/plan-pools.d.ts +6 -5
  40. package/dist/models/plan-pools.d.ts.map +1 -1
  41. package/dist/models/plan-pools.js +10 -6
  42. package/dist/models/plan-pools.js.map +1 -1
  43. package/dist/protocol/sse.d.ts.map +1 -1
  44. package/dist/protocol/sse.js +35 -17
  45. package/dist/protocol/sse.js.map +1 -1
  46. package/dist/schemas/providers/plan-limits.js +1 -1
  47. package/dist/schemas/providers/plan-limits.js.map +1 -1
  48. package/dist/schemas/providers/switched.d.ts +30 -0
  49. package/dist/schemas/providers/switched.d.ts.map +1 -0
  50. package/dist/schemas/providers/switched.js +45 -0
  51. package/dist/schemas/providers/switched.js.map +1 -0
  52. package/dist/schemas/workspace/name-order.d.ts +9 -0
  53. package/dist/schemas/workspace/name-order.d.ts.map +1 -0
  54. package/dist/schemas/workspace/name-order.js +4 -0
  55. package/dist/schemas/workspace/name-order.js.map +1 -0
  56. package/dist/text/notice-rows.d.ts +7 -1
  57. package/dist/text/notice-rows.d.ts.map +1 -1
  58. package/dist/text/notice-rows.js +15 -0
  59. package/dist/text/notice-rows.js.map +1 -1
  60. package/dist/text/transcript-fold.d.ts.map +1 -1
  61. package/dist/text/transcript-fold.js +4 -5
  62. package/dist/text/transcript-fold.js.map +1 -1
  63. package/package.json +5 -5
  64. package/src/events/agent-events.ts +3 -0
  65. package/src/events/agent-words.test.ts +7 -0
  66. package/src/events/agent-words.ts +14 -1
  67. package/src/events/refusal-incidents.ts +109 -0
  68. package/src/events/sandbox-notice.ts +23 -0
  69. package/src/events/system-events.ts +4 -0
  70. package/src/events/transcript.ts +1 -0
  71. package/src/models/plan-pools.test.ts +13 -0
  72. package/src/models/plan-pools.ts +30 -10
  73. package/src/protocol/sse.test.ts +45 -1
  74. package/src/protocol/sse.ts +38 -19
  75. package/src/schemas/providers/plan-limits.ts +1 -1
  76. package/src/schemas/providers/switched.test.ts +46 -0
  77. package/src/schemas/providers/switched.ts +72 -0
  78. package/src/schemas/workspace/name-order.test.ts +30 -0
  79. package/src/schemas/workspace/name-order.ts +18 -0
  80. package/src/text/notice-rows.ts +28 -3
  81. package/src/text/transcript-fold.test.ts +115 -1
  82. package/src/text/transcript-fold.ts +6 -7
@@ -561,20 +561,40 @@ const preference = (state: AccountState): number => {
561
561
  }
562
562
  };
563
563
 
564
- /** The account an unnamed turn runs on: ready by most room, then unmeasured, then at the line, then spent, blocked only when that is all there is. Ties keep the caller's order. */
565
- export const preferredAccount = <T extends { readonly state: AccountState }>(entries: readonly T[]): T | undefined =>
566
- entries.reduce<T | undefined>((best, next) => {
567
- if (best === undefined) {
568
- return next;
569
- }
570
- const tier = preference(next.state) - preference(best.state);
571
- return tier < 0 || (tier === 0 && next.state.kind === "ready" && best.state.kind === "ready" && next.state.room > best.state.room) ? next : best;
572
- }, undefined);
564
+ /** What a pick reads of an account: its verdict, and whether its organisation keeps switching it off. */
565
+ interface RankedAccount {
566
+ readonly state: AccountState;
567
+ // Refused its entitlement twice or more in the last week (the daemon's usage/entitlement-history.ts). Absent: steady.
568
+ readonly flapping?: boolean | undefined;
569
+ }
570
+
571
+ /* A FLAPPING ACCOUNT RANKS BEHIND EVERY STEADY ONE OF ITS TIER, whatever its room, for the week after it serves again.
572
+ Claude account d8561075…'s organisation switched Claude Code off at 2026-10-27 08:44, let it serve from 21:17 to
573
+ 00:39, and switched it off again at 10-28 08:48. Each time it served, the answered turn settled its refusal, its
574
+ reading showed the most room, and the pick put the next turns back on it until it was refused again. The tier still
575
+ comes first: a flapping account with proven room beats an unmeasured, spent or blocked one. */
576
+ const ranksAbove = (next: RankedAccount, best: RankedAccount): boolean => {
577
+ const tier = preference(next.state) - preference(best.state);
578
+ if (tier !== 0) {
579
+ return tier < 0;
580
+ }
581
+ if ((next.flapping === true) !== (best.flapping === true)) {
582
+ return best.flapping === true;
583
+ }
584
+ return next.state.kind === "ready" && best.state.kind === "ready" && next.state.room > best.state.room;
585
+ };
586
+
587
+ /**
588
+ * The account an unnamed turn runs on: ready by most room, then unmeasured, then at the line, then spent, blocked only
589
+ * when that is all there is; within each, a flapping account after the steady ones. Ties keep the caller's order.
590
+ */
591
+ export const preferredAccount = <T extends RankedAccount>(entries: readonly T[]): T | undefined =>
592
+ entries.reduce<T | undefined>((best, next) => (best === undefined || ranksAbove(next, best) ? next : best), undefined);
573
593
 
574
594
  /**
575
595
  * The roomiest account with proven room, or none: what a move off a refused account may land on. Ties keep the caller's
576
596
  * order. An account at the line is left out: a move there could be refused in turn, and two such accounts would hand the
577
597
  * turn back and forth.
578
598
  */
579
- export const roomiestAccount = <T extends { readonly state: AccountState }>(entries: readonly T[]): T | undefined =>
599
+ export const roomiestAccount = <T extends RankedAccount>(entries: readonly T[]): T | undefined =>
580
600
  preferredAccount(entries.filter((entry) => entry.state.kind === "ready" && entry.state.room > 0));
@@ -1,4 +1,4 @@
1
- import { parseSseText, type SseEvent, sseData, sseEvents, sseFrames, sseJson } from "./sse.js";
1
+ import { createSseParser, parseSseText, type SseEvent, sseData, sseEvents, sseFrames, sseJson } from "./sse.js";
2
2
 
3
3
  const encoder = new TextEncoder();
4
4
 
@@ -96,3 +96,47 @@ it("ends an event stream that goes silent past the idle window", async () => {
96
96
  it("sseJson reads a parsed event's data", () => {
97
97
  expect([sseJson(parseSseText(`data: [1]\n\n`)[0]!), sseJson(parseSseText(`: c\n\n`)[0]!)]).toEqual([[1], undefined]);
98
98
  });
99
+
100
+ it("preserves events and raw text at every chunk boundary, including a pending CR at EOF", () => {
101
+ for (const text of [
102
+ `\uFEFF: hello\r\nid: 7\revent: turn\ndata: first\r\ndata: second\r\n\r\ndata: last`,
103
+ `data: first\r\rdata: second\r`,
104
+ `data: first\r\n\r\n`,
105
+ `\r\r\n\n`,
106
+ ]) {
107
+ const expected = parseSseText(text);
108
+ for (let cut = 0; cut <= text.length; cut += 1) {
109
+ const events: SseEvent[] = [];
110
+ const parser = createSseParser((event) => events.push(event));
111
+ parser.feed(text.slice(0, cut));
112
+ parser.feed(``);
113
+ parser.feed(text.slice(cut));
114
+ parser.end();
115
+ expect(events).toEqual(expected);
116
+ }
117
+ expect(expected.map((event) => event.raw).join(``)).toBe(text);
118
+ }
119
+ });
120
+
121
+ it("collects a long data line from many fragments, then resets for the next event", () => {
122
+ const value = `a𐐀b`.repeat(20_000);
123
+ const text = `data: ${value}\r\n\r\ndata: next\n\n`;
124
+ const events: SseEvent[] = [];
125
+ const parser = createSseParser((event) => events.push(event));
126
+ for (let at = 0; at < text.length; at += 13) {
127
+ parser.feed(text.slice(at, at + 13));
128
+ }
129
+ parser.end();
130
+
131
+ expect(events.map((event) => event.data)).toEqual([value, `next`]);
132
+ expect(events.map((event) => event.raw).join(``)).toBe(text);
133
+ });
134
+
135
+ it("keeps every data line of a large multiline event and starts the next event cleanly", () => {
136
+ const values = Array.from({ length: 16_000 }, (_, index) => `value ${index}`);
137
+ const raw = `${values.map((value) => `data: ${value}\n`).join(``)}\n`;
138
+ const events = parseSseText(`${raw}data: next\n\n`);
139
+
140
+ expect(events.map((event) => event.data)).toEqual([values.join(`\n`), `next`]);
141
+ expect(events[0]?.raw).toBe(raw);
142
+ });
@@ -42,9 +42,10 @@ const fresh = (): Pending => ({ raw: ``, name: undefined, data: undefined, retry
42
42
  // Every block is dispatched, a comment-only one too, so a reader forwarding the stream loses nothing; a reader of
43
43
  // messages skips the ones whose `data` is undefined.
44
44
  export const createSseParser = (dispatch: (event: SseEvent) => void): SseParser => {
45
- let buffer = ``;
46
- // How far into `buffer` is known to hold no terminator, so a long line arriving in small chunks is scanned once.
47
- let scanned = 0;
45
+ // Keep an incomplete line in pieces: concatenating it on each feed makes the next regexp flatten and copy all
46
+ // earlier chunks again. Only scan new text, and join a line once its terminator arrives.
47
+ const fragments: string[] = [];
48
+ let pendingCr = false;
48
49
  let started = false;
49
50
  let lastId: string | undefined;
50
51
  let pending = fresh();
@@ -58,7 +59,8 @@ export const createSseParser = (dispatch: (event: SseEvent) => void): SseParser
58
59
  if (name === `event`) {
59
60
  pending.name = value;
60
61
  } else if (name === `data`) {
61
- pending.data = [...(pending.data ?? []), value];
62
+ pending.data ??= [];
63
+ pending.data.push(value);
62
64
  } else if (name === `id` && !value.includes(`\0`)) {
63
65
  lastId = value;
64
66
  } else if (name === `retry` && /^\d+$/.test(value)) {
@@ -79,20 +81,31 @@ export const createSseParser = (dispatch: (event: SseEvent) => void): SseParser
79
81
  field(colon < 0 ? text : text.slice(0, colon), colon < 0 ? `` : text.slice(colon + (text.charAt(colon + 1) === ` ` ? 2 : 1)));
80
82
  };
81
83
 
82
- const lines = (final: boolean): void => {
84
+ const finishLine = (text: string, terminator: string): void => {
85
+ let whole = text;
86
+ if (fragments.length > 0) {
87
+ whole = fragments.join(``) + text;
88
+ fragments.length = 0;
89
+ }
90
+ line(whole, terminator);
91
+ };
92
+
93
+ const lines = (text: string): void => {
83
94
  const terminators = /\r\n|\r|\n/gu;
84
- terminators.lastIndex = scanned;
85
95
  let start = 0;
86
- for (let found = terminators.exec(buffer); found !== null; found = terminators.exec(buffer)) {
87
- // A `\r` that ends the buffer may be the first half of a `\r\n` still in flight.
88
- if (found[0] === `\r` && found.index === buffer.length - 1 && !final) {
89
- break;
96
+ for (let found = terminators.exec(text); found !== null; found = terminators.exec(text)) {
97
+ // A trailing `\r` may be the first half of a `\r\n` still in flight.
98
+ if (found[0] === `\r` && found.index === text.length - 1) {
99
+ fragments.push(text.slice(start, found.index));
100
+ pendingCr = true;
101
+ return;
90
102
  }
91
- line(buffer.slice(start, found.index), found[0]);
103
+ finishLine(text.slice(start, found.index), found[0]);
92
104
  start = found.index + found[0].length;
93
105
  }
94
- buffer = buffer.slice(start);
95
- scanned = Math.max(0, buffer.length - 1);
106
+ if (start < text.length) {
107
+ fragments.push(text.slice(start));
108
+ }
96
109
  };
97
110
 
98
111
  return {
@@ -106,14 +119,20 @@ export const createSseParser = (dispatch: (event: SseEvent) => void): SseParser
106
119
  next = next.slice(1);
107
120
  }
108
121
  }
109
- buffer += next;
110
- lines(false);
122
+ if (pendingCr && next !== ``) {
123
+ pendingCr = false;
124
+ const lf = next.startsWith(`\n`);
125
+ finishLine(``, lf ? `\r\n` : `\r`);
126
+ next = lf ? next.slice(1) : next;
127
+ }
128
+ lines(next);
111
129
  },
112
130
  end: () => {
113
- lines(true);
114
- if (buffer !== ``) {
115
- line(buffer, ``);
116
- buffer = ``;
131
+ if (pendingCr) {
132
+ pendingCr = false;
133
+ finishLine(``, `\r`);
134
+ } else if (fragments.length > 0) {
135
+ finishLine(``, ``);
117
136
  }
118
137
  if (pending.raw !== ``) {
119
138
  emit();
@@ -528,7 +528,7 @@ export const SwitchAccountSchema = z.object({
528
528
  .boolean()
529
529
  .optional()
530
530
  .describe(
531
- "Keep the provider session across the move (the model keeps everything, and re-reads all of it once on the other account) rather than opening a fresh one seeded from the record.",
531
+ "Whether the provider session goes with the move: the model keeps everything, and re-reads all of it once on the other account. Left out, it goes, as `true`. `false` opens a fresh session seeded from the record instead.",
532
532
  ),
533
533
  handoff: HandoffModeSchema.optional().describe(
534
534
  "How the held turn continues the conversation on the new account: `carry`, `trim` or `summary` (see `limitHandoff`). Wins over `carry`. Leave it out for the held turn's own pick, else the sandbox's setting.",
@@ -0,0 +1,46 @@
1
+ import { type Switched, switchedLine, switchedNotice } from "./switched.js";
2
+
3
+ // The row a turn's switch leaves in the record names the part that changed, and says whether the session went with it.
4
+
5
+ describe("switchedLine", () => {
6
+ it("names the provider, account or loop a fresh session started on", () => {
7
+ expect(switchedLine({ segment: "provider", provider: "codex", model: "gpt-5-codex", fresh: true })).toBe(
8
+ "Switched to Codex: this message started a fresh session, with the conversation so far carried over.",
9
+ );
10
+ expect(switchedLine({ segment: "account", provider: "claude", account: "Work", fresh: true })).toBe(
11
+ "Switched to the Work account: this message started a fresh session, with the conversation so far carried over.",
12
+ );
13
+ expect(switchedLine({ segment: "loop", provider: "kimi", loop: "Claude Code", fresh: true })).toBe(
14
+ "Switched to running through Claude Code: this message started a fresh session, with the conversation so far carried over.",
15
+ );
16
+ });
17
+
18
+ it("says an account it has no name for as another of the provider's, never as the provider it was already on", () => {
19
+ expect(switchedLine({ segment: "account", provider: "claude", fresh: true })).toBe(
20
+ "Switched to another Claude account: this message started a fresh session, with the conversation so far carried over.",
21
+ );
22
+ });
23
+
24
+ it("says a model switch kept the session, or that it opened a fresh one where there was none to keep", () => {
25
+ expect(switchedLine({ segment: "model", provider: "claude", model: "claude-sonnet-5", fresh: false })).toBe(
26
+ "Switched to Claude Sonnet 5: same session, so the model re-reads the conversation once.",
27
+ );
28
+ expect(switchedLine({ segment: "model", provider: "claude", model: "claude-sonnet-5", fresh: true })).toBe(
29
+ "Switched to Claude Sonnet 5: this message started a fresh session, with the conversation so far carried over.",
30
+ );
31
+ });
32
+ });
33
+
34
+ describe("switchedNotice", () => {
35
+ it("carries every fact it has, and leaves off the ones it does not", () => {
36
+ const all: Switched = { segment: "account", provider: "claude", model: "claude-opus-5-5", account: "Work", loop: "Claude Code", fresh: true };
37
+ expect(switchedNotice(all)).toStrictEqual({
38
+ code: "switched",
39
+ params: { segment: "account", provider: "claude", model: "claude-opus-5-5", account: "Work", loop: "Claude Code", fresh: true },
40
+ });
41
+ expect(switchedNotice({ segment: "model", provider: "claude", fresh: false })).toStrictEqual({
42
+ code: "switched",
43
+ params: { segment: "model", provider: "claude", fresh: false },
44
+ });
45
+ });
46
+ });
@@ -0,0 +1,72 @@
1
+ import { z } from "zod";
2
+ import { AgentProviderSchema } from "../agent.js";
3
+ import { providerLabel } from "../../models/agent-catalog.js";
4
+ import { humanizeModelId } from "../../models/model-label.js";
5
+ import { providerSpec } from "../../models/provider-specs.js";
6
+ import type { SandboxNotice } from "../../events/sandbox-notice.js";
7
+
8
+ // WHEN A CONVERSATION CHANGES WHAT IT RUNS ON. A turn that goes out on another provider, account, loop or model than the
9
+ // conversation's turn before it says so once, as it starts, and the record keeps that as a row of its own: every
10
+ // window, device and reload then shows the same history. A window's own divider, drawn as a person picks, is only a
11
+ // preview of this, and it has been wrong (a stale window drew a switch that never happened). The daemon reads the
12
+ // switch off the conversation's record before and after the turn's `begin` (its agent/run/turn/turn-switch.ts).
13
+ //
14
+ // Provider, account and loop each retire the session, since a session lives on the runtime and account that minted it
15
+ // (the daemon's conversations/registry/routing.ts): the turn opens a fresh one, seeded from the record. A model alone
16
+ // keeps the session, and the new model reads the whole conversation once, on a cold cache. Effort, thinking and fast
17
+ // mode are no switch.
18
+
19
+ // What changed, named by the first of these that did.
20
+ export const SWITCH_SEGMENTS = ["provider", "account", "loop", "model"] as const;
21
+ export const SwitchSegmentSchema = z.enum(SWITCH_SEGMENTS);
22
+ export type SwitchSegment = z.infer<typeof SwitchSegmentSchema>;
23
+
24
+ export const SwitchedSchema = z.object({
25
+ segment: SwitchSegmentSchema.describe("What changed: the provider, else the account, else the loop, else the model."),
26
+ provider: AgentProviderSchema.describe("The provider the turn now runs on."),
27
+ model: z.string().optional().describe("The model the turn now runs on, by id. Absent where the conversation names none."),
28
+ account: z.string().optional().describe("What the account the turn now runs on is called in the sandbox. Absent where the sandbox has no name for it."),
29
+ loop: z.string().optional().describe("What the loop the turn now runs through is called (Claude Code, Codex, OpenCode)."),
30
+ fresh: z
31
+ .boolean()
32
+ .describe("Whether the turn opened a fresh session seeded from the record; false where it went on in the same session on another model."),
33
+ });
34
+ export type Switched = z.infer<typeof SwitchedSchema>;
35
+
36
+ export const switchedNotice = (event: Switched): Extract<SandboxNotice, { code: "switched" }> => {
37
+ const params: Extract<SandboxNotice, { code: "switched" }>["params"] = { segment: event.segment, provider: event.provider, fresh: event.fresh };
38
+ if (event.model !== undefined) {
39
+ params.model = event.model;
40
+ }
41
+ if (event.account !== undefined) {
42
+ params.account = event.account;
43
+ }
44
+ if (event.loop !== undefined) {
45
+ params.loop = event.loop;
46
+ }
47
+ return { code: "switched", params };
48
+ };
49
+
50
+ /** What a provider's accounts are filed under ("Claude", "ChatGPT"), which an account the sandbox has no name for is said as. */
51
+ export const accountsLabel = (provider: string): string => providerSpec(provider)?.accountLabel ?? providerLabel(provider);
52
+
53
+ // What it switched to, named by the part that changed: an account switch said as "Switched to Claude Code" would name
54
+ // the provider the chat was already on.
55
+ const switchedTo = (event: Switched): string => {
56
+ switch (event.segment) {
57
+ case "provider":
58
+ return `Switched to ${providerLabel(event.provider)}`;
59
+ case "account":
60
+ return event.account === undefined ? `Switched to another ${accountsLabel(event.provider)} account` : `Switched to the ${event.account} account`;
61
+ case "loop":
62
+ return event.loop === undefined ? "Switched to another loop" : `Switched to running through ${event.loop}`;
63
+ case "model":
64
+ return event.model === undefined ? "Switched to another model" : `Switched to ${humanizeModelId(event.model)}`;
65
+ }
66
+ };
67
+
68
+ /** The transcript's line for a turn that switched what it runs on, in the English the record keeps. */
69
+ export const switchedLine = (event: Switched): string =>
70
+ `${switchedTo(event)}: ${
71
+ event.fresh ? "this message started a fresh session, with the conversation so far carried over." : "same session, so the model re-reads the conversation once."
72
+ }`;
@@ -0,0 +1,30 @@
1
+ import { compareListed, compareNames } from "./name-order.js";
2
+
3
+ const sorted = (names: readonly string[]): string[] => names.toSorted(compareNames);
4
+
5
+ describe(`compareNames`, () => {
6
+ it(`puts numbers in counting order`, () => {
7
+ expect(sorted([`shot-10.png`, `shot-2.png`, `shot-1.png`])).toEqual([`shot-1.png`, `shot-2.png`, `shot-10.png`]);
8
+ });
9
+
10
+ it(`folds case, so a capitalised name sits among its letter`, () => {
11
+ expect(sorted([`zeta.md`, `README.md`, `alpha.md`])).toEqual([`alpha.md`, `README.md`, `zeta.md`]);
12
+ });
13
+
14
+ it(`breaks a tie between names that collate alike by code point`, () => {
15
+ expect(sorted([`readme.md`, `README.md`])).toEqual([`README.md`, `readme.md`]);
16
+ expect(compareNames(`a`, `a`)).toBe(0);
17
+ });
18
+ });
19
+
20
+ describe(`compareListed`, () => {
21
+ it(`lists folders first, each kind in natural order`, () => {
22
+ const entries = [
23
+ { name: `b10`, dir: false },
24
+ { name: `src`, dir: true },
25
+ { name: `b2`, dir: false },
26
+ { name: `assets`, dir: true },
27
+ ];
28
+ expect(entries.toSorted(compareListed).map((entry) => entry.name)).toEqual([`assets`, `src`, `b2`, `b10`]);
29
+ });
30
+ });
@@ -0,0 +1,18 @@
1
+ // The one order a folder's entries are listed in, by the daemon's walk, the desktop app's folder server, the browser's
2
+ // provisional rows and the home alike: a folder that read `file1, file10, file2` in the tree and `file1, file2, file10`
3
+ // in the home was two orders for one folder. Natural, as every desktop file manager sorts (`shot-2` before `shot-10`),
4
+ // and case-folded, so `README.md` sits among the r's.
5
+ //
6
+ // A fixed locale, not the reader's: the daemon sorts with whatever locale its process happens to start under, and the
7
+ // browser re-sorts a listing when a provisional row joins it, so two different collations would shuffle the rows the
8
+ // moment a paste landed. English collation still files an accented letter beside its base letter.
9
+ const collator = new Intl.Collator(`en`, { numeric: true, sensitivity: `base` });
10
+
11
+ /** Natural, case-insensitive name order; names that collate alike fall back to code-point order, so it is total. */
12
+ export const compareNames = (left: string, right: string): number => collator.compare(left, right) || (left < right ? -1 : left > right ? 1 : 0);
13
+
14
+ /** Folders before files, then natural name order: how every listing of a folder is laid out. */
15
+ export const compareListed = (
16
+ left: { readonly name: string; readonly dir: boolean },
17
+ right: { readonly name: string; readonly dir: boolean },
18
+ ): number => (left.dir === right.dir ? compareNames(left.name, right.name) : left.dir ? -1 : 1);
@@ -1,12 +1,18 @@
1
1
  import type { AgentEvent } from "../events/agent-events.js";
2
2
  import type { TranscriptRow } from "../events/transcript.js";
3
- import { noticeCode } from "../events/sandbox-notice.js";
3
+ import { noticeCode, type SandboxNotice } from "../events/sandbox-notice.js";
4
4
  import { contextTrimLine, contextTrimNotice } from "../schemas/context-trim.js";
5
5
  import { freshStartLine, freshStartNotice, handedOffLine, handedOffNotice } from "../schemas/providers/handoff.js";
6
+ import { switchedLine, switchedNotice } from "../schemas/providers/switched.js";
6
7
 
7
8
  // The notices that say what a turn was given to start from, each a row of its own worded from its frame's facts: what
8
- // the window left out of the message, how a held turn continued, and where a home's session started over.
9
- type StartingFrame = Extract<AgentEvent, { kind: "context_trim" | "handoff" | "fresh_start" }>;
9
+ // the window left out of the message, how a held turn continued, where a home's session started over, and what the
10
+ // turn switched to since the one before it.
11
+ type StartingFrame = Extract<AgentEvent, { kind: "context_trim" | "handoff" | "fresh_start" | "switched" }>;
12
+ const STARTING_KINDS: ReadonlySet<AgentEvent["kind"]> = new Set<StartingFrame["kind"]>(["context_trim", "handoff", "fresh_start", "switched"]);
13
+
14
+ /** Whether the frame is one of those notices. */
15
+ export const isStartingFrame = (event: AgentEvent): event is StartingFrame => STARTING_KINDS.has(event.kind);
10
16
 
11
17
  /** A starting frame's row, in the English the record keeps, with the code a reader words it from. */
12
18
  export const startingRow = (event: StartingFrame): TranscriptRow => {
@@ -17,5 +23,24 @@ export const startingRow = (event: StartingFrame): TranscriptRow => {
17
23
  return { role: "notice", text: handedOffLine(event), noticeCode: noticeCode(handedOffNotice(event)) };
18
24
  case "fresh_start":
19
25
  return { role: "notice", text: freshStartLine(event), noticeCode: noticeCode(freshStartNotice(event)) };
26
+ case "switched":
27
+ return { role: "notice", text: switchedLine(event), noticeCode: noticeCode(switchedNotice(event)) };
20
28
  }
21
29
  };
30
+
31
+ /** A move off one account onto another before a turn ran, as its notice carries it. */
32
+ export type AccountMoved = Extract<SandboxNotice, { code: "accountMoved" }>["params"];
33
+
34
+ // Each names both accounts, since "moved" alone leaves the reader to work out from where and to where.
35
+ const MOVED_LINES = {
36
+ refused: ({ from, to }) => `Ran on ${to}: the ${from} account's plan or organization does not allow it.`,
37
+ reach: ({ from, to }) => `Ran on ${to}: the people this conversation works for may not use the ${from} account.`,
38
+ cold: ({ from, to }) => `Moved from ${from} to ${to}, which has more room left: the cache had expired, so moving cost nothing.`,
39
+ } as const satisfies Readonly<Record<AccountMoved["why"], (move: AccountMoved) => string>>;
40
+
41
+ /** The row a turn moved to another account opens with, so the reader learns where it ran and why without asking. */
42
+ export const accountMovedRow = (move: AccountMoved): TranscriptRow => ({
43
+ role: "notice",
44
+ text: MOVED_LINES[move.why](move),
45
+ noticeCode: noticeCode({ code: "accountMoved", params: move }),
46
+ });
@@ -4,9 +4,11 @@ import { type TranscriptPatch, type TranscriptRow, TranscriptRowSchema, type Tra
4
4
  import { sandboxNoticeOf } from "../events/sandbox-notice.js";
5
5
  import { watchWakePrompt } from "../events/watch-wake.js";
6
6
  import { LAND_CONFLICT_OPENING } from "../events/land-conflict.js";
7
- import { RESUME_NOTES } from "../events/resume.js";
7
+ import { RESUME_NOTES,resumeDisclosure,resumeNoticeRow } from "../events/resume.js";
8
8
  import { childReportPrompt, peerMessagePrompt } from "../events/agent-words.js";
9
9
  import { applyTranscriptPatch, foldTurn, mapTool, TranscriptFold, userRow } from "./transcript-fold.js";
10
+ import { transcriptIncidents } from "../events/refusal-incidents.js";
11
+ import { accountMovedRow } from "./notice-rows.js";
10
12
 
11
13
  // Epoch ms stamped on the opening user row's sentAt.
12
14
  const SENT_AT = 1_767_225_600_000;
@@ -515,6 +517,21 @@ describe("foldTurn", () => {
515
517
  });
516
518
  });
517
519
 
520
+ // A turn that went out on another provider, account, loop or model than the one before it: a row of its own, in
521
+ // the record, so every window shows the same switch.
522
+ it("marks a turn's switch with a row of its own, coded for the reader's language", () => {
523
+ expect(foldOf("go", [{ kind: "switched", segment: "provider", provider: "codex", model: "gpt-5-codex", loop: "Codex", fresh: true }]).at(-1)).toEqual({
524
+ role: "notice",
525
+ text: "Switched to Codex: this message started a fresh session, with the conversation so far carried over.",
526
+ noticeCode: { code: "switched", params: { segment: "provider", provider: "codex", model: "gpt-5-codex", loop: "Codex", fresh: true } },
527
+ });
528
+ expect(foldOf("go", [{ kind: "switched", segment: "model", provider: "claude", model: "claude-sonnet-5", fresh: false }]).at(-1)).toEqual({
529
+ role: "notice",
530
+ text: "Switched to Claude Sonnet 5: same session, so the model re-reads the conversation once.",
531
+ noticeCode: { code: "switched", params: { segment: "model", provider: "claude", model: "claude-sonnet-5", fresh: false } },
532
+ });
533
+ });
534
+
518
535
  // A spawned child's work goes into its parent's checkout, as the parent's in-process subagents' edits do: the row
519
536
  // says so, never that it reached the owner's workspace, and says who is to bring in a clash.
520
537
  it("says a child's work went into its parent's checkout, or was held off it by a clash", () => {
@@ -1339,3 +1356,100 @@ describe("TranscriptFold with a clock", () => {
1339
1356
  ]);
1340
1357
  });
1341
1358
  });
1359
+
1360
+ // The pile one disabled organization left on 2026-10-28: the peer's message, a rebase, then a refusal, its re-send, the
1361
+ // same refusal again and the move that got it through, each a row of its own. One problem is one row: the run is found
1362
+ // over the rows as stored, the last of it drawn and every attempt behind its details.
1363
+ describe("transcriptIncidents", () => {
1364
+ const ORG_OFF = "Your organization has disabled Claude subscription access for Claude Code";
1365
+ const refusal = { kind: "error", code: "claude-not-entitled", message: ORG_OFF, held: { ran: false } } as const satisfies AgentEvent;
1366
+ // A turn refused at the door, folded as the daemon folds it, on its clock.
1367
+ const refusedAt = (at: number): TranscriptRow => {
1368
+ const fold = new TranscriptFold([], () => at);
1369
+ fold.apply(refusal);
1370
+ return fold.rows.at(-1)!;
1371
+ };
1372
+ const resent = (): TranscriptRow => {
1373
+ const disclosure = resumeDisclosure(RESUME_NOTES.door);
1374
+ if (disclosure?.kind !== "notice") {
1375
+ throw new Error("the door re-run is disclosed as a notice");
1376
+ }
1377
+ return resumeNoticeRow(disclosure);
1378
+ };
1379
+ const moved = accountMovedRow({ why: "refused", from: "Work", to: "radarsu@gmail.com", said: ORG_OFF });
1380
+ const peer: TranscriptRow = { role: "notice", text: "Message from another conversation", agentWords: { kind: "peer", from: "stout-raven-owob", sent: "look" } };
1381
+ const rebased: TranscriptRow = { role: "notice", text: "rebased", noticeCode: { code: "synced", params: { commits: 53 } } };
1382
+
1383
+ it("folds a refusal, its re-sends, the same refusal again and the move that ended it into one row", () => {
1384
+ const rows = [peer, rebased, refusedAt(1_000), resent(), refusedAt(2_000), resent(), moved];
1385
+ expect(transcriptIncidents(rows)).toEqual([
1386
+ {
1387
+ from: 2,
1388
+ to: 6,
1389
+ attempts: [
1390
+ { at: 1_000, said: ORG_OFF },
1391
+ { at: 2_000, said: ORG_OFF },
1392
+ ],
1393
+ resolved: true,
1394
+ },
1395
+ ]);
1396
+ });
1397
+
1398
+ // THE FAILURE THIS PREVENTS: the same sentence twice, a row apart, read as two problems.
1399
+ it("never leaves two identical refusals side by side as two rows", () => {
1400
+ expect(transcriptIncidents([refusedAt(1), refusedAt(2)])).toEqual([{ from: 0, to: 1, attempts: [{ at: 1, said: ORG_OFF }, { at: 2, said: ORG_OFF }], resolved: false }]);
1401
+ });
1402
+
1403
+ // A re-send still in flight is the latest word: the turn is being tried again, which the refusal under it no longer says.
1404
+ it("draws a re-send in flight as the run's last row, unresolved", () => {
1405
+ expect(transcriptIncidents([refusedAt(1), resent()])).toEqual([{ from: 0, to: 1, attempts: [{ at: 1, said: ORG_OFF }], resolved: false }]);
1406
+ });
1407
+
1408
+ it("leaves a lone refusal, a lone move and the rows around a run as they are", () => {
1409
+ expect(transcriptIncidents([peer, refusedAt(1)])).toEqual([]);
1410
+ expect(transcriptIncidents([moved])).toEqual([]);
1411
+ // The person's own words between two refusals are part of the story: neither run reaches across them.
1412
+ expect(transcriptIncidents([refusedAt(1), userRow("again", SENT_AT, []), refusedAt(2)])).toEqual([]);
1413
+ });
1414
+
1415
+ // A different refusal is a different problem, and a memory hold has a row of its own that asks its own question.
1416
+ it("starts again at a different refusal, and never folds a memory hold", () => {
1417
+ const rowOf = (event: Extract<AgentEvent, { kind: "error" }>): TranscriptRow => {
1418
+ const fold = new TranscriptFold([]);
1419
+ fold.apply(event);
1420
+ return fold.rows.at(-1)!;
1421
+ };
1422
+ const spent = rowOf({ kind: "error", code: "trial-exhausted", message: "The free trial is spent.", held: { ran: false } });
1423
+ const memory = rowOf({ kind: "error", code: "sandbox-memory-low", message: "Sandbox memory is low.", held: { ran: false } });
1424
+ const rows = [refusedAt(1), spent, spent, memory, memory];
1425
+ expect(transcriptIncidents(rows).map(({ from, to }) => [from, to])).toEqual([[1, 2]]);
1426
+ });
1427
+
1428
+ // A provider refusing an account it no longer serves answers as a failure of its own, with nothing run between two.
1429
+ it("folds the same coded failure twice running, and leaves an uncoded one be", () => {
1430
+ const failed = (code: AgentErrorCode | undefined): TranscriptRow => ({
1431
+ role: "notice",
1432
+ text: "refused",
1433
+ noticeCode: code === undefined ? { code: "failed", params: { message: "refused" } } : { code: "failed", params: { message: "refused", error: code } },
1434
+ });
1435
+ expect(transcriptIncidents([failed("account-not-entitled"), failed("account-not-entitled")])).toMatchObject([{ from: 0, to: 1 }]);
1436
+ expect(transcriptIncidents([failed(undefined), failed(undefined)])).toEqual([]);
1437
+ });
1438
+
1439
+ // A person's pick in the composer is the editor's own line, which the sandbox cannot code: the reader names it.
1440
+ it("ends a run on a row the reader says resolved it", () => {
1441
+ const switched: TranscriptRow = { role: "notice", text: "Switched to the radarsu@gmail.com account" };
1442
+ expect(transcriptIncidents([refusedAt(1), resent(), refusedAt(2), switched], (row) => row === switched)).toMatchObject([{ from: 0, to: 3, resolved: true }]);
1443
+ expect(transcriptIncidents([refusedAt(1), switched])).toEqual([]);
1444
+ });
1445
+
1446
+ // The move's own row names both accounts by name, and says it in a code the reader words in its own language.
1447
+ it("words the move with both accounts' names, and codes it", () => {
1448
+ expect(moved).toEqual({
1449
+ role: "notice",
1450
+ text: "Ran on radarsu@gmail.com: the Work account's plan or organization does not allow it.",
1451
+ noticeCode: { code: "accountMoved", params: { why: "refused", from: "Work", to: "radarsu@gmail.com", said: ORG_OFF } },
1452
+ });
1453
+ expect(sandboxNoticeOf(accountMovedRow({ why: "cold", from: "Work", to: "Home" }))).toEqual({ code: "accountMoved", params: { why: "cold", from: "Work", to: "Home" } });
1454
+ });
1455
+ });
@@ -12,7 +12,7 @@ import {
12
12
  type TranscriptTool,
13
13
  } from "../events/transcript.js";
14
14
  import { keptWarmLine, keptWarmNotice } from "../schemas/keep-warm.js";
15
- import { startingRow } from "./notice-rows.js";
15
+ import { isStartingFrame, startingRow } from "./notice-rows.js";
16
16
  import { isLandConflict } from "../events/land-conflict.js";
17
17
  import { turnedAwayCode } from "../policy/turned-away.js";
18
18
  import { errorRow, RENEWAL_WITHDRAWN, RENEWING } from "../events/failure-rows.js";
@@ -150,6 +150,11 @@ export class TranscriptFold {
150
150
  if (parent !== undefined) {
151
151
  return this.applyChild(event, parent);
152
152
  }
153
+ // What the turn started from, each a row of its own rather than a stamp on the message: what was left out is not
154
+ // part of what was sent, and the fold beside the message only ever lists notes that actually rode.
155
+ if (isStartingFrame(event)) {
156
+ return this.pushRow(startingRow(event));
157
+ }
153
158
  switch (event.kind) {
154
159
  case "delta": {
155
160
  if (event.text.length === 0) {
@@ -244,12 +249,6 @@ export class TranscriptFold {
244
249
  const notice = keptWarmNotice(event);
245
250
  return line === undefined || notice === undefined ? [] : this.pushRow({ role: "notice", text: line, noticeCode: noticeCode(notice) });
246
251
  }
247
- // Each a row of its own rather than a stamp on the message: what was left out is not part of what was sent, and
248
- // the fold beside the message only ever lists notes that actually rode.
249
- case "context_trim":
250
- case "handoff":
251
- case "fresh_start":
252
- return this.pushRow(startingRow(event));
253
252
  case "worktree":
254
253
  return this.synced(event.sync);
255
254
  case "landed":