@intentic/sandbox-contract 1.403.1 → 1.405.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 (74) hide show
  1. package/dist/contracts/agent.contract.d.ts +8 -0
  2. package/dist/contracts/agent.contract.d.ts.map +1 -1
  3. package/dist/contracts/agents.contract.d.ts +40 -0
  4. package/dist/contracts/agents.contract.d.ts.map +1 -1
  5. package/dist/contracts/runner.contract.d.ts +246 -246
  6. package/dist/contracts/seal.contract.d.ts +10 -0
  7. package/dist/contracts/seal.contract.d.ts.map +1 -1
  8. package/dist/contracts/system.contract.d.ts +30 -18
  9. package/dist/contracts/system.contract.d.ts.map +1 -1
  10. package/dist/contracts/translator.contract.d.ts +16 -0
  11. package/dist/contracts/translator.contract.d.ts.map +1 -1
  12. package/dist/events/system-events.d.ts +8 -0
  13. package/dist/events/system-events.d.ts.map +1 -1
  14. package/dist/models/plan-pools.d.ts +5 -34
  15. package/dist/models/plan-pools.d.ts.map +1 -1
  16. package/dist/models/plan-pools.js +4 -95
  17. package/dist/models/plan-pools.js.map +1 -1
  18. package/dist/models/verdict/pool-gates.d.ts +17 -0
  19. package/dist/models/verdict/pool-gates.d.ts.map +1 -0
  20. package/dist/models/verdict/pool-gates.js +41 -0
  21. package/dist/models/verdict/pool-gates.js.map +1 -0
  22. package/dist/models/verdict/refusal-verdict.d.ts +21 -0
  23. package/dist/models/verdict/refusal-verdict.d.ts.map +1 -0
  24. package/dist/models/verdict/refusal-verdict.js +68 -0
  25. package/dist/models/verdict/refusal-verdict.js.map +1 -0
  26. package/dist/protocol/raw/raw-json-routes.d.ts +196 -0
  27. package/dist/protocol/raw/raw-json-routes.d.ts.map +1 -1
  28. package/dist/protocol/raw/raw-json-routes.js +5 -0
  29. package/dist/protocol/raw/raw-json-routes.js.map +1 -1
  30. package/dist/protocol/raw/raw-routes.d.ts +31 -0
  31. package/dist/protocol/raw/raw-routes.d.ts.map +1 -1
  32. package/dist/protocol/raw/raw-routes.js +7 -0
  33. package/dist/protocol/raw/raw-routes.js.map +1 -1
  34. package/dist/schemas/agent-next.d.ts +1 -0
  35. package/dist/schemas/agent-next.d.ts.map +1 -1
  36. package/dist/schemas/agent-next.js +4 -0
  37. package/dist/schemas/agent-next.js.map +1 -1
  38. package/dist/schemas/agent.d.ts +126 -0
  39. package/dist/schemas/agent.d.ts.map +1 -1
  40. package/dist/schemas/agent.js +15 -4
  41. package/dist/schemas/agent.js.map +1 -1
  42. package/dist/schemas/agents-list.d.ts +4 -0
  43. package/dist/schemas/agents-list.d.ts.map +1 -1
  44. package/dist/schemas/agents.d.ts +6 -0
  45. package/dist/schemas/agents.d.ts.map +1 -1
  46. package/dist/schemas/diagnostics.d.ts +248 -0
  47. package/dist/schemas/diagnostics.d.ts.map +1 -0
  48. package/dist/schemas/diagnostics.js +114 -0
  49. package/dist/schemas/diagnostics.js.map +1 -0
  50. package/dist/schemas/links.d.ts +6 -0
  51. package/dist/schemas/links.d.ts.map +1 -1
  52. package/dist/schemas/links.js +6 -0
  53. package/dist/schemas/links.js.map +1 -1
  54. package/dist/schemas/providers/plan-limits.d.ts +22 -1
  55. package/dist/schemas/providers/plan-limits.d.ts.map +1 -1
  56. package/dist/schemas/providers/plan-limits.js +10 -1
  57. package/dist/schemas/providers/plan-limits.js.map +1 -1
  58. package/dist/schemas/providers/refusals.d.ts +5 -0
  59. package/dist/schemas/providers/refusals.d.ts.map +1 -1
  60. package/dist/schemas/providers/refusals.js +4 -0
  61. package/dist/schemas/providers/refusals.js.map +1 -1
  62. package/package.json +5 -5
  63. package/src/models/plan-pools.test.ts +96 -5
  64. package/src/models/plan-pools.ts +22 -212
  65. package/src/models/verdict/pool-gates.ts +94 -0
  66. package/src/models/verdict/refusal-verdict.ts +148 -0
  67. package/src/protocol/raw/raw-json-routes.ts +7 -0
  68. package/src/protocol/raw/raw-routes.ts +17 -0
  69. package/src/schemas/agent-next.ts +6 -0
  70. package/src/schemas/agent.ts +50 -29
  71. package/src/schemas/diagnostics.ts +166 -0
  72. package/src/schemas/links.ts +9 -0
  73. package/src/schemas/providers/plan-limits.ts +16 -1
  74. package/src/schemas/providers/refusals.ts +12 -3
@@ -0,0 +1,148 @@
1
+ import type { AccountUsage, ModelCooldown, ProviderRefusal } from "../../schemas/providers/plan-limits.js";
2
+ import { bindingWindow, SPENT_UTILIZATION } from "./pool-gates.js";
3
+
4
+ // Which refusals on file still speak, and over which account: the half of the serviceability rule plan-pools.ts runs
5
+ // before it lays them on the readings (judgedReading). Every account is judged on its own facts, never another's.
6
+
7
+ /** Everything the serviceability rule reads of one account, as the account rows already carry it. */
8
+ export interface ServiceFacts {
9
+ // The daemon's key: a native account's id, a routed credential's auth-file name.
10
+ readonly account: string;
11
+ readonly needsReauth?: boolean | undefined;
12
+ // Why the sign-in needs renewing, where the provider said.
13
+ readonly detail?: string | undefined;
14
+ readonly seatRefusal?: string | undefined;
15
+ readonly cooling?: { readonly until?: number | undefined; readonly reason?: string | undefined; readonly verify?: string | undefined } | undefined;
16
+ // A routed account's per-model benches as the translator holds them (TranslatorAccount.cooldowns).
17
+ readonly cooldowns?: readonly ModelCooldown[] | undefined;
18
+ readonly usage?: AccountUsage | undefined;
19
+ // How the account is named to a person (its label, a routed credential's address); a surface that quotes a figure
20
+ // says whose it is.
21
+ readonly label?: string | undefined;
22
+ }
23
+
24
+ /** Every refusal on file for one provider: what its accounts are judged against, each standing until something answers it. */
25
+ export type RefusalsOnFile = readonly ProviderRefusal[];
26
+
27
+ // A spent allowance is over once a reading with room in the pool its model spends lands after it; a refused credential
28
+ // once any reading does (the token worked). Nothing a reading says answers an entitlement refusal: a seatless account
29
+ // authenticates and reads fine. Nor does the refused account's own reading answer an allowance it does not measure
30
+ // (`unmetered`: an admin's credit). `measured` says whether this reading can speak to the allowance at all: false for
31
+ // that account's own, true for another account's where nothing says which one refused (verdictOn).
32
+ // The refused model's pool, not the account's fullest: 2026-11-08, a Google account with its Claude pool at 0% answered
33
+ // a Gemini refusal, and one with Claude at 100% could never answer a Gemini one with Gemini's pool open.
34
+ const answers = (refusal: ProviderRefusal, facts: ServiceFacts, measured: boolean = refusal.unmetered !== true): boolean => {
35
+ const measuredAt = facts.usage?.measuredAt;
36
+ if (refusal.kind === "entitlement" || !measured || measuredAt === undefined || measuredAt <= refusal.at) {
37
+ return false;
38
+ }
39
+ if (refusal.kind === "auth") {
40
+ return facts.needsReauth !== true;
41
+ }
42
+ const binding = bindingWindow(facts.usage, refusal.model === undefined ? undefined : { id: refusal.model });
43
+ return binding !== undefined && binding.utilization < SPENT_UTILIZATION;
44
+ };
45
+
46
+ /**
47
+ * When the pool a spent allowance that named no instant was refused in reopens, in epoch seconds: the soonest reset of
48
+ * the binding pool for the model it named (the pool judgedReading pins full) on the accounts it may have refused, its own
49
+ * where it named one, any where it named none, as any account's room answers a nameless one. The daemon's ledger stamps
50
+ * it on the refusal as it files it (`poolResetsAt`), while the readings still show that pool open: once it reopens the
51
+ * reading lapses it to an empty pool and a different one binds, so it cannot be read back off the reading later.
52
+ * Undefined for a refusal that named its instant, one no reading measures (`unmetered`), a person's mark (lifted by a
53
+ * person or a turn, not a window), and where no reading publishes a reset still ahead of the refusal.
54
+ */
55
+ export const refusedPoolReset = (refusal: ProviderRefusal, accounts: readonly ServiceFacts[]): number | undefined => {
56
+ if (refusal.kind !== "limit" || refusal.resetsAt !== undefined || refusal.unmetered === true || refusal.byHand === true) {
57
+ return undefined;
58
+ }
59
+ const model = refusal.model === undefined ? undefined : { id: refusal.model };
60
+ const resets = accounts
61
+ .filter((facts) => refusal.account === undefined || facts.account === refusal.account)
62
+ .flatMap((facts) => {
63
+ const reset = bindingWindow(facts.usage, model)?.resetsAt;
64
+ return reset !== undefined && reset * 1000 > refusal.at ? [reset] : [];
65
+ });
66
+ return resets.length === 0 ? undefined : Math.min(...resets);
67
+ };
68
+
69
+ /*
70
+ * How one refusal stands over ONE account, judged from that account's facts alone: nothing read of another account
71
+ * answers it there (2026-11-08: one Google account reading room answered every nameless refusal for all 31, within
72
+ * seconds of each, so a refused model read 0% and then 100% again while every turn on it was refused). Over once the
73
+ * instant it named has passed (or, where it named none, the reset of the pool it was refused in, stamped as it was filed:
74
+ * refusedPoolReset, unless this account was read since and a reading outranks a stamp: 2026-10-21). Where it is known to
75
+ * be this account's (it named it, or the provider has no other), the provider's own instant outranks a usage endpoint
76
+ * that kept showing room while it refused, so it stands until then; else this account's reading of the refused pool
77
+ * since it answers it. A nameless one is one account saying no and nothing saying which, so on each account it is only
78
+ * that account's own reading that answers it, whatever kind of allowance or instant it named: held to its instant, one
79
+ * team account's refusal held every Codex account spent for a day, the free ones reading 0% used (2026-10-19).
80
+ */
81
+ const verdictOn = (refusal: ProviderRefusal, facts: ServiceFacts, accounts: number, now: number): "standing" | "answered" => {
82
+ const over = refusal.resetsAt ?? refusal.poolResetsAt;
83
+ const readSince = over !== undefined && (facts.usage?.measuredAt ?? 0) > over * 1000;
84
+ if (refusal.kind === "limit" && over !== undefined && over * 1000 <= now && (refusal.resetsAt !== undefined || !readSince)) {
85
+ return "answered";
86
+ }
87
+ const known = refusal.account !== undefined || accounts <= 1;
88
+ if (refusal.kind === "limit" && refusal.resetsAt !== undefined && known) {
89
+ return "standing";
90
+ }
91
+ return answers(refusal, facts, known ? undefined : true) ? "answered" : "standing";
92
+ };
93
+
94
+ /**
95
+ * How a refusal on file stands over a provider's accounts: `gone` once the account it named is disconnected, `standing`
96
+ * while it stands over any account it covers (verdictOn), else `answered`. An empty list is one not loaded yet, so the
97
+ * refusal stands. Judged by the daemon and every open window at the same instant from what the refusal carries.
98
+ */
99
+ export const refusalVerdict = (
100
+ refusal: ProviderRefusal,
101
+ accounts: readonly ServiceFacts[],
102
+ now: number = Date.now(),
103
+ ): "standing" | "answered" | "gone" => {
104
+ const covered = accounts.filter((facts) => (refusal.account ?? facts.account) === facts.account);
105
+ if (accounts.length === 0) {
106
+ return "standing";
107
+ }
108
+ if (covered.length === 0) {
109
+ return "gone";
110
+ }
111
+ return covered.some((facts) => verdictOn(refusal, facts, accounts.length, now) === "standing") ? "standing" : "answered";
112
+ };
113
+
114
+ // A stamp a reading has outlived (verdictOn) says nothing of when the pool now holding the refusal reopens: that pool's
115
+ // own reset does.
116
+ const unstampedPast = (refusal: ProviderRefusal, now: number): ProviderRefusal => {
117
+ if (refusal.poolResetsAt === undefined || refusal.poolResetsAt * 1000 > now) {
118
+ return refusal;
119
+ }
120
+ const { poolResetsAt: _outlived, ...standing } = refusal;
121
+ return standing;
122
+ };
123
+
124
+ // What a translator's per-model bench says, as a refusal filed for its account: a spent allowance on that model that
125
+ // stands until the instant the provider named, and no reading answers it before then (verdictOn: named, with its
126
+ // instant). Dated before anything on file, since the translator keeps no instant it began, so a refusal filed since
127
+ // (a revoked sign-in) is the account's newer word. One past its instant is over.
128
+ export const cooldownRefusals = (facts: ServiceFacts, now: number = Date.now()): ProviderRefusal[] =>
129
+ (facts.cooldowns ?? []).flatMap((cooldown) =>
130
+ cooldown.until * 1000 > now
131
+ ? [{ at: 0, kind: "limit", account: facts.account, model: cooldown.model, resetsAt: cooldown.until, message: `Out of allowance for ${cooldown.model} on this account.` }]
132
+ : [],
133
+ );
134
+
135
+ /**
136
+ * The refusals still standing over each of a provider's accounts (those naming it, those naming none, and the
137
+ * translator's per-model benches of it), each judged on that account's own facts.
138
+ */
139
+ export const standingOver = (accounts: readonly ServiceFacts[], refusals: RefusalsOnFile, now: number = Date.now()): ((account: string) => RefusalsOnFile) => {
140
+ const live = refusals.filter((refusal) => refusalVerdict(refusal, accounts, now) !== "gone");
141
+ return (account) => {
142
+ const facts = accounts.find((entry) => entry.account === account) ?? { account };
143
+ const filed = live
144
+ .filter((refusal) => (refusal.account ?? account) === account && verdictOn(refusal, facts, accounts.length, now) === "standing")
145
+ .map((refusal) => unstampedPast(refusal, now));
146
+ return [...cooldownRefusals(facts, now), ...filed];
147
+ };
148
+ };
@@ -14,6 +14,7 @@ import {
14
14
  EnvironmentSchema,
15
15
  } from "../../schemas/environment.js";
16
16
  import { SyncStatusSchema } from "../../schemas/devices.js";
17
+ import { ConversationBundleSchema, DiagnosticsAnswerSchema, DiagnosticsAskSchema, DiagnosticsQuerySchema } from "../../schemas/diagnostics.js";
17
18
  import { HostsListSchema } from "../../schemas/hosts.js";
18
19
  import { VoicesViewSchema } from "../../schemas/voice.js";
19
20
  import {
@@ -191,6 +192,12 @@ export const RAW_JSON_ROUTES = {
191
192
  "POST /link/conversations/{id}/messages": { input: LinkMessageSchema, output: LinkMessageReceiptSchema },
192
193
  "POST /link/conversations/{id}/answer": { input: LinkAnswerSchema, output: OkSchema },
193
194
  "POST /link/conversations/{id}/stop": { output: LinkTaskStatusSchema },
195
+ // A link's records: the diagnostics answer and a conversation's bundle. The fleet reads answer as the `agents`
196
+ // command's own routes do, which have no shared schema.
197
+ "POST /link/records/diagnostics": { input: DiagnosticsQuerySchema, output: DiagnosticsAnswerSchema },
198
+ "GET /link/records/fleet/{handle}/bundle": { output: ConversationBundleSchema },
199
+ "POST /diagnostics": { input: DiagnosticsAskSchema, output: DiagnosticsAnswerSchema },
200
+ "GET /fleet/{handle}/bundle": { output: ConversationBundleSchema },
194
201
  // An accounts link: what it may use, one static key's copy, and a lent sign-in's per-turn credential.
195
202
  "GET /link/accounts": { output: LinkAccountsSchema },
196
203
  "POST /link/accounts/copy": { input: SharedAccountRefSchema, output: LinkAccountCopySchema },
@@ -168,6 +168,11 @@ export const RAW_ROUTES = {
168
168
  "POST /fleet/message": { agent: true },
169
169
  "POST /fleet/resume": { agent: true },
170
170
  "GET /fleet/{handle}": { agent: true },
171
+ // One conversation's debug bundle (schemas/diagnostics.ts): `agents bundle`, and the editor's download of it. It
172
+ // carries the daemon's log lines about it, so a person reads it at the floor the logs are read at.
173
+ "GET /fleet/{handle}/bundle": { agent: true, floor: "maintainer", control: "never" },
174
+ // The `diagnostics` command: one read-only question of the daemon's records, or of a linked sandbox's with `on`.
175
+ "POST /diagnostics": { agent: true, floor: "maintainer", control: "never" },
171
176
  // The `devices push` CLI: a program the agent built, carried to one of the owner's computers in chunks; held to the
172
177
  // devices the calling conversation's turn mounts, and refused by the machine itself unless "Run programs" is on.
173
178
  "POST /devices/{name}/artifacts": { agent: true, control: "never" },
@@ -269,6 +274,11 @@ export const RAW_ROUTES = {
269
274
  // Its sibling for MCP: a hooked runtime's (Cursor's) calls to its turn's MCP servers, on a session signed the same
270
275
  // way, naming the provider and the one server it may forward to. Held open while a server streams its answer.
271
276
  "ALL /privacy/mcp/{session}": { auth: "door", control: "never", stream: true },
277
+ // The translator's gateway: every routed loop's model requests, on the signed session its base URL carries (the
278
+ // daemon's agent/providers/translator-gateway-session.ts), which names the provider, and on the translator's bearer
279
+ // too, both checked in the handler. Each request naming a model is placed on one of the provider's accounts before
280
+ // the translator sees it, so a refusal names the account that gave it. Held open while a model streams its answer.
281
+ "ALL /translator-gateway/{session}/*": { auth: "door", control: "never", stream: true },
272
282
  // Inbound links: another of the owner's sandboxes handing this one tasks (schemas/links.ts). Minted, re-termed and
273
283
  // revoked by the owner alone, checked in the handler like a control token; a waiting task is the owner's to allow.
274
284
  "GET /system/links": { control: "never" },
@@ -284,6 +294,13 @@ export const RAW_ROUTES = {
284
294
  "POST /link/conversations/{id}/messages": { auth: "door", control: "never" },
285
295
  "POST /link/conversations/{id}/answer": { auth: "door", control: "never" },
286
296
  "POST /link/conversations/{id}/stop": { auth: "door", control: "never" },
297
+ // A link's records doors (schemas/links.ts `records`): the asking sandbox reading this one's conversations, logs and
298
+ // diagnostics without starting a turn. Each checks the link token itself and answers only while the link's terms
299
+ // share records; none can change anything.
300
+ "GET /link/records/fleet": { auth: "door", control: "never" },
301
+ "GET /link/records/fleet/{handle}": { auth: "door", control: "never" },
302
+ "GET /link/records/fleet/{handle}/bundle": { auth: "door", control: "never" },
303
+ "POST /link/records/diagnostics": { auth: "door", control: "never" },
287
304
  // An accounts link's doors (schemas/providers/account-sharing.ts): the accounts its terms name, a static key's copy,
288
305
  // and a lent sign-in's access token per turn, re-minted mid-turn. The refresh token never leaves; each door checks the
289
306
  // link token itself and answers only for what the terms name.
@@ -25,6 +25,12 @@ export const AgentNextSchema = z.discriminatedUnion("kind", [
25
25
  z.object({
26
26
  kind: z.literal("land"),
27
27
  after: z.string().describe("The conversation whose landed work the first booked message waits for."),
28
+ // A modifier rather than a kind of its own, so a window older than it still reads the wait (as a land, which it
29
+ // says a little wrong) rather than failing the whole card.
30
+ turn: z
31
+ .literal(true)
32
+ .optional()
33
+ .describe("Set when that message waits for the conversation's turn to end cleanly with work to look at, not for its work to land (AgentTurn `sendAfterTurn`)."),
28
34
  count: z.number().int().min(1).describe("How many messages are booked to go by themselves."),
29
35
  }),
30
36
  ]);
@@ -283,6 +283,16 @@ const AgentTurnFieldsSchema = z.object({
283
283
  sendAfter: ConversationIdSchema.optional().describe(
284
284
  "Hold this message until the conversation named here has finished and all of its work has landed in the workspace, instead of starting a turn now: for work that builds on another agent's. It waits in this conversation's queue, where it can be sent early, reworded, rescheduled or removed. Sent at once when that conversation has nothing running and nothing left to land.",
285
285
  ),
286
+ // What `sendAfter` waits for, when it is not the land: the named conversation's turn ending clean, with its work still
287
+ // on its own branch. What a code review or a test pass booked on a session still at work waits by (a fresh session's
288
+ // opening message, `freshOf`), so it starts the moment the work holds still rather than after somebody lands it. A
289
+ // modifier, as `sendAtReopen` is of `sendAt`: a daemon from before it reads the land, which only waits longer.
290
+ sendAfterTurn: z
291
+ .literal(true)
292
+ .optional()
293
+ .describe(
294
+ "Says `sendAfter` waits for that conversation's turn to end, not for its work to land: the message goes once that conversation has finished a turn cleanly (nothing running, not stopped on a question, a permission or a failure, no checklist left open, nothing waiting to wake it) with work of its own to look at, whether or not that work has landed. Sent at once when it already rests so. Only with `sendAfter`.",
295
+ ),
286
296
  // Decided like `isolated`: the opening turn's answer, latched on the entry it opens. A maintainer's alone, since the
287
297
  // standing answer it sets is what `agents.autoLand` sets, and that route is a maintainer's.
288
298
  conversationAutoLand: z
@@ -292,35 +302,40 @@ const AgentTurnFieldsSchema = z.object({
292
302
  "Whether this conversation's finished work merges into the workspace by itself from now on: its own answer to the sandbox-wide setting, the one `agents.autoLand` changes later. Read only from the message that opens the conversation, and only from a maintainer. Unlike `autoLand`, it holds for every later turn.",
293
303
  ),
294
304
  });
295
- export const AgentTurnSchema = AgentTurnFieldsSchema
296
- // An attachment-only send (no text) is legal; an entirely empty turn is not.
297
- .refine((turn) => turn.prompt.trim().length > 0 || (turn.attachments?.length ?? 0) > 0, {
298
- message: "prompt or attachments required",
299
- })
300
- .refine((turn) => turn.isolated !== true || turn.conversationId !== undefined, {
301
- message: "isolated requires conversationId",
302
- })
303
- .refine((turn) => turn.worktreeBase === undefined || (turn.isolated === true && turn.conversationId !== undefined), {
304
- message: "worktreeBase requires an isolated conversationId",
305
- })
306
- .refine((turn) => turn.origin === undefined || turn.conversationId !== undefined, {
307
- message: "origin requires conversationId",
308
- })
309
- .refine((turn) => turn.forkOf === undefined || turn.conversationId !== undefined, {
310
- message: "forkOf requires conversationId",
311
- })
312
- // "then" needs a checkout of its own; rolling back the shared tree under everyone else is what it must never mean.
313
- .refine((turn) => turn.forkOf?.files !== "then" || turn.isolated === true, {
314
- message: 'forkOf.files "then" requires isolated',
315
- })
316
- .superRefine(freshOfIssues)
317
- .superRefine(fromBranchIssues)
318
- .refine((turn) => turn.sendAt === undefined || turn.sendAfter === undefined, {
319
- message: "sendAt and sendAfter are two different holds: name one",
320
- })
321
- .refine((turn) => turn.sendAfter === undefined || turn.sendAfter !== turn.conversationId, {
322
- message: "a conversation cannot wait for its own work to land",
323
- });
305
+ // A turn says something: words, or files alone. A Continue a queue keeps says nothing by design (WordlessTurnSchema).
306
+ export const turnHasWords = (turn: { readonly prompt: string; readonly attachments?: readonly unknown[] | undefined }): boolean =>
307
+ turn.prompt.trim().length > 0 || (turn.attachments?.length ?? 0) > 0;
308
+ const withTurnRules = (fields: typeof AgentTurnFieldsSchema) =>
309
+ fields
310
+ .refine((turn) => turn.isolated !== true || turn.conversationId !== undefined, {
311
+ message: "isolated requires conversationId",
312
+ })
313
+ .refine((turn) => turn.worktreeBase === undefined || (turn.isolated === true && turn.conversationId !== undefined), {
314
+ message: "worktreeBase requires an isolated conversationId",
315
+ })
316
+ .refine((turn) => turn.origin === undefined || turn.conversationId !== undefined, {
317
+ message: "origin requires conversationId",
318
+ })
319
+ .refine((turn) => turn.forkOf === undefined || turn.conversationId !== undefined, {
320
+ message: "forkOf requires conversationId",
321
+ })
322
+ // "then" needs a checkout of its own; rolling back the shared tree under everyone else is what it must never mean.
323
+ .refine((turn) => turn.forkOf?.files !== "then" || turn.isolated === true, {
324
+ message: 'forkOf.files "then" requires isolated',
325
+ })
326
+ .superRefine(freshOfIssues)
327
+ .superRefine(fromBranchIssues)
328
+ .refine((turn) => turn.sendAt === undefined || turn.sendAfter === undefined, {
329
+ message: "sendAt and sendAfter are two different holds: name one",
330
+ })
331
+ .refine((turn) => turn.sendAfter === undefined || turn.sendAfter !== turn.conversationId, {
332
+ message: "a conversation cannot wait for its own work to land",
333
+ })
334
+ .refine((turn) => turn.sendAfterTurn === undefined || turn.sendAfter !== undefined, {
335
+ message: "sendAfterTurn says what sendAfter waits for: name the conversation in sendAfter",
336
+ });
337
+ export const AgentTurnSchema = withTurnRules(AgentTurnFieldsSchema.refine(turnHasWords, { message: "prompt or attachments required" }));
338
+ export const WordlessTurnSchema = withTurnRules(AgentTurnFieldsSchema);
324
339
  export type AgentTurn = z.infer<typeof AgentTurnSchema>;
325
340
  // What `agent.run` takes: a turn, plus the one field only a request carries and no stored turn keeps. A daemon from before
326
341
  // `continues` reads past it and takes `prompt` as the words, which is why a client still sends some.
@@ -518,6 +533,12 @@ export const QueuedMessageSchema = z.object({
518
533
  after: ConversationIdSchema.optional().describe(
519
534
  "The conversation whose finished work must land before this message goes out by itself, in place of `until`.",
520
535
  ),
536
+ afterTurn: z
537
+ .literal(true)
538
+ .optional()
539
+ .describe(
540
+ "Says `after` waits for that conversation's turn to end cleanly with work to look at, not for its work to land (`sendAfterTurn`). Absent on a land booking, and from sandboxes older than the field.",
541
+ ),
521
542
  reopenOf: QueuedReopenSchema.optional().describe(
522
543
  "The allowance this message's `until` waits out: it was booked for that account's reopen, by the composer or by the sandbox holding words it would not send into a spent allowance, rather than for a time somebody chose. Absent on any other booking, and from sandboxes older than the field.",
523
544
  ),
@@ -0,0 +1,166 @@
1
+ import { z } from "zod";
2
+
3
+ // THE DIAGNOSTICS QUERIES: read-only questions over what a sandbox's daemon already recorded (its log, the editor's
4
+ // reports, slow spans and rollups, the turn ledger, the resource series, its boots, one conversation's timeline). One
5
+ // set of arguments serves every door that asks them: the `diagnostics` tools a turn mounts, the `diagnostics` command on
6
+ // the agent's PATH (POST /diagnostics), and a linked sandbox reading this one's records (POST /link/records/diagnostics).
7
+ // Each answers with text written to be read, never the raw lines, and each takes a window.
8
+
9
+ // Two weeks and a day: the perf rollups keep two weeks; every other record reaches less far, and says so.
10
+ export const DIAGNOSTICS_MAX_MINUTES = 15 * 24 * 60;
11
+ // Bounds one answer's rows; a caller that hits the cap is told and narrows.
12
+ export const DIAGNOSTICS_MAX_LINES = 200;
13
+
14
+ const levels = ["trace", "debug", "info", "warn", "error", "fatal"] as const;
15
+ export const DiagnosticsLevelSchema = z.enum(levels);
16
+
17
+ const minutes = () => z.number().int().min(1).max(DIAGNOSTICS_MAX_MINUTES).optional();
18
+ const limit = () => z.number().int().min(1).max(DIAGNOSTICS_MAX_LINES).optional();
19
+ const instant = () => z.iso.datetime({ offset: true });
20
+
21
+ /** `errors`: the daemon's log or the editor's reports, newest first. */
22
+ export const DiagnosticsErrorsArgs = {
23
+ source: z
24
+ .enum(["daemon", "browser"])
25
+ .optional()
26
+ .describe("Whose account of it: the sandbox's own log, or what the editor sent about itself. Defaults to the daemon."),
27
+ sinceMinutes: minutes().describe("How far back to look. Leave it out for everything the file still holds."),
28
+ from: instant()
29
+ .optional()
30
+ .describe("Start of an absolute window (ISO time, e.g. `2026-11-07T23:40:00Z`), instead of `sinceMinutes`: for reading around a moment you already know."),
31
+ until: instant()
32
+ .optional()
33
+ .describe("End of the window (ISO time): lines after it are left out. With `from`, reads exactly the lines between the two."),
34
+ level: DiagnosticsLevelSchema.optional().describe("Lowest level to include, and it includes worse ones. Defaults to `warn`, which is what went wrong."),
35
+ contains: z
36
+ .string()
37
+ .max(200)
38
+ .optional()
39
+ .describe("Case-insensitive substring, matched anywhere in the line: a conversation id, an error code, a route, a message."),
40
+ group: z
41
+ .boolean()
42
+ .optional()
43
+ .describe("true: one row per kind of message, with its count and first and last time. false: every line. Left out, lines are grouped once there are more than `limit`."),
44
+ stacks: z.boolean().optional().describe("Include each exception's stack. Off by default: stacks dwarf the line they belong to."),
45
+ limit: limit(),
46
+ };
47
+
48
+ /** `slow`: operations over their budget, or every span's rollups. */
49
+ export const DiagnosticsSlowArgs = {
50
+ source: z
51
+ .enum(["slow", "rollups"])
52
+ .optional()
53
+ .describe(
54
+ "`slow` (the default): the spans over budget, one by one, from perf.jsonl (about a week). `rollups`: the distribution of every span from perf-rollups.jsonl (two weeks), with no single span or load to show.",
55
+ ),
56
+ sinceMinutes: minutes(),
57
+ op: z
58
+ .string()
59
+ .max(100)
60
+ .optional()
61
+ .describe("One operation by its exact name (`git.run` is not `git.run.wait`), or every one under a prefix ending in `.` or `*` (`git.`, `devices.*`)."),
62
+ groupBy: z
63
+ .enum(["op", "op+path", "none"])
64
+ .optional()
65
+ .describe(
66
+ "`op` one row per operation; `op+path` splits each by its subject (the route of a request, the git subcommand, the hook's tool); `none` every span. Left out, spans are grouped by op once there are more than `limit`. Rollups have no single spans, so `none` reads as `op+path` there.",
67
+ ),
68
+ limit: limit(),
69
+ };
70
+
71
+ /** `turns`: how recent agent turns ended, from the spend ledger. */
72
+ export const DiagnosticsTurnsArgs = {
73
+ sinceMinutes: minutes(),
74
+ conversationId: z.string().max(200).optional().describe("Narrow to one conversation."),
75
+ only: z
76
+ .enum(["failed", "unproven", "silent", "interrupted"])
77
+ .optional()
78
+ .describe(
79
+ 'Narrow to one kind of ending: "failed" is turns that failed or were cancelled, "unproven" is turns that ' +
80
+ "changed code and finished with nothing having checked it (including ones whose last check broke), " +
81
+ '"silent" is turns that ran but called no tool and changed no file, "interrupted" is turns a restart or ' +
82
+ "a spent allowance cut off. Leave it out for every turn.",
83
+ ),
84
+ limit: limit(),
85
+ };
86
+
87
+ /** `resources`: one field of the resource series over time. */
88
+ export const DiagnosticsResourcesArgs = {
89
+ field: z.string().min(1).max(200).describe("Dotted path into one sample, e.g. `system.cgroup.event_oom_kill`."),
90
+ sinceMinutes: minutes(),
91
+ limit: limit(),
92
+ };
93
+
94
+ /** `restarts`: the daemon's boots and why each run before ended. */
95
+ export const DiagnosticsRestartsArgs = { sinceMinutes: minutes(), limit: limit() };
96
+
97
+ /** `timeline`: everything recorded about one conversation, oldest first. */
98
+ export const DiagnosticsTimelineArgs = {
99
+ conversationId: z.string().min(1).max(200).describe("The conversation's id, e.g. `wise-fern-usz1`."),
100
+ sinceMinutes: minutes(),
101
+ level: DiagnosticsLevelSchema.optional().describe("Lowest daemon.log level to include. Defaults to `info`, so the turn's own lifecycle lines are in."),
102
+ limit: z.number().int().min(1).max(DIAGNOSTICS_MAX_LINES).optional().describe("The newest this many events. Defaults to 100."),
103
+ };
104
+
105
+ // One query, named by `query`, with that query's own arguments.
106
+ export const DiagnosticsQuerySchema = z.discriminatedUnion("query", [
107
+ z.object({ query: z.literal("errors"), ...DiagnosticsErrorsArgs }),
108
+ z.object({ query: z.literal("slow"), ...DiagnosticsSlowArgs }),
109
+ z.object({ query: z.literal("turns"), ...DiagnosticsTurnsArgs }),
110
+ z.object({ query: z.literal("resources"), ...DiagnosticsResourcesArgs }),
111
+ z.object({ query: z.literal("restarts"), ...DiagnosticsRestartsArgs }),
112
+ z.object({ query: z.literal("timeline"), ...DiagnosticsTimelineArgs }),
113
+ ]);
114
+ export type DiagnosticsQuery = z.infer<typeof DiagnosticsQuerySchema>;
115
+ export type DiagnosticsQueryName = DiagnosticsQuery["query"];
116
+ export const DIAGNOSTICS_QUERY_NAMES = ["errors", "slow", "turns", "resources", "restarts", "timeline"] as const satisfies readonly DiagnosticsQueryName[];
117
+
118
+ // POST /diagnostics: one query of this sandbox's records, or, with `on`, of the linked sandbox that card names, read
119
+ // through the link (its owner must share records on it).
120
+ export const DiagnosticsAskSchema = z.intersection(
121
+ DiagnosticsQuerySchema,
122
+ z.object({
123
+ on: z
124
+ .string()
125
+ .min(1)
126
+ .max(100)
127
+ .optional()
128
+ .describe("A link card's id: ask the linked sandbox instead of this one. `agents links` names the links this turn may use."),
129
+ }),
130
+ );
131
+ export type DiagnosticsAsk = z.infer<typeof DiagnosticsAskSchema>;
132
+
133
+ export const DiagnosticsAnswerSchema = z.object({
134
+ text: z.string().describe("The answer, as the diagnostics tools word it: what it searched, how far back the record reaches, then the rows."),
135
+ sandbox: z.string().optional().describe("Whose records these are, when they are a linked sandbox's."),
136
+ });
137
+ export type DiagnosticsAnswer = z.infer<typeof DiagnosticsAnswerSchema>;
138
+
139
+ /* A CONVERSATION'S DEBUG BUNDLE: one file holding what a person or an agent elsewhere needs to look into what happened
140
+ * to one conversation, without access to the sandbox it ran in. GET /fleet/{handle}/bundle (and the link's records door)
141
+ * answers it; `agents bundle` writes it, and the editor downloads it. Every part is what the sandbox already shows its
142
+ * own agents: secrets ride as their `{{secret:name}}` references, as they are stored. */
143
+
144
+ export const CONVERSATION_BUNDLE_KIND = "intentic.conversation-bundle";
145
+
146
+ export const ConversationBundleSchema = z.object({
147
+ kind: z.literal(CONVERSATION_BUNDLE_KIND),
148
+ version: z.literal(1),
149
+ exportedAt: z.string().describe("When it was put together, ISO time."),
150
+ sandbox: z.object({
151
+ name: z.string().describe("What the sandbox calls itself."),
152
+ version: z.string().optional().describe("The daemon's version: 0.0.0 is an unreleased build."),
153
+ }),
154
+ conversation: z.string().describe("The conversation's id."),
155
+ // What `agents show` answers, as JSON: what it was asked, where it got to, its branch, how it ended.
156
+ show: z.unknown(),
157
+ // The record as stored, newest last, bounded: `total` says how many rows it has.
158
+ transcript: z.unknown(),
159
+ // The diagnostics answers about it, each as the `diagnostics` command words it.
160
+ timeline: z.string(),
161
+ turns: z.string(),
162
+ errors: z.string(),
163
+ restarts: z.string(),
164
+ browser: z.string().describe("What the editor reported about itself while the conversation ran."),
165
+ });
166
+ export type ConversationBundle = z.infer<typeof ConversationBundleSchema>;
@@ -36,6 +36,11 @@ const turnsPerHourTerm = z
36
36
  const tasksTerm = z
37
37
  .boolean()
38
38
  .describe("Whether the link may hand this sandbox tasks at all. An accounts link is minted without: it only borrows and copies the accounts below.");
39
+ const recordsTerm = z
40
+ .boolean()
41
+ .describe(
42
+ "Whether the asking sandbox may read this sandbox's records without starting a turn: its conversations (every one but a private one) and their transcripts, its daemon's log and diagnostics. Read-only, and each read is logged here. For looking into a problem from the other sandbox; off unless its owner turns it on.",
43
+ );
39
44
  const accountsTerm = z
40
45
  .array(SharedAccountRefSchema)
41
46
  .max(64)
@@ -58,6 +63,7 @@ export const LinkTermsSchema = z.object({
58
63
  approve: approveTerm.default(false),
59
64
  turnsPerHour: turnsPerHourTerm.default(LINK_TURNS_PER_HOUR_DEFAULT),
60
65
  tasks: tasksTerm.default(true),
66
+ records: recordsTerm.default(false),
61
67
  accounts: accountsTerm.default([]),
62
68
  });
63
69
  export type LinkTerms = z.infer<typeof LinkTermsSchema>;
@@ -117,6 +123,7 @@ export const InboundLinkTermsUpdateSchema = z.object({
117
123
  approve: approveTerm.optional(),
118
124
  turnsPerHour: turnsPerHourTerm.optional(),
119
125
  tasks: tasksTerm.optional(),
126
+ records: recordsTerm.optional(),
120
127
  accounts: accountsTerm.optional(),
121
128
  });
122
129
  export type InboundLinkTermsUpdate = z.infer<typeof InboundLinkTermsUpdateSchema>;
@@ -137,6 +144,8 @@ export const LinkHelloSchema = z.object({
137
144
  // Absent from a sandbox older than accounts links, which takes tasks and lends nothing.
138
145
  tasks: z.boolean().optional(),
139
146
  accounts: z.number().int().nonnegative().optional().describe("How many accounts the link may use."),
147
+ // Absent from a sandbox older than records over links, which shares none.
148
+ records: z.boolean().optional().describe("Whether the link may read this sandbox's records (its conversations, logs and diagnostics)."),
140
149
  }),
141
150
  maxHops: z.number().int(),
142
151
  });
@@ -5,6 +5,7 @@ import { AgentHarnessSchema, AgentProviderSchema, ConversationIdSchema, EditorCo
5
5
  import { MENTION_LIMIT } from "../../text/mentions.js";
6
6
  import { HandoffModeSchema } from "./handoff.js";
7
7
  import { NightAnswerSchema } from "../night-hours.js";
8
+ import { ModelCooldownSchema } from "./refusals.js";
8
9
  // Headroom is one shape shared by every provider, not a Claude idea others imitate: a native account and a routed
9
10
  // subscription differ in who holds the credential, never in what a reading is. Every surface that draws a percentage
10
11
  // reads this one type.
@@ -150,7 +151,7 @@ export const LimitResetClaimSchema = z.object({
150
151
  detail: z.string().optional().describe("What went wrong, in words, for the two outcomes that are this sandbox's fault rather than the plan's."),
151
152
  });
152
153
  export type LimitResetClaim = z.infer<typeof LimitResetClaimSchema>;
153
- export { type ProviderRefusal, ProviderRefusalSchema, type ProviderRefusals, ProviderRefusalsSchema } from "./refusals.js";
154
+ export { type ModelCooldown, ModelCooldownSchema, type ProviderRefusal, ProviderRefusalSchema, type ProviderRefusals, ProviderRefusalsSchema } from "./refusals.js";
154
155
  // `name` is CLIProxyAPI's auth-file name, the stable key a disconnect addresses; `label` is the reported sign-in
155
156
  // identity (email, else the file name).
156
157
  export const TranslatorAccountSchema = z.object({
@@ -175,6 +176,11 @@ export const TranslatorAccountSchema = z.object({
175
176
  verify: z.string().optional(),
176
177
  })
177
178
  .optional(),
179
+ // The proxy's per-model benches: the provider refused this account on one model, for its allowance, and said when
180
+ // to try again. Each is a spent allowance that names its account, its model and the provider's own instant, which the
181
+ // serviceability rule reads like a refusal filed for this account (refusal-verdict.ts cooldownRefusals). A bench on
182
+ // one model never benches the account's others: a Google account out of Claude still serves Gemini.
183
+ cooldowns: z.array(ModelCooldownSchema).optional(),
178
184
  });
179
185
  export type TranslatorAccount = z.infer<typeof TranslatorAccountSchema>;
180
186
  // A list per provider, not a flag: CLIProxyAPI holds several auth files per provider and balances across them. Built
@@ -479,6 +485,12 @@ export const QueueScheduleSchema = z
479
485
  .describe(
480
486
  "Says `sendAt` is the reopen of the allowance what waits would be refused by, not a time you chose; the queue records it as `reopenOf`. Only with `sendAt`.",
481
487
  ),
488
+ sendAfterTurn: z
489
+ .literal(true)
490
+ .optional()
491
+ .describe(
492
+ "Says `sendAfter` waits for that conversation's turn to end cleanly with work to look at, not for its work to land (AgentTurn `sendAfterTurn`). Only with `sendAfter`.",
493
+ ),
482
494
  ids: z
483
495
  .array(z.string().min(1))
484
496
  .optional()
@@ -489,6 +501,9 @@ export const QueueScheduleSchema = z
489
501
  })
490
502
  .refine((input) => input.sendAfter !== input.conversationId, {
491
503
  message: "a conversation cannot wait for its own work to land",
504
+ })
505
+ .refine((input) => input.sendAfterTurn === undefined || input.sendAfter !== undefined, {
506
+ message: "sendAfterTurn says what sendAfter waits for: name the conversation in sendAfter",
492
507
  });
493
508
  export type QueueSchedule = z.infer<typeof QueueScheduleSchema>;
494
509
  // Books the conversation to carry on from where its last turn stopped, at an instant or once another conversation's work
@@ -3,8 +3,9 @@ import { z } from "zod";
3
3
  // WHAT A PROVIDER SAID WHEN IT REFUSED A TURN, and the ledger of them the sandbox answers with. Kept out of plan-limits.ts,
4
4
  // which re-exports both, so the plan and turn schemas there stay within one file's reach.
5
5
 
6
- // Observed and exact, unlike a polled usage snapshot that can be stale; keyed by provider, not account, since a routed
7
- // turn doesn't know which served it. `kind` is read off what the provider said, not the frame code.
6
+ // Observed and exact, unlike a polled usage snapshot that can be stale; filed by provider, naming the account it refused
7
+ // wherever that is known (a routed turn's since the daemon's gateway places each request on one: 2026-11-08), and judged
8
+ // on that account alone. `kind` is read off what the provider said, not the frame code.
8
9
  export const ProviderRefusalSchema = z.object({
9
10
  // Read side by side with `AccountUsage.measuredAt` (also ms).
10
11
  at: z.number().describe("When it refused, in milliseconds."),
@@ -15,7 +16,8 @@ export const ProviderRefusalSchema = z.object({
15
16
  "Three different noes, kept apart because what fixes each is different. A spent allowance is answered by waiting; a refused credential by signing in again; and an entitlement refusal, where somebody has switched this off for your seat, by neither of those. That last one authenticates fine and reports healthy limits the whole time it refuses everything.",
16
17
  ),
17
18
  message: z.string().describe("The provider's own words, verbatim. The only part that says which limit or which credential."),
18
- // Known for native turns only; a routed turn doesn't say which account served it.
19
+ // Absent only where nothing names the account that refused: such a refusal is judged on each account by that
20
+ // account's own reading (refusal-verdict.ts).
19
21
  account: z.string().optional().describe("Which account was serving, where that is known."),
20
22
  // Lets a `limit` refusal be read against the pool that model spends (`UsageWindow.gates`), not the account's
21
23
  // fullest pool.
@@ -46,6 +48,13 @@ export const ProviderRefusalSchema = z.object({
46
48
  ),
47
49
  });
48
50
  export type ProviderRefusal = z.infer<typeof ProviderRefusalSchema>;
51
+ // A routed account's per-model bench as the translator holds it: the provider's own refusal of that account on that
52
+ // model, kept where the translator keeps it rather than copied onto the ledger, so it ends when the provider said.
53
+ export const ModelCooldownSchema = z.object({
54
+ model: z.string().describe("The model the provider refused this account on, as the translator names it."),
55
+ until: z.number().describe("When the provider said to try again, in epoch seconds."),
56
+ });
57
+ export type ModelCooldown = z.infer<typeof ModelCooldownSchema>;
49
58
  // A released daemon (1.345.0 and earlier) answers one refusal per provider, its last: read as a list of one, as the
50
59
  // /events frame's `refusal` is (refusalsOf). What this build sends, and its output shape, is still the list.
51
60
  const RefusalsOnFileSchema = z.codec(z.union([z.array(ProviderRefusalSchema), ProviderRefusalSchema]), z.array(ProviderRefusalSchema), {