@capybara-hq/kernel 0.1.0-rc.29 → 0.1.0-rc.30

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 (62) hide show
  1. package/bootstrap.json +27 -27
  2. package/dist/admin/admin.schemas.d.ts +7 -0
  3. package/dist/config/schema.d.ts +0 -2
  4. package/dist/config/schema.js +0 -16
  5. package/dist/conversations/conversations.controller.d.ts +11 -1
  6. package/dist/conversations/conversations.controller.js +25 -1
  7. package/dist/conversations/conversations.schemas.d.ts +8 -0
  8. package/dist/conversations/conversations.schemas.js +14 -0
  9. package/dist/conversations/conversations.service.d.ts +12 -0
  10. package/dist/conversations/conversations.service.js +10 -0
  11. package/dist/conversations/event-log.d.ts +14 -0
  12. package/dist/conversations/events.d.ts +12 -0
  13. package/dist/conversations/events.js +35 -3
  14. package/dist/db/kernel-schema.d.ts +5 -0
  15. package/dist/errors.d.ts +3 -0
  16. package/dist/errors.js +3 -0
  17. package/dist/evals/plan.d.ts +20 -15
  18. package/dist/evals/plan.js +29 -6
  19. package/dist/evals/reconstruct.d.ts +16 -1
  20. package/dist/evals/reconstruct.js +55 -1
  21. package/dist/evals/sets.service.d.ts +3 -2
  22. package/dist/evals/sets.service.js +16 -2
  23. package/dist/evals/step-replay.d.ts +6 -0
  24. package/dist/evals/step-replay.js +5 -0
  25. package/dist/evals/trajectory.d.ts +5 -1
  26. package/dist/evals/trajectory.js +3 -1
  27. package/dist/evals/worker.js +2 -1
  28. package/dist/identity/settings.d.ts +64 -0
  29. package/dist/identity/settings.js +86 -2
  30. package/dist/orgs/roles.d.ts +1 -1
  31. package/dist/orgs/roles.js +2 -0
  32. package/dist/orgs/settings.service.d.ts +17 -0
  33. package/dist/orgs/settings.service.js +31 -3
  34. package/dist/platform/ops/admin.ops.js +8 -2
  35. package/dist/platform/ops/conversations.ops.js +34 -0
  36. package/dist/platform/ops/evals.ops.js +12 -1
  37. package/dist/platform/ops/orgs.ops.js +1 -0
  38. package/dist/runtime/compaction-progress.d.ts +62 -0
  39. package/dist/runtime/compaction-progress.js +82 -0
  40. package/dist/runtime/compaction-settings.service.d.ts +16 -0
  41. package/dist/runtime/compaction-settings.service.js +42 -0
  42. package/dist/runtime/compaction.service.d.ts +50 -0
  43. package/dist/runtime/compaction.service.js +75 -0
  44. package/dist/runtime/context/compaction.d.ts +90 -12
  45. package/dist/runtime/context/compaction.js +256 -21
  46. package/dist/runtime/context/fit.d.ts +79 -0
  47. package/dist/runtime/context/fit.js +202 -0
  48. package/dist/runtime/model-call.d.ts +134 -5
  49. package/dist/runtime/model-call.js +766 -335
  50. package/dist/runtime/run-control.d.ts +6 -1
  51. package/dist/runtime/run-control.js +7 -0
  52. package/dist/runtime/run-queue.d.ts +14 -0
  53. package/dist/runtime/run-queue.js +75 -0
  54. package/dist/runtime/run-steps.d.ts +3 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.d.ts +14 -2
  57. package/dist/runtime/run-worker.js +160 -33
  58. package/dist/runtime/runtime.module.js +11 -0
  59. package/dist/runtime/stream.js +15 -0
  60. package/dist/tools/pipeline.js +6 -3
  61. package/package.json +1 -1
  62. package/src/migrations/0132_compact_runs.sql +6 -0
package/bootstrap.json CHANGED
@@ -3,111 +3,111 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "4bfd588739e5cec6f2177d4e8f72e43a4dae50f3"
6
+ "commit": "ce9c71ed59616520447edda01117252dfbc45680"
7
7
  },
8
8
  "plugins": [
9
9
  {
10
10
  "name": "openai-compatible",
11
11
  "source": "npm",
12
12
  "npm": "@capybara-hq/plugin-openai-compatible",
13
- "version": "0.1.0-rc.8",
14
- "integrity": "sha512-IDINuU0r2JONeoEneACLhqnIeDCHX0AICaUJd8TeVmCbzsjMPlchTXngFQin66UN3jqi92yhFDGMKixLsArVCA==",
13
+ "version": "0.1.0-rc.10",
14
+ "integrity": "sha512-Xqvl9tDGZhuLzXEEuEAoz+pZdtRg3baoLz1fjs1DQvEropXVQeF9LwV3dkfj/XF2cpRLBTMyZdxdzqebczl67A==",
15
15
  "required": true
16
16
  },
17
17
  {
18
18
  "name": "object-store-s3",
19
19
  "source": "npm",
20
20
  "npm": "@capybara-hq/plugin-object-store-s3",
21
- "version": "0.1.0-rc.7",
22
- "integrity": "sha512-7HHh45e2CiMxQVfMEKexdRkT7k2iUqznNWMEVazzd+rhT4tguLVY8TkWClv4EK246fqVXvnj48rmmL6Dd6oTvw==",
21
+ "version": "0.1.0-rc.9",
22
+ "integrity": "sha512-yqW5gM5+4sdY/nJWDyu7ltDLdUm6b4q9+R/yrCLJhMRCI7HQbxeqDWky29EiDjjsJD5BaiQ6N3a5Ua75ANll7g==",
23
23
  "required": true
24
24
  },
25
25
  {
26
26
  "name": "anthropic",
27
27
  "source": "npm",
28
28
  "npm": "@capybara-hq/plugin-anthropic",
29
- "version": "0.1.0-rc.7",
30
- "integrity": "sha512-yjUyDqJppihZmhgLVomFbhf1Iek31xyJ4W4+It4Dy3K4wsyZV9khhWrm9x1xxtcb1RvDIGgUxRmvLgoTIeUTYQ==",
29
+ "version": "0.1.0-rc.8",
30
+ "integrity": "sha512-QWUE8TboL2zV5QVLSksb38Re+3bOoWy9zJUW/CxH2WZ7VQUhvt5hc+3cO5eVNkA7zopRh3W8xxnT8dxuPQPixA==",
31
31
  "required": false
32
32
  },
33
33
  {
34
34
  "name": "openai",
35
35
  "source": "npm",
36
36
  "npm": "@capybara-hq/plugin-openai",
37
- "version": "0.1.0-rc.8",
38
- "integrity": "sha512-n8IRL9u+yxmtd/aEntgSdTswjTDdhn2tjXTN9FWARGI+dTQnsbkX9108P4T31kmOBVcuwPYzNB09NG+im2LQIg==",
37
+ "version": "0.1.0-rc.9",
38
+ "integrity": "sha512-P0mCs/tQBRFfb9WrVo+AaFlGgu/LLpSajYbnaz6mXZpYL6cs7H0D+eFM3ogI3PUNXQHQuJ4NRI99ylYlkRd8PQ==",
39
39
  "required": false
40
40
  },
41
41
  {
42
42
  "name": "deepseek",
43
43
  "source": "npm",
44
44
  "npm": "@capybara-hq/plugin-deepseek",
45
- "version": "0.1.0-rc.7",
46
- "integrity": "sha512-f0kYjYzvwxPtT2bnpf7fYkggMHvlLTJX7bacaWnIoR1cHeTxiNKuvOv8ptkztpkgTmKadjKqllI5b9AOhhILRg==",
45
+ "version": "0.1.0-rc.8",
46
+ "integrity": "sha512-ILqGaQ9P7OvNLTohBHNK6PlWf4vakVUOmdqJKBiWTskVTFD0XqBMiBGxcCaU7Fu1WeDfwIcQZv3lN4Y69KrMHQ==",
47
47
  "required": false
48
48
  },
49
49
  {
50
50
  "name": "bailian",
51
51
  "source": "npm",
52
52
  "npm": "@capybara-hq/plugin-bailian",
53
- "version": "0.1.0-rc.7",
54
- "integrity": "sha512-VqTq6mjzka+iEW5BdcZspBdkWSQ1mLsLueg/XABaZzNDEAE/a6ErDE10GadzOTzorqAttXebTLJDjJebgLmtwA==",
53
+ "version": "0.1.0-rc.8",
54
+ "integrity": "sha512-/z9Kf2UxN+8/qtfjijtXtVk0A2qbes8yaT7oyB5Mv5r4xATUACCczBa6ct2/dbY6avxNQMv8O53IZzsexSdpfg==",
55
55
  "required": false
56
56
  },
57
57
  {
58
58
  "name": "ark",
59
59
  "source": "npm",
60
60
  "npm": "@capybara-hq/plugin-ark",
61
- "version": "0.1.0-rc.7",
62
- "integrity": "sha512-Ml/HS3w3fD4x0gh/Yh0jbz8Riv8x7Jkd5phPZUsKDtuE4pvr+hllRYOxs9p0/Lax11BDvbUK9EFzRkCa+xAQeQ==",
61
+ "version": "0.1.0-rc.8",
62
+ "integrity": "sha512-pICTGWFpvX/1onDORPK3OtLGPsMCwbvbRAs3OnQzw+KBCGQC/LmNd9yWfDZ3T40IYMq+lXlLW0DUqFI5RzZ7LQ==",
63
63
  "required": false
64
64
  },
65
65
  {
66
66
  "name": "connector-mcp",
67
67
  "source": "npm",
68
68
  "npm": "@capybara-hq/plugin-connector-mcp",
69
- "version": "0.1.0-rc.7",
70
- "integrity": "sha512-hJlW+u1iLt/mKJ9iPBbGT6tbpGevPVTS+8dvLtPbpf2fFRhM2eLrQy6+zuKUhuVQCcJYBrpz4vu5vh1ZBkqNZg==",
69
+ "version": "0.1.0-rc.9",
70
+ "integrity": "sha512-UU+QL78lXkFciPMJqXWdt7DygzGC+OaYe/tvkQwLs+kJH2F786htXQBr7hbZnpGy6VfppSQWLB/w3cRHoR+RiA==",
71
71
  "required": false
72
72
  },
73
73
  {
74
74
  "name": "connector-openapi",
75
75
  "source": "npm",
76
76
  "npm": "@capybara-hq/plugin-connector-openapi",
77
- "version": "0.1.0-rc.8",
78
- "integrity": "sha512-2WU6sU0yAeWDy10DZ2I45uv2I6Q1FQDKvok2W0r6dfIO11G9iTsRNIMbtNsdVO2OUWY8nhAgh95BXBrpUELELQ==",
77
+ "version": "0.1.0-rc.10",
78
+ "integrity": "sha512-SA3lpZdy+pFhtGC59cPx1IsQtadzXh6jwpxlz3dhMsmNpfXHMDxEJymyy11W1Np8vL6dD+COo9kvzrbhEKBlnw==",
79
79
  "required": false
80
80
  },
81
81
  {
82
82
  "name": "jina",
83
83
  "source": "npm",
84
84
  "npm": "@capybara-hq/plugin-jina",
85
- "version": "0.1.0-rc.7",
86
- "integrity": "sha512-rpr59xbQJg+DuzhnAjn7Ql0rW9Cw9gKWHpER9nKvILvEYjEurmhniJkkqeHMnMlPba8lNUeQRGzmxdmLfKA10g==",
85
+ "version": "0.1.0-rc.8",
86
+ "integrity": "sha512-Z6Qggs79OfE7PPvkCudLXD3RiiYFT/slLiLJeleZEpn5A56rmk35tDU2EEBVfREQrRuLqjteTG0eQRSNpH4L9Q==",
87
87
  "required": false
88
88
  },
89
89
  {
90
90
  "name": "sandbox-docker",
91
91
  "source": "npm",
92
92
  "npm": "@capybara-hq/plugin-sandbox-docker",
93
- "version": "0.1.0-rc.12",
94
- "integrity": "sha512-c1iTAu/ifkwfnvVOsxEDfxEJNU7HDVewDtX4vdibwpodIhBvxz8tGjGYJ0HXDL3ipGEodiiIgJsVpabnMQ6cBQ==",
93
+ "version": "0.1.0-rc.14",
94
+ "integrity": "sha512-e64Re3gnU5uxQT/JH3mUolSyz0/Njen5CzMKl9brcsqouV7cY0sIjReLpnkBV0zNxmpMvK73WAO7OT7CZd5Kbg==",
95
95
  "required": false
96
96
  },
97
97
  {
98
98
  "name": "todo",
99
99
  "source": "npm",
100
100
  "npm": "@capybara-hq/plugin-todo",
101
- "version": "0.1.0-rc.8",
102
- "integrity": "sha512-xNdzvAmOQmBaDj29hsvbhMJINy2xe+ILTqG+cQhUfsyar7gUJaVOehseufvIq+cVbTjkI2tW7XlwGrtP3E3NtA==",
101
+ "version": "0.1.0-rc.10",
102
+ "integrity": "sha512-9sRVd7MaUsUF5Uk0EDsRqIae492TDEGjOcH5IM+SxTY2NcQCiXVs4ck/N6kRuV65x5LzVcrGLBfyx/Zi+2229w==",
103
103
  "required": false
104
104
  },
105
105
  {
106
106
  "name": "skills-core",
107
107
  "source": "npm",
108
108
  "npm": "@capybara-hq/plugin-skills-core",
109
- "version": "0.1.0-rc.0",
110
- "integrity": "sha512-U3R+B3QcklCQyye22bQU1aJq05oLW4Fr3hfmLHuPFOq5jNt30mDc0zNPSDLr6MFDdUI/OJkkX7wvkyKa+zRPAQ==",
109
+ "version": "0.1.0-rc.1",
110
+ "integrity": "sha512-eIad/YOTGMAjOQPEVrN6jfq/WHhpJUn5FifbELnFmRij1yo+mI4b/5/72DZ0cjsRXFWhUODen2IPmhYH/YZqWQ==",
111
111
  "required": false,
112
112
  "builtin": true
113
113
  }
@@ -69,6 +69,13 @@ export declare const DeploymentSettingsBody: z.ZodObject<{
69
69
  pr: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
70
  sessionUrl: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
71
71
  }, z.core.$strict>>;
72
+ compaction: z.ZodOptional<z.ZodObject<{
73
+ enabled: z.ZodOptional<z.ZodBoolean>;
74
+ threshold: z.ZodOptional<z.ZodNumber>;
75
+ keepRecentTurns: z.ZodOptional<z.ZodNumber>;
76
+ reserveTokens: z.ZodOptional<z.ZodNumber>;
77
+ maxOutputTokens: z.ZodOptional<z.ZodNumber>;
78
+ }, z.core.$strict>>;
72
79
  }, z.core.$strict>;
73
80
  export declare const PurposeParams: z.ZodObject<{
74
81
  purpose: z.ZodString;
@@ -125,8 +125,6 @@ export declare const KernelConfigSchema: z.ZodObject<{
125
125
  maxRunSeconds: z.ZodDefault<z.ZodNumber>;
126
126
  streamIdleMs: z.ZodDefault<z.ZodNumber>;
127
127
  maxOutputTokens: z.ZodDefault<z.ZodNumber>;
128
- compactionThreshold: z.ZodDefault<z.ZodNumber>;
129
- keepRecentTurns: z.ZodDefault<z.ZodNumber>;
130
128
  workerConcurrency: z.ZodDefault<z.ZodNumber>;
131
129
  orgConcurrency: z.ZodDefault<z.ZodNumber>;
132
130
  jobLockMs: z.ZodDefault<z.ZodNumber>;
@@ -609,20 +609,6 @@ export const KernelConfigSchema = z.object({
609
609
  .meta(meta({
610
610
  description: "Default output-token limit per model call when the agent does not set maxOutputTokens (an agent's maxOutputTokens overrides it; either is capped by the model's own maximum)",
611
611
  })),
612
- compactionThreshold: z
613
- .number()
614
- .gt(0)
615
- .max(1)
616
- .default(0.8)
617
- .meta(meta({
618
- description: "Compact the conversation when the estimated input reaches this fraction of the context window",
619
- })),
620
- keepRecentTurns: z
621
- .number()
622
- .int()
623
- .nonnegative()
624
- .default(4)
625
- .meta(meta({ description: "Number of recent user turns kept verbatim when compacting" })),
626
612
  workerConcurrency: z
627
613
  .number()
628
614
  .int()
@@ -677,8 +663,6 @@ export const KernelConfigSchema = z.object({
677
663
  maxRunSeconds: 0,
678
664
  streamIdleMs: 60000,
679
665
  maxOutputTokens: 16000,
680
- compactionThreshold: 0.8,
681
- keepRecentTurns: 4,
682
666
  workerConcurrency: 10,
683
667
  orgConcurrency: 10,
684
668
  jobLockMs: 30000,
@@ -6,7 +6,7 @@ import { type OrgContext } from "../orgs/org.guard.js";
6
6
  import { ConversationToolInfo, type ToolInfo } from "../tools/info.js";
7
7
  import type { AgentTreeNode } from "./agent-tree.js";
8
8
  import { type ArtifactPreview, ConversationArtifacts } from "./artifacts.js";
9
- import { EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery } from "./conversations.schemas.js";
9
+ import { CompactBody, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery } from "./conversations.schemas.js";
10
10
  import { type ConversationGroup, ConversationsService, type ConversationView, type SubagentView, type UsageTotals } from "./conversations.service.js";
11
11
  import { ConversationDeviceStatus } from "./device-status.js";
12
12
  import type { ConversationEvent } from "./events.js";
@@ -322,5 +322,15 @@ export declare class ConversationsController {
322
322
  abort(principal: Principal, org: OrgContext, id: string): Promise<{
323
323
  runId: string;
324
324
  }>;
325
+ /**
326
+ * Manual compaction (context compaction spec §4.7): starts a compact run that summarizes the
327
+ * conversation's earlier history and returns its id (`202 { runId }`); while one is queued or
328
+ * running the same run id comes back (the request is idempotent). Member and above, the caller's
329
+ * own chat conversation: an eval or someone else's is `conversation.not_found`, a sub-agent's is
330
+ * `conversation.read_only`, and an active ordinary run is `409 conversation.busy`.
331
+ */
332
+ compact(principal: Principal, org: OrgContext, { id }: z.infer<typeof IdParams>, _body: z.infer<typeof CompactBody>): Promise<{
333
+ runId: string;
334
+ }>;
325
335
  }
326
336
  export {};
@@ -17,7 +17,7 @@ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
17
17
  import { MAX_ATTACHMENTS } from "../tools/connector-content.js";
18
18
  import { ConversationToolInfo, TOOL_INFO_KEY_MAX, TOOL_INFO_MAX_KEYS, } from "../tools/info.js";
19
19
  import { ARTIFACT_DOWNLOAD_CACHE_SECONDS, ConversationArtifacts, } from "./artifacts.js";
20
- import { EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, searchFields, } from "./conversations.schemas.js";
20
+ import { CompactBody, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, searchFields, } from "./conversations.schemas.js";
21
21
  import { ConversationsService, } from "./conversations.service.js";
22
22
  import { ConversationDeviceStatus } from "./device-status.js";
23
23
  import { ConversationFiles, FILE_CONTENT_MAX_BYTES } from "./files.js";
@@ -159,6 +159,8 @@ class ConversationQueueBodyDto extends createZodDto(QueueBody, "ConversationQueu
159
159
  }
160
160
  class ConversationQueueEditBodyDto extends createZodDto(QueueEditBody, "ConversationQueueEditBody") {
161
161
  }
162
+ class ConversationCompactBodyDto extends createZodDto(CompactBody, "ConversationCompactBody") {
163
+ }
162
164
  /**
163
165
  * 会话(`/api/v1/orgs/:orgId/conversations`):`agents.use`(访客以上),只接受人类用户;
164
166
  * 服务令牌 → 403 `forbidden`。只有会话所有者可见,其他人一律 `conversation.not_found`。
@@ -467,6 +469,19 @@ let ConversationsController = class ConversationsController {
467
469
  const p = requireUser(principal);
468
470
  return { runId: await this.conversations.abort(org.orgId, id, p.account.id) };
469
471
  }
472
+ /**
473
+ * Manual compaction (context compaction spec §4.7): starts a compact run that summarizes the
474
+ * conversation's earlier history and returns its id (`202 { runId }`); while one is queued or
475
+ * running the same run id comes back (the request is idempotent). Member and above, the caller's
476
+ * own chat conversation: an eval or someone else's is `conversation.not_found`, a sub-agent's is
477
+ * `conversation.read_only`, and an active ordinary run is `409 conversation.busy`.
478
+ */
479
+ async compact(principal, org, { id },
480
+ // the body is validated for shape only: the queued/running compact run is the idempotency key
481
+ _body) {
482
+ const p = requireUser(principal);
483
+ return { runId: await this.conversations.compact(org.orgId, id, p.account.id) };
484
+ }
470
485
  };
471
486
  __decorate([
472
487
  Post(),
@@ -679,6 +694,15 @@ __decorate([
679
694
  __param(1, CurrentOrg()),
680
695
  __param(2, Param("id"))
681
696
  ], ConversationsController.prototype, "abort", null);
697
+ __decorate([
698
+ Post(":id/compact"),
699
+ HttpCode(202),
700
+ OrgAction("conversations.compact"),
701
+ __param(0, CurrentPrincipal()),
702
+ __param(1, CurrentOrg()),
703
+ __param(2, ZParam(ConversationIdParamsDto)),
704
+ __param(3, ZBody(ConversationCompactBodyDto))
705
+ ], ConversationsController.prototype, "compact", null);
682
706
  ConversationsController = __decorate([
683
707
  Controller("api/v1/orgs/:orgId/conversations"),
684
708
  __param(0, Inject(ConversationsService)),
@@ -40,6 +40,14 @@ export declare const PatchBody: z.ZodObject<{
40
40
  export declare const IdParams: z.ZodObject<{
41
41
  id: z.ZodString;
42
42
  }, z.core.$strip>;
43
+ /**
44
+ * `POST …/compact` (context compaction spec §4.7): the optional client request id only makes a
45
+ * transport retry identifiable; the compact run already queued/running is the idempotency key.
46
+ * Every field is optional, so a request with no body at all is accepted like `{}`.
47
+ */
48
+ export declare const CompactBody: z.ZodDefault<z.ZodObject<{
49
+ clientRequestId: z.ZodOptional<z.ZodString>;
50
+ }, z.core.$strict>>;
43
51
  export declare const SubagentsQuery: z.ZodObject<{
44
52
  after: z.ZodOptional<z.ZodString>;
45
53
  limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
@@ -46,6 +46,15 @@ export const PatchBody = z
46
46
  .strict()
47
47
  .refine((b) => b.title !== undefined || b.archived !== undefined, "title or archived is required");
48
48
  export const IdParams = z.object({ id: z.string().min(1).max(100) });
49
+ /**
50
+ * `POST …/compact` (context compaction spec §4.7): the optional client request id only makes a
51
+ * transport retry identifiable; the compact run already queued/running is the idempotency key.
52
+ * Every field is optional, so a request with no body at all is accepted like `{}`.
53
+ */
54
+ export const CompactBody = z
55
+ .object({ clientRequestId: z.string().min(1).max(200).optional() })
56
+ .strict()
57
+ .default({});
49
58
  export const SubagentsQuery = z.object({
50
59
  /** The previous page's last sub-agent id (`next`). */
51
60
  after: z.string().min(1).max(100).optional(),
@@ -76,4 +85,9 @@ export const CONVERSATION_ROUTES = [
76
85
  { route: "GET /api/v1/orgs/:orgId/conversations/:id/files", params: IdParams, query: FilesQuery },
77
86
  { route: "GET /api/v1/orgs/:orgId/conversations/:id/device", params: IdParams },
78
87
  { route: "POST /api/v1/orgs/:orgId/conversations/:id/abort", params: IdParams },
88
+ {
89
+ route: "POST /api/v1/orgs/:orgId/conversations/:id/compact",
90
+ params: IdParams,
91
+ body: CompactBody,
92
+ },
79
93
  ];
@@ -156,6 +156,11 @@ export interface RunControl {
156
156
  abortWaiting(conversationId: string, runId: string, byAccountId: string): Promise<boolean>;
157
157
  /** 请求中止运行(广播到所有副本)。 */
158
158
  requestAbort(runId: string, byAccountId: string): Promise<void>;
159
+ /**
160
+ * A manual compaction run (context compaction spec §4.7): the compact run already queued/running,
161
+ * or a new one; `conversation.busy` while an ordinary run is active.
162
+ */
163
+ startCompaction(conversationId: string, accountId: string): Promise<string>;
159
164
  /**
160
165
  * Stops a sub-agent with its descendants (with `includeSelf: false` only the sub-agent
161
166
  * conversations below); the number of runs asked to stop (agent map spec §6).
@@ -563,6 +568,13 @@ export declare class ConversationsService {
563
568
  * the sub-agent's latest run id. Its `aborted` finish never wakes its parent.
564
569
  */
565
570
  abort(orgId: string, conversationId: string, accountId: string): Promise<string>;
571
+ /**
572
+ * Manual compaction (context compaction spec §4.7): starts a compact run for the caller's own
573
+ * chat conversation, or returns the compact run already queued/running. Eval conversations and
574
+ * other people's are `conversation.not_found`; a sub-agent's is `conversation.read_only`; while
575
+ * an ordinary run is active the run start is `conversation.busy`.
576
+ */
577
+ compact(orgId: string, conversationId: string, accountId: string): Promise<string>;
566
578
  /**
567
579
  * Marks a person's stop of the root's tree (`tree_stopped_at`, see {@link abort}); committed
568
580
  * before any stop, so every wake decided after it (under the root's row lock) sees it.
@@ -1031,6 +1031,16 @@ let ConversationsService = class ConversationsService {
1031
1031
  throw new ApiError("run.not_active", "No active run to abort");
1032
1032
  return last.id;
1033
1033
  }
1034
+ /**
1035
+ * Manual compaction (context compaction spec §4.7): starts a compact run for the caller's own
1036
+ * chat conversation, or returns the compact run already queued/running. Eval conversations and
1037
+ * other people's are `conversation.not_found`; a sub-agent's is `conversation.read_only`; while
1038
+ * an ordinary run is active the run start is `conversation.busy`.
1039
+ */
1040
+ async compact(orgId, conversationId, accountId) {
1041
+ await this.writable(orgId, conversationId, accountId);
1042
+ return this.runs.startCompaction(conversationId, accountId);
1043
+ }
1034
1044
  /**
1035
1045
  * Marks a person's stop of the root's tree (`tree_stopped_at`, see {@link abort}); committed
1036
1046
  * before any stop, so every wake decided after it (under the root's row lock) sees it.
@@ -38,6 +38,9 @@ export declare const conversationTopic: (conversationId: string) => string;
38
38
  * (sub-agents spec §14.2, agent map spec §8), `subagentId` the progressing agent: its step and
39
39
  * tool call count so far, and its last tool's key. Not in any log; the SSE forwards it as
40
40
  * `event: subagent_progress` (data without `kind`).
41
+ * - `compaction_progress`: a compaction of a run is running (context compaction spec §4.6), on that
42
+ * run's own conversation's topic **only** (a child's compaction stays on the child's stream); the
43
+ * SSE forwards the flat data as `event: compaction`. Ephemeral, display-only, not in the log.
41
44
  */
42
45
  export type ConversationBusMessage = {
43
46
  kind: "events";
@@ -62,6 +65,17 @@ export type ConversationBusMessage = {
62
65
  step: number;
63
66
  toolCalls: number;
64
67
  lastToolKey?: string;
68
+ } | {
69
+ kind: "compaction_progress";
70
+ runId: string;
71
+ conversationId: string;
72
+ agentId?: string;
73
+ phase: "preparing" | "summarizing" | "writing";
74
+ step: number;
75
+ chunk?: number;
76
+ chunks?: number;
77
+ chars?: number;
78
+ startedAt: number;
65
79
  };
66
80
  /**
67
81
  * What changed about a conversation outside its event log (UI refresh B): the SSE stream sends it as
@@ -456,6 +456,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
456
456
  triggerAccountId: z.ZodString;
457
457
  trigger: z.ZodOptional<z.ZodEnum<{
458
458
  background_task: "background_task";
459
+ compact: "compact";
459
460
  message: "message";
460
461
  schedule: "schedule";
461
462
  subagent: "subagent";
@@ -509,6 +510,14 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
509
510
  etag: z.ZodOptional<z.ZodString>;
510
511
  }, z.core.$strip>>>;
511
512
  mediaBudgetBytes: z.ZodOptional<z.ZodNumber>;
513
+ fit: z.ZodOptional<z.ZodObject<{
514
+ droppedMessageIndexes: z.ZodArray<z.ZodNumber>;
515
+ truncated: z.ZodArray<z.ZodObject<{
516
+ messageIndex: z.ZodNumber;
517
+ block: z.ZodNumber;
518
+ note: z.ZodString;
519
+ }, z.core.$strip>>;
520
+ }, z.core.$strip>>;
512
521
  }, z.core.$strip>;
513
522
  }, z.core.$strip>;
514
523
  }, z.core.$strip>, z.ZodObject<{
@@ -598,6 +607,8 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
598
607
  title: "title";
599
608
  web_fetch: "web_fetch";
600
609
  }>>;
610
+ chunk: z.ZodOptional<z.ZodNumber>;
611
+ chunks: z.ZodOptional<z.ZodNumber>;
601
612
  callId: z.ZodOptional<z.ZodString>;
602
613
  }, z.core.$strip>;
603
614
  }, z.core.$strip>, z.ZodObject<{
@@ -1280,6 +1291,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1280
1291
  payload: z.ZodObject<{
1281
1292
  coversUpToSeq: z.ZodNumber;
1282
1293
  text: z.ZodString;
1294
+ savedTokens: z.ZodOptional<z.ZodNumber>;
1283
1295
  }, z.core.$strip>;
1284
1296
  }, z.core.$strip>, z.ZodObject<{
1285
1297
  type: z.ZodLiteral<"compaction_failed">;
@@ -449,9 +449,11 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
449
449
  * What started the run (display only): absent or `message` = a person's message (or a
450
450
  * sub-agent's task), `background_task` = a finished background task woke the conversation
451
451
  * (spec 2026-11-05-background-bash-design §3), `subagent` = a sub-agent's delivery woke it
452
- * (agent map spec §5.3), `schedule` = a scheduled task's message (scheduled tasks spec §6).
452
+ * (agent map spec §5.3), `schedule` = a scheduled task's message (scheduled tasks spec §6),
453
+ * `compact` = a manual compaction run (context compaction spec §4.7): no message, no model
454
+ * step, only the summary and its usage.
453
455
  */
454
- trigger: z.enum(["message", "background_task", "subagent", "schedule"]).optional(),
456
+ trigger: z.enum(["message", "background_task", "subagent", "schedule", "compact"]).optional(),
455
457
  /**
456
458
  * A wake run's boundary: the seq of the finish or delivery that woke it (full-run replay
457
459
  * seeds from it).
@@ -533,6 +535,20 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
533
535
  * 还原时用它重现同样的省略结果。较早的事件没有。
534
536
  */
535
537
  mediaBudgetBytes: count.optional(),
538
+ /**
539
+ * The hard fit guard's plan (context compaction spec §4.3): indexes into the assembled
540
+ * request's message list that were dropped, and text / tool_result blocks replaced by the
541
+ * truncation note. `assembleModelRequest` applies it (the runtime `buildRequest` calls it,
542
+ * and `evals/reconstruct` calls it directly), so the request replays byte-for-byte; absent
543
+ * when the request fit (and in older recordings). A candidate model with another window
544
+ * recomputes it and reports `context_fit`.
545
+ */
546
+ fit: z
547
+ .object({
548
+ droppedMessageIndexes: z.array(count),
549
+ truncated: z.array(z.object({ messageIndex: count, block: count, note: z.string() })),
550
+ })
551
+ .optional(),
536
552
  }),
537
553
  })),
538
554
  ev("assistant_message", z.object({
@@ -556,6 +572,13 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
556
572
  model: z.string(),
557
573
  ...ModelUsageShape,
558
574
  purpose: z.enum(["compaction", "title", "web_fetch", "review"]).optional(),
575
+ /**
576
+ * The chunk a chunked compaction call summarised (1-based), with the number of calls the
577
+ * compaction attempted (the full chunk count on a completed one; on a failed or hook-denied
578
+ * run only the calls that were made). Absent on a single-call compaction: older logs have none.
579
+ */
580
+ chunk: count.optional(),
581
+ chunks: count.optional(),
559
582
  /** The tool call a `web_fetch` or `review` usage belongs to. */
560
583
  callId: z.string().optional(),
561
584
  })),
@@ -1049,7 +1072,16 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1049
1072
  */
1050
1073
  stoppedBy: z.enum(["person", "deletion", "subagent_end"]).optional(),
1051
1074
  })),
1052
- ev("compaction_summary", z.object({ coversUpToSeq: seqNo, text: z.string() })),
1075
+ ev("compaction_summary", z.object({
1076
+ coversUpToSeq: seqNo,
1077
+ text: z.string(),
1078
+ /**
1079
+ * The estimated transcript input minus the stored summary output (context compaction spec
1080
+ * §4.9), so the UI needs no chunked usage to show what compaction saved. Optional: older
1081
+ * logs have none.
1082
+ */
1083
+ savedTokens: count.optional(),
1084
+ })),
1053
1085
  ev("compaction_failed", z.object({ attempt: count, reason: z.string() })),
1054
1086
  ev("run_finished", z.object({
1055
1087
  /** `budget`: a sub-agent stopped at its parent run's token cap (phase C, spec §8.3). */
@@ -372,6 +372,11 @@ export interface RunsTable {
372
372
  * inherited by its unattended descendants); null = a person's run.
373
373
  */
374
374
  scheduled_task_run_id: ColumnType<string | null, string | null | undefined, string | null>;
375
+ /**
376
+ * 0132: a manual compaction run (context compaction spec §4.7): it calls the shared compaction
377
+ * execution with `force: true` instead of the agent loop, and writes no model step.
378
+ */
379
+ compact: ColumnType<boolean, boolean | undefined, boolean>;
375
380
  }
376
381
  /** 0053: one row per sub-agent dispatch (an `Agent` call of a parent run). */
377
382
  export interface SubagentDispatchesTable {
package/dist/errors.d.ts CHANGED
@@ -273,6 +273,8 @@ export declare const ERROR_CODES: {
273
273
  /** An org template was saved since the editor read it (`expectedVersion` is stale, P4-12). */
274
274
  readonly "agent_template.version_conflict": 409;
275
275
  readonly "conversation.not_found": 404;
276
+ /** A manual compaction asked for while an ordinary run is active (context compaction §4.7). */
277
+ readonly "conversation.busy": 409;
276
278
  readonly "conversation.output_not_found": 404;
277
279
  readonly "conversation.artifact_not_found": 404;
278
280
  readonly "conversation.artifact_not_previewable": 400;
@@ -452,6 +454,7 @@ export declare const ERROR_CODES: {
452
454
  readonly "eval.case_exists": 409;
453
455
  readonly "eval.too_many_cases": 409;
454
456
  readonly "eval.agent_mismatch": 409;
457
+ readonly "eval.compact_not_replayable": 422;
455
458
  readonly "eval.run_not_found": 404;
456
459
  readonly "eval.token_cap_invalid": 400;
457
460
  readonly "eval.run_finished": 409;
package/dist/errors.js CHANGED
@@ -273,6 +273,8 @@ export const ERROR_CODES = {
273
273
  /** An org template was saved since the editor read it (`expectedVersion` is stale, P4-12). */
274
274
  "agent_template.version_conflict": 409,
275
275
  "conversation.not_found": 404,
276
+ /** A manual compaction asked for while an ordinary run is active (context compaction §4.7). */
277
+ "conversation.busy": 409,
276
278
  "conversation.output_not_found": 404,
277
279
  "conversation.artifact_not_found": 404,
278
280
  "conversation.artifact_not_previewable": 400,
@@ -452,6 +454,7 @@ export const ERROR_CODES = {
452
454
  "eval.case_exists": 409,
453
455
  "eval.too_many_cases": 409,
454
456
  "eval.agent_mismatch": 409,
457
+ "eval.compact_not_replayable": 422,
455
458
  "eval.run_not_found": 404,
456
459
  "eval.token_cap_invalid": 400,
457
460
  "eval.run_finished": 409,
@@ -2,23 +2,25 @@ import type { ModelUsage } from "@capybara-hq/plugin-sdk";
2
2
  import type { ModelRef } from "../agents/definition.js";
3
3
  import { type CaseSnapshot } from "./snapshot.js";
4
4
  /**
5
- * 用例的回放计划(D5 估算、预建结果):写入用例时由快照算好存进 `eval_cases.plan_step` / `plan_run`,
6
- * 估算与启动只读这些列,不读快照。
5
+ * A case's replay plan (D5 estimate, pre-built results): computed from the snapshot when the case is
6
+ * written and stored in `eval_cases.plan_step` / `plan_run`; estimates and starts read only those
7
+ * columns, never the snapshot.
7
8
  */
8
- /** 一个用例要回放的调用与原运行的用量(估算与预建结果用)。 */
9
+ /** The calls a case replays and the original run's usage (for estimates and pre-built results). */
9
10
  export interface CasePlan {
10
- /** step 模式:每个可回放调用一行;run 模式:整个用例一行(step / seq 为 null)。 */
11
+ /** Step mode: one row per replayable call; run mode: one row for the case (step / seq null). */
11
12
  results: {
12
13
  step: number | null;
13
14
  modelCallSeq: number | null;
14
15
  }[];
15
- /** 预计的模型请求数。 */
16
+ /** The expected number of model requests. */
16
17
  modelRequests: number;
17
- /** 这些请求在原运行里的用量(逐项相加)。 */
18
+ /** Those requests' usage in the original run (summed per field). */
18
19
  usage: ModelUsage;
19
20
  /**
20
- * 评委的上下文估算:各条结果的「用户请求」token + 两边回复(基线输出 token × 2,候选按与基线同量估算)。
21
- * 评委的系统提示词、评分标准与输出上限按运行时的设置另加(见 `runs.service.ts`)。
21
+ * The judge's context estimate: each result's "user request" tokens plus both replies (the
22
+ * baseline's output tokens × 2; the candidate is estimated at the same amount). The judge's system
23
+ * prompt, rubric and output cap are added at run time from the settings (`runs.service.ts`).
22
24
  */
23
25
  judgeContextTokens: number;
24
26
  /**
@@ -27,17 +29,20 @@ export interface CasePlan {
27
29
  */
28
30
  switchedModel?: ModelRef;
29
31
  }
30
- /** 存在 `eval_cases.plan_step` / `plan_run` 的计划(与 {@link CasePlan} 同形)。 */
32
+ /** A plan as stored in `eval_cases.plan_step` / `plan_run` (the same shape as {@link CasePlan}). */
31
33
  export type StoredCasePlan = CasePlan;
32
- /** 一段文本的 token 估算(与运行时同一个估算器)。 */
34
+ /** The token estimate of a text (the same estimator as the runtime). */
33
35
  export declare const textTokens: (text: string) => number;
34
- /** 快照里 `beforeSeq` 之前最近一条用户消息的文本(评委看的「用户请求」)。 */
36
+ /** The newest user message before `beforeSeq` in the snapshot (the "user request" the judge sees). */
35
37
  export declare function userRequestOf(s: CaseSnapshot, beforeSeq: number): string;
36
38
  /**
37
- * 一个用例的回放计划:
38
- * - `step`:请求 = 可回放的调用(`replayableCalls`),用量 = 这些调用各自记录的 usage(该步该调用之后第一条);
39
- * - `run`:请求 = 原运行的全部 `model_call`,用量 = 原运行的全部 usage。
40
- * 写入用例时算好存进 `plan_step` / `plan_run`({@link casePlans}),估算与启动不再读快照。
39
+ * A case's replay plan:
40
+ * - `step`: requests = the replayable calls (`replayableCalls`), usage = each call's recorded usage
41
+ * (the first one after that call, same step);
42
+ * - `run`: requests = every `model_call` of the original run, usage = every usage of the run.
43
+ * Computed when the case is written and stored in `plan_step` / `plan_run` ({@link casePlans}), so
44
+ * estimates and starts do not read the snapshot.
45
+ * A compact run has no plan in either mode ({@link compactRun}): estimates and starts skip it.
41
46
  */
42
47
  export declare function casePlan(s: CaseSnapshot, mode: "step" | "run"): CasePlan;
43
48
  /** 两种模式的计划(写入用例时调用)。 */