@capybara-hq/kernel 0.1.0-rc.109 → 0.1.0-rc.110

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 (51) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/background/wake-rules.js +2 -0
  3. package/dist/conversations/conversations.service.js +4 -2
  4. package/dist/conversations/event-log.js +11 -1
  5. package/dist/conversations/events.d.ts +5 -0
  6. package/dist/conversations/events.js +11 -2
  7. package/dist/conversations/prompt-suggestion-store.d.ts +3 -1
  8. package/dist/conversations/prompt-suggestion-store.js +5 -1
  9. package/dist/db/kernel-schema.d.ts +7 -0
  10. package/dist/identity/accounts.d.ts +8 -9
  11. package/dist/identity/accounts.js +18 -3
  12. package/dist/identity/me.controller.d.ts +4 -2
  13. package/dist/identity/me.controller.js +4 -2
  14. package/dist/identity/me.schemas.d.ts +3 -0
  15. package/dist/identity/me.schemas.js +5 -0
  16. package/dist/identity/settings.d.ts +15 -0
  17. package/dist/identity/settings.js +12 -0
  18. package/dist/infra/outbox/registry.d.ts +14 -0
  19. package/dist/infra/outbox/registry.js +14 -0
  20. package/dist/orgs/settings.service.d.ts +6 -0
  21. package/dist/platform/ops/org-settings.ops.js +1 -1
  22. package/dist/platform/ops/platform.ops.js +9 -3
  23. package/dist/push/recipients.js +4 -2
  24. package/dist/runtime/abort.d.ts +22 -3
  25. package/dist/runtime/abort.js +37 -17
  26. package/dist/runtime/compaction.service.d.ts +43 -12
  27. package/dist/runtime/compaction.service.js +60 -16
  28. package/dist/runtime/context/idle-compaction-rules.d.ts +94 -0
  29. package/dist/runtime/context/idle-compaction-rules.js +84 -0
  30. package/dist/runtime/idle-arm.d.ts +38 -0
  31. package/dist/runtime/idle-arm.js +269 -0
  32. package/dist/runtime/idle-compaction-jobs.d.ts +25 -0
  33. package/dist/runtime/idle-compaction-jobs.js +21 -0
  34. package/dist/runtime/idle-compaction.d.ts +43 -0
  35. package/dist/runtime/idle-compaction.js +316 -0
  36. package/dist/runtime/idle-return.d.ts +62 -0
  37. package/dist/runtime/idle-return.js +170 -0
  38. package/dist/runtime/maintenance.d.ts +5 -2
  39. package/dist/runtime/maintenance.js +14 -4
  40. package/dist/runtime/model-call.d.ts +113 -5
  41. package/dist/runtime/model-call.js +119 -71
  42. package/dist/runtime/run-finish.d.ts +16 -1
  43. package/dist/runtime/run-finish.js +27 -4
  44. package/dist/runtime/run-queue.d.ts +56 -2
  45. package/dist/runtime/run-queue.js +257 -8
  46. package/dist/runtime/run-worker.d.ts +22 -8
  47. package/dist/runtime/run-worker.js +75 -28
  48. package/dist/runtime/runtime.module.js +11 -0
  49. package/dist/runtime/waits.js +1 -1
  50. package/package.json +1 -1
  51. package/src/migrations/0195_idle_compaction.sql +7 -0
@@ -88,6 +88,9 @@ export declare const DeploymentSettingsBody: z.ZodObject<{
88
88
  keepRecentTurns: z.ZodOptional<z.ZodNumber>;
89
89
  reserveTokens: z.ZodOptional<z.ZodNumber>;
90
90
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
91
+ idleEnabled: z.ZodOptional<z.ZodBoolean>;
92
+ idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
93
+ idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
91
94
  }, z.core.$strict>>;
92
95
  promptCache: z.ZodOptional<z.ZodObject<{
93
96
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -115,6 +115,8 @@ export async function wakeDecisionIn(t, conv, consumed, deploymentOn, canSend) {
115
115
  ])
116
116
  .where("r.conversation_id", "=", conv.id)
117
117
  .where("w.type", "in", WAKE_EVENT_TYPES)
118
+ // a compact run's boundary is the consumed seq, which may be a wake event: it is no wake run
119
+ .where("r.compact", "=", false)
118
120
  .executeTakeFirst();
119
121
  if (last?.started != null) {
120
122
  const windowEnd = Number(last.started) + WAKE_WINDOW_MS;
@@ -75,7 +75,8 @@ export function escapeLike(s) {
75
75
  * SQL for the activity of the conversation row aliased/named `ref` (a correlated subquery).
76
76
  * A run waiting on its sub-agents (status waiting with `wait_expires_at`, set only for a
77
77
  * `subagents` wait) is still working, so it reports `running`; only a wait for a person
78
- * (approval, input) reports `waiting`.
78
+ * (approval, input) reports `waiting`. An idle compact run is not activity (idle compaction spec
79
+ * §6: quiet): the latest other run decides.
79
80
  */
80
81
  function activitySql(ref) {
81
82
  const id = sql.ref(`${ref}.id`);
@@ -84,7 +85,8 @@ function activitySql(ref) {
84
85
  WHEN lr.status IN ('queued', 'running') THEN 'running'
85
86
  WHEN lr.status = 'waiting' AND lr.wait_expires_at IS NOT NULL THEN 'running'
86
87
  WHEN lr.status = 'waiting' THEN 'waiting' END
87
- FROM capybara.runs lr WHERE lr.conversation_id = ${id}
88
+ FROM capybara.runs lr
89
+ WHERE lr.conversation_id = ${id} AND lr.compact_origin IS DISTINCT FROM 'idle'
88
90
  ORDER BY lr.created_at DESC, lr.id DESC LIMIT 1
89
91
  )`;
90
92
  }
@@ -472,9 +472,19 @@ let EventLog = class EventLog {
472
472
  };
473
473
  }
474
474
  const n = fresh.length;
475
+ // updated_at orders the conversation lists; an idle compact run's events leave it (idle
476
+ // compaction spec §6: quiet). Decided in this same statement (a primary key probe on runs,
477
+ // only for a batch of one run's events), so the append costs no extra round trip
478
+ const runIds = new Set(fresh.map((i) => events[i]?.runId));
479
+ const [onlyRun] = runIds;
480
+ const updatedAt = runIds.size === 1 && onlyRun !== undefined
481
+ ? sql `CASE WHEN EXISTS (SELECT 1 FROM capybara.runs ir
482
+ WHERE ir.id = ${onlyRun} AND ir.compact_origin = 'idle')
483
+ THEN updated_at ELSE now() END`
484
+ : sql `now()`;
475
485
  const { last_seq } = await t
476
486
  .updateTable("conversations")
477
- .set({ last_seq: sql `last_seq + ${n}`, updated_at: sql `now()` })
487
+ .set({ last_seq: sql `last_seq + ${n}`, updated_at: updatedAt })
478
488
  .where("id", "=", conversationId)
479
489
  .returning("last_seq")
480
490
  .executeTakeFirstOrThrow();
@@ -1100,6 +1100,10 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1100
1100
  subagent: "subagent";
1101
1101
  }>>;
1102
1102
  triggerSeq: z.ZodOptional<z.ZodNumber>;
1103
+ compactOrigin: z.ZodOptional<z.ZodEnum<{
1104
+ idle: "idle";
1105
+ manual: "manual";
1106
+ }>>;
1103
1107
  }, z.core.$strip>;
1104
1108
  }, z.core.$strip>, z.ZodObject<{
1105
1109
  type: z.ZodLiteral<"model_call">;
@@ -2159,6 +2163,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2159
2163
  eval_stopped: "eval_stopped";
2160
2164
  org_deleted: "org_deleted";
2161
2165
  shutdown_exhausted: "shutdown_exhausted";
2166
+ superseded: "superseded";
2162
2167
  user: "user";
2163
2168
  }>;
2164
2169
  detail: z.ZodOptional<z.ZodEnum<{
@@ -1024,6 +1024,11 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1024
1024
  * seeds from it).
1025
1025
  */
1026
1026
  triggerSeq: seqNo.optional(),
1027
+ /**
1028
+ * Which compact run this is (idle compaction spec §5.1); display only: absent = manual,
1029
+ * never model-visible.
1030
+ */
1031
+ compactOrigin: z.enum(["manual", "idle"]).optional(),
1027
1032
  })),
1028
1033
  ev("model_call", z.object({
1029
1034
  step: count,
@@ -1912,8 +1917,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1912
1917
  ev("run_failed", z.object({ error: z.object({ code: z.string(), message: z.string() }) })),
1913
1918
  ev("run_aborted", z.object({
1914
1919
  byAccountId: z.string().nullable(),
1915
- /** `eval_stopped`:评测整轮回放被评测运行停下(只出现在 `kind = 'eval'` 的对话里),原因见 `detail`。 */
1916
- reason: z.enum(["user", "shutdown_exhausted", "eval_stopped", "org_deleted"]),
1920
+ /**
1921
+ * `eval_stopped`: an eval's full-run replay was stopped by the eval run (only in conversations
1922
+ * with `kind = 'eval'`); the cause is in `detail`. `superseded`: an idle compact run preempted
1923
+ * by input (idle compaction spec §5.2); no account.
1924
+ */
1925
+ reason: z.enum(["user", "shutdown_exhausted", "eval_stopped", "org_deleted", "superseded"]),
1917
1926
  /**
1918
1927
  * Why an eval replay stopped (`eval_stopped`), or `wait_timeout`: a sub-agent run stopped
1919
1928
  * (`user`, no account) because its parent's sub-agents wait timed out (phase C).
@@ -45,7 +45,9 @@ export declare class PromptSuggestionStore {
45
45
  /**
46
46
  * The freshness rule (spec §4), read from PG with plain queries (no lock): `runId` is the
47
47
  * conversation's latest run and it is terminal, the log has no `user_message` and no
48
- * `run_started` with a seq above `afterSeq`, and the conversation's message queue is empty.
48
+ * `run_started` with a seq above `afterSeq`, and the conversation's message queue is empty. An
49
+ * idle compact run (idle compaction spec §6) counts for neither: it ran while the person was
50
+ * away, answered nothing and changed no message, so the suggestion they come back to stands.
49
51
  */
50
52
  isFresh(conversationId: string, s: Pick<StoredSuggestion, "runId" | "afterSeq">): Promise<boolean>;
51
53
  }
@@ -92,7 +92,9 @@ let PromptSuggestionStore = class PromptSuggestionStore {
92
92
  /**
93
93
  * The freshness rule (spec §4), read from PG with plain queries (no lock): `runId` is the
94
94
  * conversation's latest run and it is terminal, the log has no `user_message` and no
95
- * `run_started` with a seq above `afterSeq`, and the conversation's message queue is empty.
95
+ * `run_started` with a seq above `afterSeq`, and the conversation's message queue is empty. An
96
+ * idle compact run (idle compaction spec §6) counts for neither: it ran while the person was
97
+ * away, answered nothing and changed no message, so the suggestion they come back to stands.
96
98
  */
97
99
  async isFresh(conversationId, s) {
98
100
  const db = this.kdb.db;
@@ -100,6 +102,7 @@ let PromptSuggestionStore = class PromptSuggestionStore {
100
102
  .selectFrom("runs")
101
103
  .select(["id", "status"])
102
104
  .where("conversation_id", "=", conversationId)
105
+ .where((eb) => eb.or([eb("compact_origin", "is", null), eb("compact_origin", "!=", "idle")]))
103
106
  .orderBy("created_at", "desc")
104
107
  .orderBy("id", "desc")
105
108
  .limit(1)
@@ -114,6 +117,7 @@ let PromptSuggestionStore = class PromptSuggestionStore {
114
117
  .where("conversation_id", "=", conversationId)
115
118
  .where("seq", ">", String(s.afterSeq))
116
119
  .where("type", "in", ["user_message", "run_started"])
120
+ .where(sql `payload->>'compactOrigin' IS DISTINCT FROM 'idle'`)
117
121
  .limit(1)
118
122
  .executeTakeFirst();
119
123
  if (newer !== undefined)
@@ -101,6 +101,8 @@ export interface AccountsTable {
101
101
  theme: ColumnType<string | null, string | null | undefined, string | null>;
102
102
  /** 0169: the person's own avatar; null shows the SSO avatar or the initial (account profile §5.1). */
103
103
  avatar: ColumnType<AccountAvatar | null, string | null | undefined, string | null>;
104
+ /** 0195: the person's idle compaction opt-out; null follows the org (idle compaction spec §6.3). */
105
+ idle_compaction: ColumnType<"off" | null, "off" | null | undefined, "off" | null>;
104
106
  }
105
107
  /** 0169: an account's avatar uploads (bytes in the object store under `deployment/account-avatars/`). */
106
108
  export interface AccountAvatarUploadsTable {
@@ -570,6 +572,11 @@ export interface RunsTable {
570
572
  * execution with `force: true` instead of the agent loop, and writes no model step.
571
573
  */
572
574
  compact: ColumnType<boolean, boolean | undefined, boolean>;
575
+ /**
576
+ * 0195: who started a compact run (idle compaction spec §5.1): 'manual' (a person) or 'idle'
577
+ * (the idle compaction job); null = an ordinary run, or a compact run from before 0195 (manual).
578
+ */
579
+ compact_origin: ColumnType<"manual" | "idle" | null, "manual" | "idle" | null | undefined, "manual" | "idle" | null>;
573
580
  }
574
581
  /** 0053: one row per sub-agent dispatch (an `Agent` call of a parent run). */
575
582
  export interface SubagentDispatchesTable {
@@ -5,6 +5,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
5
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
6
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
7
7
  import { type AccountAvatar, type AccountView } from "./account-avatar.js";
8
+ import type { Preferences } from "./me.schemas.js";
8
9
  import { SuperAdminLock } from "./super-admin.js";
9
10
  export interface Account {
10
11
  id: string;
@@ -118,12 +119,12 @@ export declare class AccountsService {
118
119
  /**
119
120
  * A person's preferences: `timeZone` is their time zone setting (IANA), null = follow the browser
120
121
  * (run context spec §3.4); `theme` their theme (a `platform_themes` id), null = follow the org
121
- * (themes spec §7). Missing account -> nulls.
122
+ * (themes spec §7); `idleCompaction` "off" = never compact their conversations while idle, null =
123
+ * follow the org (idle compaction spec §6.3). Missing account -> nulls.
122
124
  */
123
- preferences(accountId: string): Promise<{
124
- timeZone: string | null;
125
- theme: string | null;
126
- }>;
125
+ preferences(accountId: string): Promise<Preferences>;
126
+ /** Whether the person turned idle compaction off (the runtime's check; `accounts` has no org). */
127
+ idleCompactionOff(accountId: string): Promise<boolean>;
127
128
  /**
128
129
  * Updates the preferences given (a field left out keeps its value; the caller validated the time
129
130
  * zone). A theme must be on in at least one of the person's orgs, else 400 `theme.not_available`.
@@ -131,10 +132,8 @@ export declare class AccountsService {
131
132
  setPreferences(accountId: string, prefs: {
132
133
  timeZone?: string | null | undefined;
133
134
  theme?: string | null | undefined;
134
- }): Promise<{
135
- timeZone: string | null;
136
- theme: string | null;
137
- }>;
135
+ idleCompaction?: "off" | null | undefined;
136
+ }): Promise<Preferences>;
138
137
  /** 按 id 升序分页,`after` 为上一页最后一个 id。 */
139
138
  list(opts: {
140
139
  limit: number;
@@ -260,15 +260,29 @@ let AccountsService = class AccountsService {
260
260
  /**
261
261
  * A person's preferences: `timeZone` is their time zone setting (IANA), null = follow the browser
262
262
  * (run context spec §3.4); `theme` their theme (a `platform_themes` id), null = follow the org
263
- * (themes spec §7). Missing account -> nulls.
263
+ * (themes spec §7); `idleCompaction` "off" = never compact their conversations while idle, null =
264
+ * follow the org (idle compaction spec §6.3). Missing account -> nulls.
264
265
  */
265
266
  async preferences(accountId) {
266
267
  const row = await this.db
267
268
  .selectFrom("accounts")
268
- .select(["time_zone", "theme"])
269
+ .select(["time_zone", "theme", "idle_compaction"])
269
270
  .where("id", "=", accountId)
270
271
  .executeTakeFirst();
271
- return { timeZone: row?.time_zone ?? null, theme: row?.theme ?? null };
272
+ return {
273
+ timeZone: row?.time_zone ?? null,
274
+ theme: row?.theme ?? null,
275
+ idleCompaction: row?.idle_compaction ?? null,
276
+ };
277
+ }
278
+ /** Whether the person turned idle compaction off (the runtime's check; `accounts` has no org). */
279
+ async idleCompactionOff(accountId) {
280
+ const row = await this.db
281
+ .selectFrom("accounts")
282
+ .select("idle_compaction")
283
+ .where("id", "=", accountId)
284
+ .executeTakeFirst();
285
+ return row?.idle_compaction === "off";
272
286
  }
273
287
  /**
274
288
  * Updates the preferences given (a field left out keeps its value; the caller validated the time
@@ -280,6 +294,7 @@ let AccountsService = class AccountsService {
280
294
  const set = {
281
295
  ...(prefs.timeZone !== undefined && { time_zone: prefs.timeZone }),
282
296
  ...(prefs.theme !== undefined && { theme: prefs.theme }),
297
+ ...(prefs.idleCompaction !== undefined && { idle_compaction: prefs.idleCompaction }),
283
298
  };
284
299
  if (Object.keys(set).length > 0) {
285
300
  await this.db
@@ -72,12 +72,14 @@ export declare class MeController {
72
72
  /**
73
73
  * The person's preferences: `timeZone` null = follow the browser's time zone sent with each
74
74
  * message, a set zone overrides it for the messages sent afterwards (run context spec §3.4);
75
- * `theme` null = follow the org (themes spec §7).
75
+ * `theme` null = follow the org (themes spec §7); `idleCompaction` "off" = never compact this
76
+ * person's conversations while idle, null = follow the org (idle compaction spec §6.3).
76
77
  */
77
78
  preferences(principal: Principal): Promise<Preferences>;
78
79
  /**
79
80
  * Updates the preferences given; a field left out keeps its value. An unknown time zone → 400
80
- * `validation_failed`; a theme on in none of the person's orgs → 400 `theme.not_available`.
81
+ * `validation_failed`; a theme on in none of the person's orgs → 400 `theme.not_available`;
82
+ * `idleCompaction` accepts only "off" or null (anything else → 400 `validation_failed`).
81
83
  */
82
84
  setPreferences(principal: Principal, body: z.infer<typeof PreferencesSchema>): Promise<Preferences>;
83
85
  /** 切换当前组织(仅 Web 会话);`null` 清空。非成员或已软删除的组织 → `org.not_found`。 */
@@ -114,14 +114,16 @@ let MeController = class MeController {
114
114
  /**
115
115
  * The person's preferences: `timeZone` null = follow the browser's time zone sent with each
116
116
  * message, a set zone overrides it for the messages sent afterwards (run context spec §3.4);
117
- * `theme` null = follow the org (themes spec §7).
117
+ * `theme` null = follow the org (themes spec §7); `idleCompaction` "off" = never compact this
118
+ * person's conversations while idle, null = follow the org (idle compaction spec §6.3).
118
119
  */
119
120
  async preferences(principal) {
120
121
  return this.accounts.preferences(requireUser(principal).account.id);
121
122
  }
122
123
  /**
123
124
  * Updates the preferences given; a field left out keeps its value. An unknown time zone → 400
124
- * `validation_failed`; a theme on in none of the person's orgs → 400 `theme.not_available`.
125
+ * `validation_failed`; a theme on in none of the person's orgs → 400 `theme.not_available`;
126
+ * `idleCompaction` accepts only "off" or null (anything else → 400 `validation_failed`).
125
127
  */
126
128
  async setPreferences(principal, body) {
127
129
  return this.accounts.setPreferences(requireUser(principal).account.id, body);
@@ -7,15 +7,18 @@ import type { RouteSchemas } from "../platform/route-schemas.js";
7
7
  export declare const PreferencesSchema: z.ZodObject<{
8
8
  timeZone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
9
  theme: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
+ idleCompaction: z.ZodOptional<z.ZodNullable<z.ZodLiteral<"off">>>;
10
11
  }, z.core.$strict>;
11
12
  /** The person's preferences as `GET` / `PUT /me/preferences` return them. */
12
13
  export interface Preferences {
13
14
  timeZone: string | null;
14
15
  theme: string | null;
16
+ idleCompaction: "off" | null;
15
17
  }
16
18
  declare const PreferencesBody_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
17
19
  timeZone: z.ZodOptional<z.ZodNullable<z.ZodString>>;
18
20
  theme: z.ZodOptional<z.ZodNullable<z.ZodString>>;
21
+ idleCompaction: z.ZodOptional<z.ZodNullable<z.ZodLiteral<"off">>>;
19
22
  }, z.core.$strict>>;
20
23
  export declare class PreferencesBody extends PreferencesBody_base {
21
24
  }
@@ -14,6 +14,11 @@ export const PreferencesSchema = z
14
14
  * `theme.not_available`); null = follow the org (themes spec §7).
15
15
  */
16
16
  theme: z.string().min(1).max(200).nullable().optional(),
17
+ /**
18
+ * Idle compaction spec §6.3: off = never compact this person's conversations while idle;
19
+ * null = follow the org. A narrowing only: it cannot turn the feature on.
20
+ */
21
+ idleCompaction: z.literal("off").nullable().optional(),
17
22
  })
18
23
  .strict();
19
24
  export class PreferencesBody extends createZodDto(PreferencesSchema, "PreferencesBody") {
@@ -87,6 +87,9 @@ export declare const COMPACTION_SETTINGS: z.ZodObject<{
87
87
  keepRecentTurns: z.ZodDefault<z.ZodNumber>;
88
88
  reserveTokens: z.ZodDefault<z.ZodNumber>;
89
89
  maxOutputTokens: z.ZodDefault<z.ZodNumber>;
90
+ idleEnabled: z.ZodDefault<z.ZodBoolean>;
91
+ idleMinTokensFloor: z.ZodDefault<z.ZodNumber>;
92
+ idleMinWindowRatio: z.ZodDefault<z.ZodNumber>;
90
93
  }, z.core.$strip>;
91
94
  export type CompactionSettings = z.infer<typeof COMPACTION_SETTINGS>;
92
95
  /**
@@ -100,6 +103,9 @@ export declare const COMPACTION_SETTINGS_PARTIAL: z.ZodObject<{
100
103
  keepRecentTurns: z.ZodOptional<z.ZodNumber>;
101
104
  reserveTokens: z.ZodOptional<z.ZodNumber>;
102
105
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
106
+ idleEnabled: z.ZodOptional<z.ZodBoolean>;
107
+ idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
108
+ idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
103
109
  }, z.core.$strip>;
104
110
  /**
105
111
  * The patch form both settings writers take: the partial form above, strict, so a misspelled
@@ -112,6 +118,9 @@ export declare const COMPACTION_SETTINGS_PATCH: z.ZodObject<{
112
118
  keepRecentTurns: z.ZodOptional<z.ZodNumber>;
113
119
  reserveTokens: z.ZodOptional<z.ZodNumber>;
114
120
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
121
+ idleEnabled: z.ZodOptional<z.ZodBoolean>;
122
+ idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
123
+ idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
115
124
  }, z.core.$strict>;
116
125
  export type CompactionSettingsPatch = z.infer<typeof COMPACTION_SETTINGS_PARTIAL>;
117
126
  /**
@@ -177,6 +186,9 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
177
186
  keepRecentTurns: z.ZodDefault<z.ZodNumber>;
178
187
  reserveTokens: z.ZodDefault<z.ZodNumber>;
179
188
  maxOutputTokens: z.ZodDefault<z.ZodNumber>;
189
+ idleEnabled: z.ZodDefault<z.ZodBoolean>;
190
+ idleMinTokensFloor: z.ZodDefault<z.ZodNumber>;
191
+ idleMinWindowRatio: z.ZodDefault<z.ZodNumber>;
180
192
  }, z.core.$strip>>;
181
193
  promptCache: z.ZodPrefault<z.ZodObject<{
182
194
  longTtl: z.ZodDefault<z.ZodBoolean>;
@@ -284,6 +296,9 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
284
296
  keepRecentTurns: z.ZodOptional<z.ZodNumber>;
285
297
  reserveTokens: z.ZodOptional<z.ZodNumber>;
286
298
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
299
+ idleEnabled: z.ZodOptional<z.ZodBoolean>;
300
+ idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
301
+ idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
287
302
  }, z.core.$strict>>;
288
303
  promptCache: z.ZodOptional<z.ZodObject<{
289
304
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -134,6 +134,9 @@ const COMPACTION_FIELDS = {
134
134
  keepRecentTurns: z.number().int().min(0).max(20),
135
135
  reserveTokens: z.number().int().min(0).max(50_000),
136
136
  maxOutputTokens: z.number().int().min(1024).max(32_000),
137
+ idleEnabled: z.boolean(),
138
+ idleMinTokensFloor: z.number().int().min(50_000).max(2_000_000),
139
+ idleMinWindowRatio: z.number().min(0.1).max(0.9),
137
140
  };
138
141
  /**
139
142
  * Conversation compaction (context compaction spec §4.8): the platform's defaults and the bounds
@@ -147,6 +150,9 @@ export const COMPACTION_SETTINGS = z.object({
147
150
  keepRecentTurns: COMPACTION_FIELDS.keepRecentTurns.default(4),
148
151
  reserveTokens: COMPACTION_FIELDS.reserveTokens.default(8000),
149
152
  maxOutputTokens: COMPACTION_FIELDS.maxOutputTokens.default(20_000),
153
+ idleEnabled: COMPACTION_FIELDS.idleEnabled.default(true),
154
+ idleMinTokensFloor: COMPACTION_FIELDS.idleMinTokensFloor.default(200_000),
155
+ idleMinWindowRatio: COMPACTION_FIELDS.idleMinWindowRatio.default(0.3),
150
156
  });
151
157
  /**
152
158
  * The partial form the platform and org patches carry: only the given fields, validated against
@@ -171,6 +177,9 @@ export function effectiveCompactionSettings(platform, org) {
171
177
  keepRecentTurns: org?.keepRecentTurns ?? platform.keepRecentTurns,
172
178
  reserveTokens: org?.reserveTokens ?? platform.reserveTokens,
173
179
  maxOutputTokens: org?.maxOutputTokens ?? platform.maxOutputTokens,
180
+ idleEnabled: org?.idleEnabled ?? platform.idleEnabled,
181
+ idleMinTokensFloor: org?.idleMinTokensFloor ?? platform.idleMinTokensFloor,
182
+ idleMinWindowRatio: org?.idleMinWindowRatio ?? platform.idleMinWindowRatio,
174
183
  };
175
184
  }
176
185
  /**
@@ -870,6 +879,9 @@ let SettingsService = class SettingsService {
870
879
  keepRecentTurns: compactionPatch.keepRecentTurns ?? current.compaction.keepRecentTurns,
871
880
  reserveTokens: compactionPatch.reserveTokens ?? current.compaction.reserveTokens,
872
881
  maxOutputTokens: compactionPatch.maxOutputTokens ?? current.compaction.maxOutputTokens,
882
+ idleEnabled: compactionPatch.idleEnabled ?? current.compaction.idleEnabled,
883
+ idleMinTokensFloor: compactionPatch.idleMinTokensFloor ?? current.compaction.idleMinTokensFloor,
884
+ idleMinWindowRatio: compactionPatch.idleMinWindowRatio ?? current.compaction.idleMinWindowRatio,
873
885
  };
874
886
  }
875
887
  if (promptCachePatch !== undefined) {
@@ -330,6 +330,20 @@ export declare const OUTBOX_JOBS: {
330
330
  readonly removeOnFail: true;
331
331
  };
332
332
  };
333
+ readonly "idle-compaction": {
334
+ readonly queue: "cap-kernel-maintenance";
335
+ readonly idempotent: "the job re-reads the conversation and starts at most one idle compact run under the conversation row lock, only while no event other than a run-less side-call usage follows armedSeq; a duplicate delivery finds the first delivery's run_started or its active compact run and does nothing";
336
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
337
+ readonly opts: {
338
+ readonly attempts: 2;
339
+ readonly backoff: {
340
+ readonly type: "fixed";
341
+ readonly delay: 5000;
342
+ };
343
+ readonly removeOnComplete: true;
344
+ readonly removeOnFail: true;
345
+ };
346
+ };
333
347
  readonly "usage-report": {
334
348
  readonly queue: "cap-kernel-usage-report";
335
349
  readonly idempotent: "handlers are idempotent by eventId (the event's `<conversationId>/<seq>` or the model_usage row id), and the job's `pending` list keeps a retry from reaching plugins already served";
@@ -284,6 +284,20 @@ export const OUTBOX_JOBS = {
284
284
  removeOnFail: true,
285
285
  },
286
286
  },
287
+ // `runtime/idle-compaction-jobs.ts` IDLE_COMPACTION_JOB: owed by the terminal transaction of a
288
+ // chat run that passed the arm decision (`RunFinish.finishIn`), under `idleCompactionJobId`, with
289
+ // `runAt` shortly before the run's prompt cache expires (idle compaction spec §4.2, S4)
290
+ "idle-compaction": {
291
+ queue: "cap-kernel-maintenance",
292
+ idempotent: "the job re-reads the conversation and starts at most one idle compact run under the conversation row lock, only while no event other than a run-less side-call usage follows armedSeq; a duplicate delivery finds the first delivery's run_started or its active compact run and does nothing",
293
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
294
+ opts: {
295
+ attempts: 2,
296
+ backoff: { type: "fixed", delay: 5_000 },
297
+ removeOnComplete: true,
298
+ removeOnFail: true,
299
+ },
300
+ },
287
301
  // `runtime/usage-report-jobs.ts` USAGE_REPORT_JOB: owed with the usage it reports (a `usage`
288
302
  // event or a `model_usage` row) while some plugin subscribes, under `usageReportJobId` /
289
303
  // `modelUsageJobId` (spec §8.1)
@@ -264,6 +264,9 @@ export declare const OrgSettingsSchema: z.ZodObject<{
264
264
  keepRecentTurns: z.ZodOptional<z.ZodNumber>;
265
265
  reserveTokens: z.ZodOptional<z.ZodNumber>;
266
266
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
267
+ idleEnabled: z.ZodOptional<z.ZodBoolean>;
268
+ idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
269
+ idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
267
270
  }, z.core.$strip>>>;
268
271
  promptCache: z.ZodCatch<z.ZodOptional<z.ZodObject<{
269
272
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -378,6 +381,9 @@ export declare const OrgSettingsPatchSchema: z.ZodObject<{
378
381
  keepRecentTurns: z.ZodOptional<z.ZodNumber>;
379
382
  reserveTokens: z.ZodOptional<z.ZodNumber>;
380
383
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
384
+ idleEnabled: z.ZodOptional<z.ZodBoolean>;
385
+ idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
386
+ idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
381
387
  }, z.core.$strict>>>;
382
388
  promptCache: z.ZodOptional<z.ZodNullable<z.ZodObject<{
383
389
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -57,7 +57,7 @@ let OrgSettingsOperations = class OrgSettingsOperations {
57
57
  }),
58
58
  defineOperation({
59
59
  id: "org-settings.update",
60
- description: "Change this org's settings (org admins). Give only the settings to change; null clears outsideSandbox, deviceNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). outsideSandbox (allowed or off; the platform must allow it) and deviceNetwork ({ default?, ceiling?: open | allowlist, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep; neither default nor ceiling may be open where the platform's ceiling is allowlist, and the default may not be above the ceiling) may only narrow the org's devices here: allowing outside-sandbox runs where the org has them off, opening the default or the ceiling, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. navigation: { pluginPages: [{ contribution: <extension>/<contribution>, section: primary or more }] } replaces where the org's plugin pages sit in the navigation (at most 3 primary, so send the whole list you keep); null clears it. externalSharing (on or off; null clears it, off) may only be turned off through this tool: turning it on needs a person in the organization settings on the web, and the platform must allow it. promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) may be set either way through this tool. compaction ({ enabled?, threshold? (0.5 to 0.95), keepRecentTurns? (0 to 20), reserveTokens? (0 to 50000), maxOutputTokens? (1024 to 32000) }: the org's conversation compaction overrides, merged into the stored fields; null clears the override so the org follows the platform) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; null clears it so the org follows the platform) may be set either way. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org; an org admin switches it back on in the web settings.",
60
+ description: "Change this org's settings (org admins). Give only the settings to change; null clears outsideSandbox, deviceNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). outsideSandbox (allowed or off; the platform must allow it) and deviceNetwork ({ default?, ceiling?: open | allowlist, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep; neither default nor ceiling may be open where the platform's ceiling is allowlist, and the default may not be above the ceiling) may only narrow the org's devices here: allowing outside-sandbox runs where the org has them off, opening the default or the ceiling, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. navigation: { pluginPages: [{ contribution: <extension>/<contribution>, section: primary or more }] } replaces where the org's plugin pages sit in the navigation (at most 3 primary, so send the whole list you keep); null clears it. externalSharing (on or off; null clears it, off) may only be turned off through this tool: turning it on needs a person in the organization settings on the web, and the platform must allow it. promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) may be set either way through this tool. compaction ({ enabled?, threshold? (0.5 to 0.95), keepRecentTurns? (0 to 20), reserveTokens? (0 to 50000), maxOutputTokens? (1024 to 32000), idleEnabled? (compact idle conversations before a cache of 30 minutes or more expires), idleMinTokensFloor? (50000 to 2000000), idleMinWindowRatio? (0.1 to 0.9) }: the org's conversation compaction overrides, merged into the stored fields; null clears the override so the org follows the platform) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; null clears it so the org follows the platform) may be set either way. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org; an org admin switches it back on in the web settings.",
61
61
  input: OrgSettingsPatchSchema.refine((i) => Object.values(i).some((v) => v !== undefined), {
62
62
  message: "give at least one setting",
63
63
  }),
@@ -196,7 +196,7 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
196
196
  }),
197
197
  defineOperation({
198
198
  id: "platform.preferences",
199
- description: "Read your own preferences: your time zone (an IANA name such as Asia/Shanghai, or null when it follows the time zone of the browser you send messages from; the run context already tells you the zone in effect for this message) and your theme (a theme id, or null when you follow the org's theme; themes.list names them).",
199
+ description: 'Read your own preferences: your time zone (an IANA name such as Asia/Shanghai, or null when it follows the time zone of the browser you send messages from; the run context already tells you the zone in effect for this message), your theme (a theme id, or null when you follow the org\'s theme; themes.list names them) and idleCompaction ("off" when you turned off compacting your conversations while they sit idle, or null when you follow the org).',
200
200
  input: EMPTY,
201
201
  example: {},
202
202
  // any signed-in person may call the route; every run's actor is a member of this org
@@ -207,9 +207,9 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
207
207
  }),
208
208
  defineOperation({
209
209
  id: "platform.set-preferences",
210
- description: "Change your own preferences; give only the ones to change, the others keep their values. timeZone: an IANA name such as Europe/Berlin, or null to follow the time zone of the browser you send messages from; it applies to the messages you send afterwards, on the web and in IM (the current run keeps its zone). theme: a theme id from themes.list (it applies in every org where that theme is on and personal picks are allowed), or null to follow the org's theme.",
210
+ description: 'Change your own preferences; give only the ones to change, the others keep their values. timeZone: an IANA name such as Europe/Berlin, or null to follow the time zone of the browser you send messages from; it applies to the messages you send afterwards, on the web and in IM (the current run keeps its zone). theme: a theme id from themes.list (it applies in every org where that theme is on and personal picks are allowed), or null to follow the org\'s theme. idleCompaction: "off" to never compact your conversations while they sit idle, or null to follow the org (it can only turn the feature off, never on).',
211
211
  input: PreferencesSchema.refine((i) => Object.values(i).some((v) => v !== undefined), {
212
- message: "give timeZone, theme or both",
212
+ message: "give at least one of timeZone, theme, idleCompaction",
213
213
  }),
214
214
  example: { timeZone: "Asia/Shanghai" },
215
215
  authz: { orgAction: "agents.use" },
@@ -249,11 +249,17 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
249
249
  zh.push(`把你的主题从「${inZh(from)}」改为「${inZh(to)}」`);
250
250
  en.push(`Change your theme from "${inEn(from)}" to "${inEn(to)}"`);
251
251
  }
252
+ if (input.idleCompaction !== undefined) {
253
+ const label = (v, off, org) => (v === "off" ? off : org);
254
+ zh.push(`把你的空闲压缩从「${label(now.idleCompaction, "关闭", "跟随组织")}」改为「${label(input.idleCompaction, "关闭", "跟随组织")}」`);
255
+ en.push(`Change your idle compaction from "${label(now.idleCompaction, "off", "follow the org")}" to "${label(input.idleCompaction, "off", "follow the org")}"`);
256
+ }
252
257
  return { zh: zh.join(";"), en: en.join("; ") };
253
258
  },
254
259
  run: async (input, ctx) => this.accounts.setPreferences(ctx.actorAccountId, {
255
260
  timeZone: input.timeZone,
256
261
  theme: input.theme,
262
+ idleCompaction: input.idleCompaction,
257
263
  }),
258
264
  }),
259
265
  defineOperation({
@@ -173,11 +173,13 @@ async function resolveConversation(db, conversationId, seq) {
173
173
  return null;
174
174
  const run = await db
175
175
  .selectFrom("runs")
176
- .select("automation_run_id")
176
+ .select(["automation_run_id", "compact_origin"])
177
177
  .where("id", "=", event.run_id)
178
178
  .where("conversation_id", "=", conversationId)
179
179
  .executeTakeFirst();
180
- if (!run || run.automation_run_id !== null)
180
+ // an automation's run is pushed by the automation; an idle compaction ran after the person
181
+ // left and answered nobody (idle compaction spec §6): neither pushes a reply
182
+ if (!run || run.automation_run_id !== null || run.compact_origin === "idle")
181
183
  return null;
182
184
  candidates = [owner];
183
185
  break;
@@ -7,10 +7,16 @@ export declare const RUN_ABORT_TOPIC = "run.abort";
7
7
  * its parent's sub-agents wait timeout. Written to `run_aborted.detail`.
8
8
  */
9
9
  export type RunAbortDetail = "wait_timeout";
10
+ /**
11
+ * The kernel's reason for a stop other than a person's: `superseded`, an idle compact run preempted
12
+ * by input (idle compaction spec §5.2). Written to `run_aborted.reason`; absent = `user`.
13
+ */
14
+ export type RunAbortReason = "superseded";
10
15
  /** Who stopped a run, and why when the kernel did. */
11
16
  export interface RunAbortBy {
12
17
  byAccountId: string | null;
13
18
  detail?: RunAbortDetail;
19
+ reason?: RunAbortReason;
14
20
  }
15
21
  /**
16
22
  * 跨副本中止(spec 4.3「中止信号经 Redis 广播」):`request` 先写标记键再广播;
@@ -20,13 +26,26 @@ export declare class RunAbort {
20
26
  private readonly redis;
21
27
  private readonly bus;
22
28
  constructor(redis: Redis, bus: ExtensionContext["bus"]);
23
- request(runId: string, byAccountId: string | null, detail?: RunAbortDetail): Promise<void>;
29
+ request(runId: string, byAccountId: string | null, opts?: {
30
+ detail?: RunAbortDetail | undefined;
31
+ reason?: RunAbortReason | undefined;
32
+ }): Promise<void>;
33
+ /**
34
+ * Requests the kernel's stop of a run only when no stop was requested yet: the marker is written
35
+ * with SET NX (atomic, so a person's stop racing it is never relabelled) and broadcast only when
36
+ * this call wrote it. True when it did. A plain {@link request} still overwrites the marker, so a
37
+ * person's later stop replaces a kernel one.
38
+ */
39
+ requestIfAbsent(runId: string, byAccountId: string | null, opts?: {
40
+ detail?: RunAbortDetail | undefined;
41
+ reason?: RunAbortReason | undefined;
42
+ }): Promise<boolean>;
24
43
  /**
25
44
  * Whether a stop of this run was requested (reads the marker key): who asked (and why, when the
26
- * kernel did), or null. For the moments without a subscriber (a run that just suspended and is
45
+ * kernel did: `detail`, `reason`), or null. For the moments without a subscriber (a run that just suspended and is
27
46
  * about to become `waiting`), to pick up a stop that arrived meanwhile.
28
47
  */
29
48
  requested(runId: string): Promise<RunAbortBy | null>;
30
49
  /** Subscribes to stops of one run; `onAbort` is called at most once. Returns the unsubscribe. */
31
- watch(runId: string, onAbort: (byAccountId: string | null, detail?: RunAbortDetail) => void): Promise<() => Promise<void>>;
50
+ watch(runId: string, onAbort: (byAccountId: string | null, detail?: RunAbortDetail, reason?: RunAbortReason) => void): Promise<() => Promise<void>>;
32
51
  }