@capybara-hq/kernel 0.1.0-rc.32 → 0.1.0-rc.34

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 (107) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/catalog/requests.service.d.ts +8 -6
  4. package/dist/catalog/requests.service.js +52 -29
  5. package/dist/channels/inbound.d.ts +0 -25
  6. package/dist/channels/inbound.js +26 -1
  7. package/dist/channels/phrases.d.ts +28 -0
  8. package/dist/channels/phrases.js +28 -0
  9. package/dist/config/schema.d.ts +4 -0
  10. package/dist/config/schema.js +7 -1
  11. package/dist/conversations/conversations.controller.d.ts +4 -1
  12. package/dist/conversations/conversations.controller.js +14 -2
  13. package/dist/conversations/conversations.service.d.ts +43 -3
  14. package/dist/conversations/conversations.service.js +93 -19
  15. package/dist/conversations/event-log.d.ts +3 -3
  16. package/dist/conversations/event-log.js +3 -3
  17. package/dist/conversations/events.d.ts +24 -0
  18. package/dist/conversations/events.js +69 -0
  19. package/dist/db/kernel-schema.d.ts +20 -0
  20. package/dist/devices/conversation-devices.d.ts +57 -3
  21. package/dist/devices/conversation-devices.js +63 -11
  22. package/dist/devices/device-projects.service.d.ts +162 -0
  23. package/dist/devices/device-projects.service.js +503 -0
  24. package/dist/devices/devices.controller.d.ts +15 -2
  25. package/dist/devices/devices.controller.js +60 -3
  26. package/dist/devices/devices.module.js +15 -2
  27. package/dist/devices/devices.schemas.js +9 -1
  28. package/dist/devices/devices.service.js +8 -4
  29. package/dist/devices/dto.d.ts +31 -0
  30. package/dist/devices/dto.js +38 -1
  31. package/dist/devices/working-root.d.ts +41 -0
  32. package/dist/devices/working-root.js +50 -0
  33. package/dist/errors.d.ts +39 -0
  34. package/dist/errors.js +39 -0
  35. package/dist/evals/run-replay.d.ts +9 -1
  36. package/dist/evals/run-replay.js +15 -1
  37. package/dist/local-devices/local-device-provider.d.ts +37 -1
  38. package/dist/local-devices/local-device-provider.js +33 -0
  39. package/dist/local-devices/machines.d.ts +2 -1
  40. package/dist/local-devices/machines.js +4 -1
  41. package/dist/local-devices/network-grants.d.ts +1 -1
  42. package/dist/local-devices/network-grants.js +2 -3
  43. package/dist/local-devices/policy-summary.js +1 -0
  44. package/dist/local-devices/relay.d.ts +2 -0
  45. package/dist/local-devices/relay.js +3 -1
  46. package/dist/local-devices/targets.d.ts +6 -1
  47. package/dist/local-devices/targets.js +14 -0
  48. package/dist/orgs/settings.controller.d.ts +3 -1
  49. package/dist/orgs/settings.controller.js +7 -3
  50. package/dist/orgs/settings.service.d.ts +78 -31
  51. package/dist/orgs/settings.service.js +109 -52
  52. package/dist/overrides.d.ts +4 -0
  53. package/dist/overrides.js +2 -0
  54. package/dist/platform/ops/agent-skills.ops.js +2 -1
  55. package/dist/platform/ops/devices.ops.d.ts +3 -1
  56. package/dist/platform/ops/devices.ops.js +136 -3
  57. package/dist/platform/ops/org-settings.ops.js +20 -10
  58. package/dist/runtime/context/build.d.ts +3 -0
  59. package/dist/runtime/context/build.js +14 -0
  60. package/dist/runtime/context/compaction.js +2 -0
  61. package/dist/runtime/context/project-root.d.ts +43 -0
  62. package/dist/runtime/context/project-root.js +85 -0
  63. package/dist/runtime/model-call.js +25 -1
  64. package/dist/runtime/project/knowledge.d.ts +129 -0
  65. package/dist/runtime/project/knowledge.js +248 -0
  66. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  67. package/dist/runtime/project/knowledge.service.js +288 -0
  68. package/dist/runtime/run-worker.d.ts +5 -0
  69. package/dist/runtime/run-worker.js +27 -6
  70. package/dist/runtime/runtime.module.js +7 -0
  71. package/dist/sandbox/modes.d.ts +31 -19
  72. package/dist/sandbox/modes.js +43 -24
  73. package/dist/sandbox/review/review.service.d.ts +14 -2
  74. package/dist/sandbox/review/review.service.js +2 -0
  75. package/dist/sandbox/review/rules.d.ts +6 -4
  76. package/dist/sandbox/review/rules.js +185 -62
  77. package/dist/sandbox/review/types.d.ts +14 -0
  78. package/dist/sandbox/sandbox.service.d.ts +20 -2
  79. package/dist/sandbox/sandbox.service.js +86 -3
  80. package/dist/schedules/grant-rules.d.ts +2 -0
  81. package/dist/schedules/grant-rules.js +3 -1
  82. package/dist/schedules/schedule-math.js +21 -2
  83. package/dist/schedules/scheduled-tasks.service.js +3 -1
  84. package/dist/skills/catalog.d.ts +6 -1
  85. package/dist/skills/catalog.js +18 -4
  86. package/dist/skills/invoke.d.ts +64 -2
  87. package/dist/skills/invoke.js +214 -6
  88. package/dist/skills/skills.module.js +5 -0
  89. package/dist/tools/approvals.service.d.ts +6 -0
  90. package/dist/tools/builtins/sandbox/bash.js +19 -4
  91. package/dist/tools/builtins/sandbox/common.d.ts +36 -6
  92. package/dist/tools/builtins/sandbox/common.js +69 -8
  93. package/dist/tools/builtins/sandbox/edit.js +2 -2
  94. package/dist/tools/builtins/sandbox/glob.js +3 -2
  95. package/dist/tools/builtins/sandbox/grep.js +2 -1
  96. package/dist/tools/builtins/sandbox/read.js +3 -3
  97. package/dist/tools/builtins/sandbox/write.js +2 -2
  98. package/dist/tools/builtins/skill-load.d.ts +47 -2
  99. package/dist/tools/builtins/skill-load.js +160 -2
  100. package/dist/tools/network-asks.d.ts +7 -0
  101. package/dist/tools/network-asks.js +11 -1
  102. package/dist/tools/pipeline.d.ts +1 -1
  103. package/dist/tools/pipeline.js +60 -9
  104. package/dist/tools/registry.d.ts +6 -0
  105. package/package.json +2 -2
  106. package/src/migrations/0133_project_root.sql +30 -0
  107. package/src/migrations/0134_org_cloud_network_delta.sql +38 -0
@@ -0,0 +1,248 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isFileSystemGoneError, isSandboxGoneError, MAX_DEVICE_LIST_ENTRIES, parseSkillMd, SKILL_ENTRY_FILE, } from "@capybara-hq/plugin-sdk";
3
+ import { POLICY_REFUSAL_PREFIX } from "../../local-devices/relay.js";
4
+ /** The most of a project's `AGENTS.md` a `project_root` event carries, in UTF-8 bytes (marker included). */
5
+ export const AGENTS_MD_MAX_BYTES = 64 * 1024;
6
+ /** Appended to an `AGENTS.md` cut at {@link AGENTS_MD_MAX_BYTES} (model-visible, so English). */
7
+ export const AGENTS_MD_TRUNCATED_MARKER = "\n\n[AGENTS.md is longer than 64 KiB; the rest was cut here]";
8
+ /** The directory of a project's skills, relative to its root. */
9
+ export const PROJECT_SKILLS_DIR = ".agents/skills";
10
+ /** How many `SKILL.md` files one run start reads at once. */
11
+ const SKILL_READ_CONCURRENCY = 8;
12
+ /**
13
+ * The most skill directories a run start reads, the first by name; a project with more says so
14
+ * (`skillsTruncated`).
15
+ */
16
+ export const PROJECT_SKILLS_MAX = 100;
17
+ /**
18
+ * The most of one `SKILL.md` a run start reads, in bytes: the name and description come from its
19
+ * frontmatter at the top, and the digest covers the bytes read.
20
+ */
21
+ export const SKILL_MD_MAX_BYTES = 1024 * 1024;
22
+ /** The most entries one listing of the skills directory asks for (files there take no skill's place). */
23
+ const SKILLS_LIST_LIMIT = MAX_DEVICE_LIST_ENTRIES;
24
+ /** The longest `unavailable.message` the event takes. */
25
+ const MESSAGE_MAX_CHARS = 500;
26
+ /** The idempotency key of a run's `project_root` event (a retried run start appends it once). */
27
+ export const projectRootIdemKey = (runId) => `project_root:${runId}`;
28
+ /** A device path or a device error inside a reason, bounded. */
29
+ function clipped(s, max = 200) {
30
+ return s.length <= max ? s : `${s.slice(0, max)}…`;
31
+ }
32
+ const unavailable = (reason, text) => ({
33
+ reason,
34
+ message: text.length <= MESSAGE_MAX_CHARS ? text : `${text.slice(0, MESSAGE_MAX_CHARS - 1)}…`,
35
+ });
36
+ /** The `unavailable` values a reader records: a reason code and an English message for the model. */
37
+ export const projectUnavailable = {
38
+ gone: (root) => unavailable("gone", `The project's root ${clipped(root)} no longer exists on the device.`),
39
+ outsideMode: (root, mode) => unavailable("outside_mode", `The project's root ${clipped(root)} is outside what the device can read in ${mode} mode.`),
40
+ notDirectory: (root) => unavailable("unreadable", `The project's root ${clipped(root)} is not a directory.`),
41
+ /** The device's own error text is logged, never recorded: the message stays the same per root. */
42
+ unreadable: (root) => unavailable("unreadable", `The project's root ${clipped(root)} could not be read.`),
43
+ widerMode: (root) => unavailable("outside_mode", `The project's root ${clipped(root)} was not read: the device runs a wider mode than the organization allows.`),
44
+ removed: (project) => unavailable("removed", `The project "${clipped(project, 80)}" was removed from the device's projects.`),
45
+ unsupported: () => unavailable("unsupported", "The device does not offer projects; capybara-device on that machine needs an update."),
46
+ };
47
+ /** The snapshot of a project the run cannot use: the reason alone, no AGENTS.md, no skills. */
48
+ export const unavailableProject = (project, root, why) => ({ project, root, unavailable: why, skills: [] });
49
+ /** A lost instance or file system: passed on, so the sandbox service recovers or records it. */
50
+ const isGone = (e) => isSandboxGoneError(e) || isFileSystemGoneError(e);
51
+ const messageOf = (e) => (e instanceof Error ? e.message : String(e));
52
+ const isPolicyRefusal = (e) => e instanceof Error && e.message.startsWith(POLICY_REFUSAL_PREFIX);
53
+ /** The hex sha256 of a file's bytes: a skill's digest. */
54
+ const digestOf = (data) => createHash("sha256").update(data).digest("hex");
55
+ /**
56
+ * `text` within {@link AGENTS_MD_MAX_BYTES} UTF-8 bytes: unchanged when it fits and the read was
57
+ * whole; otherwise cut on a code point boundary and followed by {@link AGENTS_MD_TRUNCATED_MARKER},
58
+ * marker included in the cap. Measured on the decoded string, so invalid bytes the decoder turned
59
+ * into U+FFFD cannot push it past the cap.
60
+ */
61
+ export function capAgentsMd(text, readTruncated) {
62
+ if (!readTruncated && Buffer.byteLength(text, "utf8") <= AGENTS_MD_MAX_BYTES) {
63
+ return { text, cut: false };
64
+ }
65
+ const budget = AGENTS_MD_MAX_BYTES - Buffer.byteLength(AGENTS_MD_TRUNCATED_MARKER, "utf8");
66
+ let used = 0;
67
+ let end = 0;
68
+ for (const ch of text) {
69
+ const n = Buffer.byteLength(ch, "utf8");
70
+ if (used + n > budget)
71
+ break;
72
+ used += n;
73
+ end += ch.length;
74
+ }
75
+ return { text: `${text.slice(0, end)}${AGENTS_MD_TRUNCATED_MARKER}`, cut: true };
76
+ }
77
+ const decoder = new TextDecoder("utf-8");
78
+ /**
79
+ * A SKILL.md is decoded strictly, as `readProjectSkill` decodes it when `Skill` loads it: a file
80
+ * that is not UTF-8 is skipped here, so the catalog never lists a skill that cannot be loaded.
81
+ */
82
+ const skillDecoder = new TextDecoder("utf-8", { fatal: true });
83
+ /**
84
+ * Reads the project at `target.root` through `files` (project root spec §4.4, §4.7). Every failure
85
+ * of the project itself is recorded, never thrown: a root that is gone, refused in the mode, not a
86
+ * directory or unreadable gives `unavailable` with its reason code and nothing else; a missing
87
+ * `AGENTS.md` is simply left out (spec §4.7: a project with skills only), an unreadable one too,
88
+ * with a log line; the first {@link PROJECT_SKILLS_MAX} skill directories by name are read
89
+ * (`skillsTruncated` when there are more), each `SKILL.md` up to {@link SKILL_MD_MAX_BYTES}; an
90
+ * unparsable, missing or misnamed `SKILL.md` (its `name` must be its directory's, the name `Skill`
91
+ * loads it by) is skipped and logged. Only a lost instance or file system (for the sandbox service) and a device
92
+ * failure ({@link ReadProjectKnowledgeOptions.isDeviceFailure}) are thrown.
93
+ */
94
+ export async function readProjectKnowledge(files, target, opts = {}) {
95
+ const { project, root, mode } = target;
96
+ const deviceFailure = opts.isDeviceFailure ?? (() => false);
97
+ const r = {
98
+ log: opts.log ?? (() => { }),
99
+ fatal: (e) => isGone(e) || deviceFailure(e),
100
+ };
101
+ const cannot = (why) => unavailableProject(project, root, why);
102
+ let st;
103
+ try {
104
+ st = await files.stat(root);
105
+ }
106
+ catch (e) {
107
+ if (r.fatal(e))
108
+ throw e;
109
+ if (isPolicyRefusal(e))
110
+ return cannot(projectUnavailable.outsideMode(root, mode));
111
+ r.log("project root could not be read", { path: root, reason: messageOf(e) });
112
+ return cannot(projectUnavailable.unreadable(root));
113
+ }
114
+ if (st === null)
115
+ return cannot(projectUnavailable.gone(root));
116
+ if (!st.isDir)
117
+ return cannot(projectUnavailable.notDirectory(root));
118
+ const out = { project, root, skills: [] };
119
+ const agentsMd = `${root}/AGENTS.md`;
120
+ try {
121
+ const read = await files.readFile(agentsMd, AGENTS_MD_MAX_BYTES);
122
+ // none: a project with skills only, nothing to say (spec §4.7)
123
+ if (read !== null) {
124
+ const capped = capAgentsMd(decoder.decode(read.data), read.truncated);
125
+ out.agentsMd = capped.text;
126
+ if (capped.cut)
127
+ out.agentsMdTruncated = true;
128
+ }
129
+ }
130
+ catch (e) {
131
+ if (r.fatal(e))
132
+ throw e;
133
+ r.log("project AGENTS.md could not be read; left out this run", {
134
+ path: agentsMd,
135
+ reason: messageOf(e),
136
+ });
137
+ }
138
+ const skills = await readSkills(files, root, r);
139
+ out.skills = skills.skills;
140
+ if (skills.truncated)
141
+ out.skillsTruncated = true;
142
+ return out;
143
+ }
144
+ /**
145
+ * The project's skills, the first {@link PROJECT_SKILLS_MAX} directories in name order (see
146
+ * {@link readProjectKnowledge}); `truncated` when the directory holds more (or more entries than
147
+ * one listing returns, so more may exist).
148
+ */
149
+ async function readSkills(files, root, r) {
150
+ const none = { skills: [], truncated: false };
151
+ if (files.list === undefined)
152
+ return none;
153
+ const dir = `${root}/${PROJECT_SKILLS_DIR}`;
154
+ let listed;
155
+ try {
156
+ listed = await files.list(dir, SKILLS_LIST_LIMIT);
157
+ }
158
+ catch (e) {
159
+ if (r.fatal(e))
160
+ throw e;
161
+ r.log("project skills directory could not be listed; no project skills this run", {
162
+ path: dir,
163
+ reason: messageOf(e),
164
+ });
165
+ return none;
166
+ }
167
+ if (listed === null)
168
+ return none;
169
+ // the listing is sorted by code unit; sorted again so the cut never depends on the provider
170
+ const all = listed.entries
171
+ .filter((e) => e.isDir)
172
+ .map((e) => e.name)
173
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
174
+ const truncated = listed.truncated || all.length > PROJECT_SKILLS_MAX;
175
+ if (truncated) {
176
+ r.log("project has more skill directories than a run reads; the rest are left out", {
177
+ path: dir,
178
+ limit: PROJECT_SKILLS_MAX,
179
+ });
180
+ }
181
+ const dirs = all.slice(0, PROJECT_SKILLS_MAX);
182
+ const found = new Array(dirs.length).fill(null);
183
+ let next = 0;
184
+ const worker = async () => {
185
+ while (next < dirs.length) {
186
+ const i = next++;
187
+ found[i] = await readSkill(files, dir, dirs[i], r);
188
+ }
189
+ };
190
+ await Promise.all(Array.from({ length: Math.min(SKILL_READ_CONCURRENCY, dirs.length) }, worker));
191
+ return { skills: found.filter((s) => s !== null), truncated };
192
+ }
193
+ /** One skill's catalog entry, or null (skipped and logged). */
194
+ async function readSkill(files, dir, name, r) {
195
+ const path = `${dir}/${name}/${SKILL_ENTRY_FILE}`;
196
+ const skip = (why) => {
197
+ r.log("project skill skipped", { skill: name, path, reason: why });
198
+ return null;
199
+ };
200
+ let read;
201
+ try {
202
+ read = await files.readFile(path, SKILL_MD_MAX_BYTES);
203
+ }
204
+ catch (e) {
205
+ if (r.fatal(e))
206
+ throw e;
207
+ return skip(`could not be read: ${messageOf(e)}`);
208
+ }
209
+ if (read === null)
210
+ return skip(`no ${SKILL_ENTRY_FILE}`);
211
+ // a longer file is parsed and digested as far as it was read: its frontmatter is at the top
212
+ let text;
213
+ try {
214
+ text = skillDecoder.decode(read.data);
215
+ }
216
+ catch {
217
+ return skip("it is not UTF-8 text");
218
+ }
219
+ const parsed = parseSkillMd(text);
220
+ if ("errors" in parsed)
221
+ return skip(parsed.errors.join("; "));
222
+ if (parsed.name !== name) {
223
+ return skip(`its name "${parsed.name}" is not its directory's name`);
224
+ }
225
+ return { name, description: parsed.description, digest: digestOf(read.data) };
226
+ }
227
+ /**
228
+ * Whether two snapshots are the same, so a run start appends nothing: the same project and root,
229
+ * the same `AGENTS.md` text (or none), the same unavailability, and the same skills with the same
230
+ * digests (and the same cut).
231
+ */
232
+ export function sameProjectRoot(a, b) {
233
+ return (a.project === b.project &&
234
+ a.root === b.root &&
235
+ a.agentsMd === b.agentsMd &&
236
+ (a.agentsMdTruncated ?? false) === (b.agentsMdTruncated ?? false) &&
237
+ a.unavailable?.reason === b.unavailable?.reason &&
238
+ a.unavailable?.message === b.unavailable?.message &&
239
+ (a.skillsTruncated ?? false) === (b.skillsTruncated ?? false) &&
240
+ a.skills.length === b.skills.length &&
241
+ a.skills.every((s, i) => {
242
+ const t = b.skills[i];
243
+ return (t !== undefined &&
244
+ s.name === t.name &&
245
+ s.description === t.description &&
246
+ s.digest === t.digest);
247
+ }));
248
+ }
@@ -0,0 +1,85 @@
1
+ import { EventLog } from "../../conversations/event-log.js";
2
+ import { ConversationDevices } from "../../devices/conversation-devices.js";
3
+ import { DeviceProjectsService } from "../../devices/device-projects.service.js";
4
+ import { KernelDb } from "../../infra/database/kernel-db.js";
5
+ import { TransactionHost } from "../../infra/database/transaction-host.js";
6
+ import type { KernelLogger } from "../../log.js";
7
+ import { SandboxService } from "../../sandbox/sandbox.service.js";
8
+ /**
9
+ * The longest a run start waits for its project's knowledge (every device call of the read under
10
+ * one bound): past it the run goes on without a new snapshot, as when the device is unreachable.
11
+ */
12
+ export declare const PROJECT_KNOWLEDGE_TIMEOUT_MS = 30000;
13
+ /**
14
+ * Test seam (`KernelSeams`): the read's time limit in ms, asked at every read; default
15
+ * {@link PROJECT_KNOWLEDGE_TIMEOUT_MS}.
16
+ */
17
+ export declare const PROJECT_KNOWLEDGE_TIMEOUT: unique symbol;
18
+ /** What a run start tells {@link ProjectKnowledgeService.record}. */
19
+ export interface ProjectKnowledgeInput {
20
+ orgId: string;
21
+ conversationId: string;
22
+ runId: string;
23
+ /** The conversation's kind: only a chat conversation can be bound to a project. */
24
+ kind: "chat" | "eval" | "subagent";
25
+ /**
26
+ * A sub-agent run's root conversation: the child works in its root's project, so its run start
27
+ * copies the root's latest snapshot (no device call). Absent for any other run.
28
+ */
29
+ rootConversationId?: string;
30
+ /** The run's shutdown signal (the read has its own time limit as well). */
31
+ signal: AbortSignal;
32
+ }
33
+ /**
34
+ * Run start's project knowledge (project root spec §4.4, §4.7): for a conversation bound to a
35
+ * project (`conversations.project_name` / `project_path`), reads the project's `AGENTS.md` and
36
+ * skills on its device before the run's first model call ({@link readProjectKnowledge}), outside
37
+ * any transaction, and appends a `project_root` event when the snapshot differs from the
38
+ * conversation's latest one. A free conversation reads nothing, so its device still starts lazily
39
+ * at its first sandbox call; an eval replay or a sub-agent never reads a device here. A sub-agent's
40
+ * run start copies its **root** conversation's latest `project_root` into its own log instead (it
41
+ * works in the same project), under its own run's idempotency key, and again only when the root's
42
+ * latest snapshot differs from the child's latest; the renderer then shows it to the child as is.
43
+ *
44
+ * Reads in the device's effective mode (`DeviceProjectsService.scopeFor`, the same scope the
45
+ * binding was checked against) and through `SandboxService.withSandbox`, as a tool call does, so
46
+ * a bound conversation starts its device eagerly (the accepted cost, spec §4.4). A project the
47
+ * run cannot use is recorded as `unavailable` with its reason: a project the device no longer
48
+ * keeps under the bound name and path (`removed`, not asked), a root that is gone, out of the mode
49
+ * (or above the owner's home) or unreadable, or a machine that does not announce projects
50
+ * (`unsupported`, not asked). The
51
+ * device not being reachable (offline, the provider down, the time limit) records nothing, and the
52
+ * run goes on as it does today when its device is away. Nothing is cached in the process.
53
+ */
54
+ export declare class ProjectKnowledgeService {
55
+ private readonly db;
56
+ private readonly eventLog;
57
+ readonly txHost: TransactionHost;
58
+ private readonly devices;
59
+ private readonly projects;
60
+ private readonly sandbox;
61
+ private readonly log;
62
+ private readonly timeoutMs;
63
+ constructor(db: KernelDb, eventLog: Pick<EventLog, "appendIn" | "notify">, txHost: TransactionHost, devices: Pick<ConversationDevices, "forTool">, projects: Pick<DeviceProjectsService, "scopeFor" | "keeps">, sandbox: Pick<SandboxService, "withSandbox">, log: KernelLogger, timeoutMs?: () => number);
64
+ /**
65
+ * Reads and records (see the class); notifies after the commit. False: the run had ended under
66
+ * the locks (a stop landed while the device was read), so nothing was appended and the run must
67
+ * not go on (as `PluginContextService.record`).
68
+ */
69
+ record(input: ProjectKnowledgeInput): Promise<boolean>;
70
+ /**
71
+ * A sub-agent's run start: the root conversation's latest snapshot appended to the child's log
72
+ * when it differs from the child's latest ({@link append}); nothing when the root has none. No
73
+ * device call, so a replay of the child (which copies the child's own event) never needs one.
74
+ */
75
+ private copyFromRoot;
76
+ /** The snapshot read on the device, or null when the device could not be asked (logged). */
77
+ private read;
78
+ /**
79
+ * One transaction under the conversation row lock (as `PluginContextService`): compares the
80
+ * snapshot with the conversation's latest `project_root` and appends it when it differs, with
81
+ * the run's idempotency key, so a retried run start finds its event (or nothing changed).
82
+ * Returns the seq written, null for none, `ended` when the run is terminal under the locks.
83
+ */
84
+ private append;
85
+ }
@@ -0,0 +1,288 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { DeviceProtocolError } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable, Optional } from "@nestjs/common";
12
+ import { EventLog } from "../../conversations/event-log.js";
13
+ import { ConversationDevices } from "../../devices/conversation-devices.js";
14
+ import { DeviceProjectsService, withinMode } from "../../devices/device-projects.service.js";
15
+ import { aboveHome } from "../../devices/working-root.js";
16
+ import { ApiError } from "../../errors.js";
17
+ import { KernelDb } from "../../infra/database/kernel-db.js";
18
+ import { TransactionHost } from "../../infra/database/transaction-host.js";
19
+ import { Transactional } from "../../infra/database/transactional.decorator.js";
20
+ import { KERNEL_LOGGER } from "../../infra/tokens.js";
21
+ import { SandboxLockLostError, SandboxPathBusyError } from "../../sandbox/leases.js";
22
+ import { homeOf } from "../../sandbox/review/rules.js";
23
+ import { SandboxService } from "../../sandbox/sandbox.service.js";
24
+ import { providerConnectionFailure } from "../../sandbox/unreachable.js";
25
+ import { runEndedIn } from "../run-status.js";
26
+ import { projectRootIdemKey, projectUnavailable, readProjectKnowledge, sameProjectRoot, unavailableProject, } from "./knowledge.js";
27
+ /**
28
+ * The longest a run start waits for its project's knowledge (every device call of the read under
29
+ * one bound): past it the run goes on without a new snapshot, as when the device is unreachable.
30
+ */
31
+ export const PROJECT_KNOWLEDGE_TIMEOUT_MS = 30_000;
32
+ /**
33
+ * Test seam (`KernelSeams`): the read's time limit in ms, asked at every read; default
34
+ * {@link PROJECT_KNOWLEDGE_TIMEOUT_MS}.
35
+ */
36
+ export const PROJECT_KNOWLEDGE_TIMEOUT = Symbol("PROJECT_KNOWLEDGE_TIMEOUT");
37
+ /**
38
+ * An error that says the device could not be asked, not that the project is unreadable: the
39
+ * provider unreachable, a kernel refusal (the device offline, gone or busy, a relay given up), a
40
+ * malformed device answer, a lost lease.
41
+ */
42
+ function isDeviceFailure(e) {
43
+ return (providerConnectionFailure(e) !== undefined ||
44
+ e instanceof ApiError ||
45
+ e instanceof DeviceProtocolError ||
46
+ e instanceof SandboxLockLostError ||
47
+ e instanceof SandboxPathBusyError);
48
+ }
49
+ /**
50
+ * Run start's project knowledge (project root spec §4.4, §4.7): for a conversation bound to a
51
+ * project (`conversations.project_name` / `project_path`), reads the project's `AGENTS.md` and
52
+ * skills on its device before the run's first model call ({@link readProjectKnowledge}), outside
53
+ * any transaction, and appends a `project_root` event when the snapshot differs from the
54
+ * conversation's latest one. A free conversation reads nothing, so its device still starts lazily
55
+ * at its first sandbox call; an eval replay or a sub-agent never reads a device here. A sub-agent's
56
+ * run start copies its **root** conversation's latest `project_root` into its own log instead (it
57
+ * works in the same project), under its own run's idempotency key, and again only when the root's
58
+ * latest snapshot differs from the child's latest; the renderer then shows it to the child as is.
59
+ *
60
+ * Reads in the device's effective mode (`DeviceProjectsService.scopeFor`, the same scope the
61
+ * binding was checked against) and through `SandboxService.withSandbox`, as a tool call does, so
62
+ * a bound conversation starts its device eagerly (the accepted cost, spec §4.4). A project the
63
+ * run cannot use is recorded as `unavailable` with its reason: a project the device no longer
64
+ * keeps under the bound name and path (`removed`, not asked), a root that is gone, out of the mode
65
+ * (or above the owner's home) or unreadable, or a machine that does not announce projects
66
+ * (`unsupported`, not asked). The
67
+ * device not being reachable (offline, the provider down, the time limit) records nothing, and the
68
+ * run goes on as it does today when its device is away. Nothing is cached in the process.
69
+ */
70
+ let ProjectKnowledgeService = class ProjectKnowledgeService {
71
+ db;
72
+ eventLog;
73
+ txHost;
74
+ devices;
75
+ projects;
76
+ sandbox;
77
+ log;
78
+ timeoutMs;
79
+ constructor(db, eventLog, txHost, devices, projects, sandbox, log, timeoutMs = () => PROJECT_KNOWLEDGE_TIMEOUT_MS) {
80
+ this.db = db;
81
+ this.eventLog = eventLog;
82
+ this.txHost = txHost;
83
+ this.devices = devices;
84
+ this.projects = projects;
85
+ this.sandbox = sandbox;
86
+ this.log = log;
87
+ this.timeoutMs = timeoutMs;
88
+ }
89
+ /**
90
+ * Reads and records (see the class); notifies after the commit. False: the run had ended under
91
+ * the locks (a stop landed while the device was read), so nothing was appended and the run must
92
+ * not go on (as `PluginContextService.record`).
93
+ */
94
+ async record(input) {
95
+ if (input.kind === "subagent")
96
+ return this.copyFromRoot(input);
97
+ if (input.kind !== "chat")
98
+ return true;
99
+ const conv = await this.db.db
100
+ .selectFrom("conversations")
101
+ .select(["account_id", "project_name", "project_path"])
102
+ .where("id", "=", input.conversationId)
103
+ .where("org_id", "=", input.orgId)
104
+ .executeTakeFirst();
105
+ if (!conv || conv.project_name === null || conv.project_path === null)
106
+ return true;
107
+ const payload = await this.read(input, {
108
+ accountId: conv.account_id,
109
+ project: conv.project_name,
110
+ root: conv.project_path,
111
+ });
112
+ if (payload === null)
113
+ return true;
114
+ const seq = await this.append(input, payload);
115
+ if (seq === "ended")
116
+ return false;
117
+ if (seq !== null)
118
+ await this.eventLog.notify(input.conversationId, seq);
119
+ return true;
120
+ }
121
+ /**
122
+ * A sub-agent's run start: the root conversation's latest snapshot appended to the child's log
123
+ * when it differs from the child's latest ({@link append}); nothing when the root has none. No
124
+ * device call, so a replay of the child (which copies the child's own event) never needs one.
125
+ */
126
+ async copyFromRoot(input) {
127
+ const rootId = input.rootConversationId;
128
+ if (rootId === undefined || rootId === input.conversationId)
129
+ return true;
130
+ const latest = await this.db.db
131
+ .selectFrom("conversation_events")
132
+ .select("payload")
133
+ .where("conversation_id", "=", rootId)
134
+ .where("type", "=", "project_root")
135
+ .orderBy("seq", "desc")
136
+ .limit(1)
137
+ .executeTakeFirst();
138
+ if (latest === undefined)
139
+ return true;
140
+ // the stored payload passed the event schema when the root's run start appended it
141
+ const seq = await this.append(input, latest.payload);
142
+ if (seq === "ended")
143
+ return false;
144
+ if (seq !== null)
145
+ await this.eventLog.notify(input.conversationId, seq);
146
+ return true;
147
+ }
148
+ /** The snapshot read on the device, or null when the device could not be asked (logged). */
149
+ async read(input, bound) {
150
+ const where = {
151
+ orgId: input.orgId,
152
+ conversationId: input.conversationId,
153
+ runId: input.runId,
154
+ project: bound.project,
155
+ };
156
+ const signal = AbortSignal.any([input.signal, AbortSignal.timeout(this.timeoutMs())]);
157
+ try {
158
+ // the device a tool call of this conversation would enter, checked for its owner now
159
+ const deviceId = await this.devices.forTool(input.orgId, input.conversationId);
160
+ const scope = await this.projects.scopeFor(input.orgId, bound.accountId, deviceId);
161
+ // the binding is the name and the path: a project removed from the device (or re-added
162
+ // under its name with another path) no longer serves the conversation, which goes on free
163
+ if (!(await this.projects.keeps(deviceId, bound.project, bound.root))) {
164
+ return unavailableProject(bound.project, bound.root, projectUnavailable.removed(bound.project));
165
+ }
166
+ // a device that cannot serve list / scan (a machine without `projects`, a provider without
167
+ // them) is not asked: the project is recorded as unavailable, so an older snapshot stops
168
+ // applying
169
+ if (!scope.supported) {
170
+ this.log.warn("project knowledge not read: the device offers no projects", {
171
+ ...where,
172
+ deviceId,
173
+ });
174
+ return unavailableProject(bound.project, bound.root, projectUnavailable.unsupported());
175
+ }
176
+ // stat / readFile carry no ceiling: a machine running a wider mode than the org allows is
177
+ // not read unasked (exec refuses it too)
178
+ if (scope.widerThanAllowed) {
179
+ this.log.warn("project knowledge not read: the device runs a wider mode than allowed", {
180
+ ...where,
181
+ deviceId,
182
+ });
183
+ return unavailableProject(bound.project, bound.root, projectUnavailable.widerMode(bound.root));
184
+ }
185
+ return await this.sandbox.withSandbox({
186
+ orgId: input.orgId,
187
+ deviceId,
188
+ holderConversationId: input.conversationId,
189
+ // the read tells the model nothing: its first tool call still learns that the device
190
+ // started, restarted or had its files reset
191
+ silent: true,
192
+ actor: {
193
+ accountId: bound.accountId,
194
+ conversationId: input.conversationId,
195
+ runId: input.runId,
196
+ },
197
+ }, async (h, p, info, sig) => {
198
+ const target = { project: bound.project, root: bound.root, mode: scope.mode };
199
+ // the kernel's own check first: a root the mode cannot read is never asked about
200
+ // a root above the owner's home is refused as the working root's rule refuses it
201
+ // (`workingRootOf`, the same home: the reported one, else the workspace's prefix)
202
+ const reported = scope.home;
203
+ const home = reported?.startsWith("/") ? reported : homeOf(info.roots.workspace);
204
+ if (!withinMode(scope, bound.root, info.roots.workspace) || aboveHome(bound.root, home)) {
205
+ return unavailableProject(bound.project, bound.root, projectUnavailable.outsideMode(bound.root, scope.mode));
206
+ }
207
+ const list = p.list;
208
+ const files = {
209
+ stat: (path) => p.stat(h, path, sig),
210
+ readFile: (path, maxBytes) => p.readFile(h, path, { maxBytes, signal: sig }),
211
+ ...(list !== undefined && {
212
+ list: (path, limit) => list.call(p, h, path, { limit, limits: { mode: scope.mode }, signal: sig }),
213
+ }),
214
+ };
215
+ return readProjectKnowledge(files, target, {
216
+ log: (msg, detail) => this.log.info(msg, { ...where, ...detail }),
217
+ isDeviceFailure: (e) => sig.aborted || isDeviceFailure(e),
218
+ });
219
+ }, signal);
220
+ }
221
+ catch (err) {
222
+ this.log.warn("project knowledge not read: the device could not be asked; the run goes on", {
223
+ ...where,
224
+ timedOut: signal.aborted && !input.signal.aborted,
225
+ err,
226
+ });
227
+ return null;
228
+ }
229
+ }
230
+ /**
231
+ * One transaction under the conversation row lock (as `PluginContextService`): compares the
232
+ * snapshot with the conversation's latest `project_root` and appends it when it differs, with
233
+ * the run's idempotency key, so a retried run start finds its event (or nothing changed).
234
+ * Returns the seq written, null for none, `ended` when the run is terminal under the locks.
235
+ */
236
+ async append(input, payload) {
237
+ const t = this.db.db;
238
+ await t
239
+ .selectFrom("conversations")
240
+ .select("id")
241
+ .where("id", "=", input.conversationId)
242
+ .forUpdate()
243
+ .executeTakeFirst();
244
+ if (await runEndedIn(t, input.runId))
245
+ return "ended";
246
+ const latest = await t
247
+ .selectFrom("conversation_events")
248
+ .select(["seq", "payload"])
249
+ .where("conversation_id", "=", input.conversationId)
250
+ .where("type", "=", "project_root")
251
+ .orderBy("seq", "desc")
252
+ .limit(1)
253
+ .executeTakeFirst();
254
+ // the stored payload passed the event schema when it was appended (`skills` defaulted)
255
+ if (latest !== undefined && sameProjectRoot(latest.payload, payload)) {
256
+ return null;
257
+ }
258
+ const [written] = await this.eventLog.appendIn(input.conversationId, [
259
+ {
260
+ type: "project_root",
261
+ runId: input.runId,
262
+ idemKey: projectRootIdemKey(input.runId),
263
+ payload,
264
+ },
265
+ ]);
266
+ // an earlier attempt of this run start already wrote its snapshot: nothing new to tell
267
+ if (written === undefined || (latest !== undefined && written.seq <= Number(latest.seq))) {
268
+ return null;
269
+ }
270
+ return written.seq;
271
+ }
272
+ };
273
+ __decorate([
274
+ Transactional()
275
+ ], ProjectKnowledgeService.prototype, "append", null);
276
+ ProjectKnowledgeService = __decorate([
277
+ Injectable(),
278
+ __param(0, Inject(KernelDb)),
279
+ __param(1, Inject(EventLog)),
280
+ __param(2, Inject(TransactionHost)),
281
+ __param(3, Inject(ConversationDevices)),
282
+ __param(4, Inject(DeviceProjectsService)),
283
+ __param(5, Inject(SandboxService)),
284
+ __param(6, Inject(KERNEL_LOGGER)),
285
+ __param(7, Optional()),
286
+ __param(7, Inject(PROJECT_KNOWLEDGE_TIMEOUT))
287
+ ], ProjectKnowledgeService);
288
+ export { ProjectKnowledgeService };
@@ -14,6 +14,7 @@ import { KyselyCheckpointSaver } from "./checkpointer.js";
14
14
  import { CompactionService } from "./compaction.service.js";
15
15
  import { ConversationLock } from "./conversation-lock.js";
16
16
  import { PluginContextService } from "./plugin-context.service.js";
17
+ import { ProjectKnowledgeService } from "./project/knowledge.service.js";
17
18
  import { ProviderRegistry } from "./providers.js";
18
19
  import { type OrgQuota } from "./quota.js";
19
20
  import { RunContextService } from "./run-context.service.js";
@@ -77,6 +78,8 @@ export declare class RunWorker {
77
78
  private readonly runContext;
78
79
  /** Run start's plugin context (memory plugin spec §6.1): the `context@1` providers' text. */
79
80
  private readonly pluginContext;
81
+ /** Run start's project knowledge (project root spec §4.4): a bound project's AGENTS.md, skills. */
82
+ private readonly projectKnowledge;
80
83
  /** The run's resolved tools, for the plugin context's `tools` (chat runs with providers). */
81
84
  private readonly tools;
82
85
  private readonly finisher;
@@ -110,6 +113,8 @@ export declare class RunWorker {
110
113
  runContext: Pick<RunContextService, "record">,
111
114
  /** Run start's plugin context (memory plugin spec §6.1): the `context@1` providers' text. */
112
115
  pluginContext: Pick<PluginContextService, "record">,
116
+ /** Run start's project knowledge (project root spec §4.4): a bound project's AGENTS.md, skills. */
117
+ projectKnowledge: Pick<ProjectKnowledgeService, "record">,
113
118
  /** The run's resolved tools, for the plugin context's `tools` (chat runs with providers). */
114
119
  tools: Pick<ToolRegistry, "forAgent">, finisher: Pick<RunFinish, "finish">, txHost: TransactionHost,
115
120
  /** The steps' live drafts this process writes for the runs it executes. */