@capybara-hq/kernel 0.1.0-rc.97 → 0.1.0-rc.99

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 (80) hide show
  1. package/bootstrap.json +17 -17
  2. package/dist/catalog/git-source.d.ts +5 -0
  3. package/dist/catalog/git-source.js +9 -5
  4. package/dist/catalog/marketplace-fetch.d.ts +9 -0
  5. package/dist/catalog/marketplace-fetch.js +9 -5
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/channels/channels.schemas.d.ts +10 -0
  8. package/dist/channels/channels.schemas.js +7 -0
  9. package/dist/channels/connections.service.d.ts +7 -0
  10. package/dist/channels/connections.service.js +4 -0
  11. package/dist/channels/features.d.ts +18 -1
  12. package/dist/channels/features.js +22 -0
  13. package/dist/channels/outbound.d.ts +19 -0
  14. package/dist/channels/outbound.js +531 -18
  15. package/dist/channels/phrases.d.ts +10 -0
  16. package/dist/channels/phrases.js +4 -0
  17. package/dist/channels/progress.d.ts +75 -0
  18. package/dist/channels/progress.js +216 -0
  19. package/dist/conversations/event-log.d.ts +8 -2
  20. package/dist/conversations/events.d.ts +6 -0
  21. package/dist/conversations/events.js +7 -1
  22. package/dist/conversations/prompt-suggestions.js +2 -2
  23. package/dist/db/kernel-schema.d.ts +16 -0
  24. package/dist/evals/run-replay.js +2 -2
  25. package/dist/evals/step-replay.js +2 -2
  26. package/dist/evals/worker.js +3 -1
  27. package/dist/extensions/plugin-icons.d.ts +7 -0
  28. package/dist/extensions/plugin-icons.js +8 -0
  29. package/dist/models/purposes.js +2 -2
  30. package/dist/net/safe-fetch.d.ts +22 -4
  31. package/dist/net/safe-fetch.js +74 -0
  32. package/dist/platform/file-ref.d.ts +2 -0
  33. package/dist/platform/file-ref.js +1 -3
  34. package/dist/platform/ops/channels.ops.js +24 -5
  35. package/dist/runtime/model-call.d.ts +23 -2
  36. package/dist/runtime/model-call.js +64 -9
  37. package/dist/runtime/run-drafts.d.ts +46 -4
  38. package/dist/runtime/run-drafts.js +110 -9
  39. package/dist/runtime/run-steps.d.ts +2 -1
  40. package/dist/runtime/run-steps.js +6 -2
  41. package/dist/runtime/runtime.module.js +3 -0
  42. package/dist/runtime/stream.controller.d.ts +7 -5
  43. package/dist/runtime/stream.controller.js +10 -6
  44. package/dist/runtime/stream.js +9 -1
  45. package/dist/runtime/write-base.d.ts +95 -0
  46. package/dist/runtime/write-base.js +281 -0
  47. package/dist/runtime/write-base.service.d.ts +68 -0
  48. package/dist/runtime/write-base.service.js +184 -0
  49. package/dist/sandbox/kernel-read.d.ts +39 -9
  50. package/dist/sandbox/kernel-read.js +33 -3
  51. package/dist/sandbox/operation-authority.d.ts +16 -12
  52. package/dist/sandbox/operation-authority.js +33 -20
  53. package/dist/sandbox/operation-intents.d.ts +10 -4
  54. package/dist/sandbox/operation-intents.js +31 -11
  55. package/dist/sandbox/sandbox.service.d.ts +30 -7
  56. package/dist/sandbox/sandbox.service.js +47 -13
  57. package/dist/tools/builtins/agent.js +4 -0
  58. package/dist/tools/builtins/image/generate.js +1 -0
  59. package/dist/tools/builtins/platform.js +4 -3
  60. package/dist/tools/builtins/sandbox/bash.d.ts +3 -1
  61. package/dist/tools/builtins/sandbox/bash.js +23 -11
  62. package/dist/tools/builtins/sandbox/common.d.ts +4 -1
  63. package/dist/tools/builtins/sandbox/common.js +5 -2
  64. package/dist/tools/builtins/sandbox/edit.js +1 -0
  65. package/dist/tools/builtins/sandbox/glob.js +2 -1
  66. package/dist/tools/builtins/sandbox/grep.js +2 -1
  67. package/dist/tools/builtins/sandbox/search-command.d.ts +4 -3
  68. package/dist/tools/builtins/sandbox/search-command.js +11 -3
  69. package/dist/tools/builtins/sandbox/write.js +1 -0
  70. package/dist/tools/builtins/send-message.js +1 -0
  71. package/dist/tools/info.d.ts +21 -2
  72. package/dist/tools/info.js +55 -12
  73. package/dist/tools/network-asks.d.ts +23 -0
  74. package/dist/tools/network-asks.js +24 -5
  75. package/dist/tools/pipeline.d.ts +3 -1
  76. package/dist/tools/pipeline.js +76 -12
  77. package/dist/tools/registry.d.ts +12 -11
  78. package/dist/tools/registry.js +6 -5
  79. package/package.json +3 -3
  80. package/src/migrations/0185_channel_process_display.sql +13 -0
@@ -0,0 +1,184 @@
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 { ToolError } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { EventLog } from "../conversations/event-log.js";
13
+ import { DeviceAccess } from "../devices/access.js";
14
+ import { ApiError } from "../errors.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
17
+ import { KernelReadInstanceNotRunning, KernelReadNotAdmitted, KernelReadUnsupported, } from "../sandbox/kernel-read.js";
18
+ import { RetirementPendingError, SandboxService } from "../sandbox/sandbox.service.js";
19
+ import { checkFilePathShape, checkToolPath, looksBinary, } from "../tools/builtins/sandbox/common.js";
20
+ import { fileStateOf, lastFileState, normalizeSandboxPath, } from "../tools/builtins/sandbox/file-state.js";
21
+ import { TOOL_VIEW_DIFF_MAX_BYTES, TOOL_VIEW_DIFF_MAX_TEXT_BYTES } from "../tools/view.js";
22
+ import { currentExecutionClaim } from "./run-execution.js";
23
+ /**
24
+ * Reads the base of a streaming `Write` of `rawPath` in `conversationId`, or null (§4.1):
25
+ * 1. The path as `Write` takes it (`checkFilePathShape`, `checkToolPath`, normalized). A relative
26
+ * path gets none here: it resolves against the working root only inside a tool's use.
27
+ * 2. The step's current execution claim, for this conversation. The log's latest recorded state
28
+ * of the path (`lastFileState`): none, or one above `TOOL_VIEW_DIFF_MAX_TEXT_BYTES`, gives none.
29
+ * 3. A `write_base` kernel read (`withKernelRead`: the run `running`, `stat` / `readFile` of exactly
30
+ * the path, never making, waking or resuming an instance, no path lease), at most
31
+ * `TOOL_VIEW_DIFF_MAX_TEXT_BYTES` read (below `TOOL_VIEW_DIFF_MAX_BYTES`). A path in the skills
32
+ * directory (read-only to `Write`), a directory, a missing file, a cut read, a NUL byte, a size
33
+ * or sha256 other than the recorded state's: none. The state check is the guard that the base
34
+ * shows nothing the conversation had not already read unchanged (symlink targets included).
35
+ * Every failure (a refused admission, `KernelReadInstanceNotRunning`, a read error, an abort) gives
36
+ * none; an expected one ({@link expectedNoBase}) is logged at debug, any other as a warning.
37
+ */
38
+ export async function readWriteBase(deps, input) {
39
+ const { conversationId, signal } = input;
40
+ try {
41
+ if (!input.path.startsWith("/"))
42
+ return null;
43
+ checkFilePathShape(input.path);
44
+ const path = normalizeSandboxPath(checkToolPath(input.path, "file_path"));
45
+ if (path === "/")
46
+ return null;
47
+ const claim = deps.claim();
48
+ if (!claim || claim.conversationId !== conversationId)
49
+ return null;
50
+ const seen = await lastFileState(deps.eventLog, conversationId, path);
51
+ if (seen === null || seen.size > TOOL_VIEW_DIFF_MAX_TEXT_BYTES)
52
+ return null;
53
+ signal.throwIfAborted();
54
+ const facts = await deps.runFacts(claim);
55
+ if (facts === null)
56
+ return null;
57
+ // checked last before the read: an attempt that ended starts no admission
58
+ signal.throwIfAborted();
59
+ const data = await deps.sandbox.withKernelRead({
60
+ orgId: claim.orgId,
61
+ deviceId: facts.deviceId,
62
+ holderConversationId: conversationId,
63
+ // a display-only read tells the model nothing
64
+ silent: true,
65
+ actor: { accountId: facts.accountId, conversationId, runId: claim.runId },
66
+ }, { claim, purpose: "write_base", path }, async (h, p, info, sig) => {
67
+ const skills = info.roots.skills;
68
+ if (path === skills || path.startsWith(`${skills}/`))
69
+ return null;
70
+ const st = await p.stat(h, path, sig);
71
+ if (st === null || st.isDir || st.size !== seen.size)
72
+ return null;
73
+ const got = await p.readFile(h, path, {
74
+ maxBytes: Math.min(TOOL_VIEW_DIFF_MAX_TEXT_BYTES, TOOL_VIEW_DIFF_MAX_BYTES),
75
+ signal: sig,
76
+ });
77
+ if (got === null || got.truncated)
78
+ return null;
79
+ return got.data;
80
+ }, signal);
81
+ if (data === null || signal.aborted)
82
+ return null;
83
+ if (data.byteLength > TOOL_VIEW_DIFF_MAX_TEXT_BYTES)
84
+ return null;
85
+ const now = fileStateOf(data, data.byteLength);
86
+ if (now.size !== seen.size || now.sha256 !== seen.sha256)
87
+ return null;
88
+ if (looksBinary(data) || data.includes(0))
89
+ return null;
90
+ const text = utf8(data);
91
+ // bytes that are not UTF-8 are binary here: no base
92
+ return text === null ? null : { text, sha256: now.sha256 };
93
+ }
94
+ catch (err) {
95
+ if (signal.aborted)
96
+ return null;
97
+ // an outcome the person simply gets no base for: debug; anything else: warn
98
+ const level = expectedNoBase(err) ? "debug" : "warn";
99
+ deps.log[level]("write base not read; the row streams without it", { conversationId, err });
100
+ return null;
101
+ }
102
+ }
103
+ /** `data` as UTF-8 text, or null when it is not valid UTF-8. */
104
+ function utf8(data) {
105
+ try {
106
+ return new TextDecoder("utf-8", { fatal: true }).decode(data);
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ /**
113
+ * The failures that only mean "no base now": the device's instance is not running, the read was
114
+ * not admitted (the run moved on, the authority refused it) or its runtime cannot enforce a
115
+ * read-only read, the sandbox is busy, the device is gone, its provider off or an earlier instance
116
+ * still awaits retirement, or the model's path is malformed (`Write` refuses it with the same
117
+ * `ToolError`).
118
+ */
119
+ export function expectedNoBase(err) {
120
+ if (err instanceof KernelReadInstanceNotRunning ||
121
+ err instanceof KernelReadNotAdmitted ||
122
+ err instanceof KernelReadUnsupported ||
123
+ err instanceof RetirementPendingError ||
124
+ err instanceof ToolError)
125
+ return true;
126
+ return (err instanceof ApiError &&
127
+ (err.code === "device.unavailable" ||
128
+ err.code === "device.not_found" ||
129
+ err.code === "sandbox.busy"));
130
+ }
131
+ /**
132
+ * The run worker's {@link WriteBaseReader} (streaming tool input spec §4.1): {@link readWriteBase}
133
+ * over the event log, the sandbox's kernel read and the run's facts read from PG. The device is
134
+ * the one the conversation tree is already bound to (never bound here), used only when the run's
135
+ * trigger account owns the conversation, its root and the device, and the device's provider is
136
+ * on in the org (`DeviceAccess.usable`), as a `Write` call would require.
137
+ */
138
+ let WriteBaseService = class WriteBaseService {
139
+ deps;
140
+ constructor(db, eventLog, sandbox, access, log) {
141
+ this.deps = {
142
+ claim: currentExecutionClaim,
143
+ eventLog,
144
+ sandbox,
145
+ log,
146
+ runFacts: async (claim) => {
147
+ const run = await db.db
148
+ .selectFrom("runs")
149
+ .select("trigger_account_id")
150
+ .where("id", "=", claim.runId)
151
+ .where("conversation_id", "=", claim.conversationId)
152
+ .executeTakeFirst();
153
+ const convs = await db.db
154
+ .selectFrom("conversations")
155
+ .select(["id", "account_id", "device_id"])
156
+ .where("org_id", "=", claim.orgId)
157
+ .where("id", "in", [claim.conversationId, claim.rootId])
158
+ .execute();
159
+ const own = convs.find((c) => c.id === claim.conversationId);
160
+ const root = convs.find((c) => c.id === claim.rootId);
161
+ if (!run || !own || !root || root.device_id === null)
162
+ return null;
163
+ const accountId = run.trigger_account_id;
164
+ // a run another account triggered never uses the owner's device
165
+ if (own.account_id !== accountId || root.account_id !== accountId)
166
+ return null;
167
+ const device = await access.usable(claim.orgId, accountId, root.device_id);
168
+ return { deviceId: device.id, accountId };
169
+ },
170
+ };
171
+ }
172
+ read(input) {
173
+ return readWriteBase(this.deps, input);
174
+ }
175
+ };
176
+ WriteBaseService = __decorate([
177
+ Injectable(),
178
+ __param(0, Inject(KernelDb)),
179
+ __param(1, Inject(EventLog)),
180
+ __param(2, Inject(SandboxService)),
181
+ __param(3, Inject(DeviceAccess)),
182
+ __param(4, Inject(KERNEL_LOGGER))
183
+ ], WriteBaseService);
184
+ export { WriteBaseService };
@@ -1,16 +1,31 @@
1
1
  import type { ExecutionClaim } from "../runtime/run-execution.js";
2
2
  /**
3
- * A kernel read of a device on behalf of a run start (permission activation L2, Hook 1): the
4
- * run's current execution claim and what is read. Only `project_root` exists: the bound project's
5
- * `AGENTS.md` and `.agents/skills/**` read before the run's first model call. Supplied only by
6
- * `ProjectKnowledgeService`, never by a tool, a Platform operation or an HTTP route.
3
+ * A kernel read of a device on behalf of a run (permission activation L2), never a tool's, a
4
+ * Platform operation's or an HTTP route's: the run's current execution claim and what is read.
5
+ * - `project_root`: the bound project's `AGENTS.md` and `.agents/skills/**`, read by
6
+ * `ProjectKnowledgeService` before the run's first model call (the run still `queued`).
7
+ * - `write_base`: the current content of the one file a streaming `Write` is about to overwrite,
8
+ * read only to show the person a live diff (streaming tool input spec §4.1): the run `running`,
9
+ * `stat` and `readFile` of exactly `path`, never making, waking or resuming an instance, no path
10
+ * lease. Display only: it never reaches the model, the log or a hook.
7
11
  */
8
- export interface KernelReadInvocation {
12
+ export type KernelReadInvocation = {
9
13
  claim: ExecutionClaim;
10
14
  purpose: "project_root";
11
15
  /** The conversation's bound project root (`conversations.project_path`). */
12
16
  root: string;
13
- }
17
+ } | {
18
+ claim: ExecutionClaim;
19
+ purpose: "write_base";
20
+ /** The one clean, absolute file path the read may reach. */
21
+ path: string;
22
+ };
23
+ /** What a kernel read reaches, without its claim. */
24
+ export type KernelReadTarget = Omit<Extract<KernelReadInvocation, {
25
+ purpose: "project_root";
26
+ }>, "claim"> | Omit<Extract<KernelReadInvocation, {
27
+ purpose: "write_base";
28
+ }>, "claim">;
14
29
  /** The directory of a project's skills, relative to its root (project root spec §4.7). */
15
30
  export declare const PROJECT_SKILLS_DIR = ".agents/skills";
16
31
  /** The methods a kernel read may use: never a write, an exec or a scan. */
@@ -25,9 +40,24 @@ export declare const isKernelReadMethod: (method: string) => method is KernelRea
25
40
  */
26
41
  export declare function kernelReadRoot(root: string, method: KernelReadMethod, path: string): string | null;
27
42
  /**
28
- * A kernel read that was not admitted (its run is no longer the claim's queued run start, the
29
- * authority refused it, its scope changed before dispatch): nothing was sent to the device. The
30
- * knowledge read treats it as a device that could not be asked, never as an unreadable project.
43
+ * The one path a kernel read of `read` may reach with `method` that covers `path`, the
44
+ * operation's only read root; null when the read is outside it. `project_root`: {@link
45
+ * kernelReadRoot}. `write_base`: `stat` or `readFile` of exactly its clean, absolute path, nothing
46
+ * else (no `list`, no other path, no parent or child).
47
+ */
48
+ export declare function kernelReadCovering(read: KernelReadTarget, method: KernelReadMethod, path: string): string | null;
49
+ /**
50
+ * A `write_base` kernel read of a device whose instance is not running (none yet, suspended,
51
+ * being made, destroyed or replaced): nothing was made, woken or resumed and nothing was sent.
52
+ */
53
+ export declare class KernelReadInstanceNotRunning extends Error {
54
+ constructor();
55
+ }
56
+ /**
57
+ * A kernel read that was not admitted (its run is no longer the claim's run in the state its
58
+ * purpose needs, the authority refused it, its scope changed before dispatch): nothing was sent to
59
+ * the device. The knowledge read treats it as a device that could not be asked, never as an
60
+ * unreadable project.
31
61
  */
32
62
  export declare class KernelReadNotAdmitted extends Error {
33
63
  constructor(cause: unknown);
@@ -28,9 +28,39 @@ export function kernelReadRoot(root, method, path) {
28
28
  return null;
29
29
  }
30
30
  /**
31
- * A kernel read that was not admitted (its run is no longer the claim's queued run start, the
32
- * authority refused it, its scope changed before dispatch): nothing was sent to the device. The
33
- * knowledge read treats it as a device that could not be asked, never as an unreadable project.
31
+ * The one path a kernel read of `read` may reach with `method` that covers `path`, the
32
+ * operation's only read root; null when the read is outside it. `project_root`: {@link
33
+ * kernelReadRoot}. `write_base`: `stat` or `readFile` of exactly its clean, absolute path, nothing
34
+ * else (no `list`, no other path, no parent or child).
35
+ */
36
+ export function kernelReadCovering(read, method, path) {
37
+ if (read.purpose === "project_root")
38
+ return kernelReadRoot(read.root, method, path);
39
+ if (read.purpose !== "write_base")
40
+ return null;
41
+ if (method !== "stat" && method !== "readFile")
42
+ return null;
43
+ if (validateSandboxPathShape(read.path).length > 0 || posix.normalize(read.path) !== read.path)
44
+ return null;
45
+ if (read.path === "/" || path !== read.path)
46
+ return null;
47
+ return read.path;
48
+ }
49
+ /**
50
+ * A `write_base` kernel read of a device whose instance is not running (none yet, suspended,
51
+ * being made, destroyed or replaced): nothing was made, woken or resumed and nothing was sent.
52
+ */
53
+ export class KernelReadInstanceNotRunning extends Error {
54
+ constructor() {
55
+ super("The device's instance is not running; a display-only read never starts it");
56
+ this.name = "KernelReadInstanceNotRunning";
57
+ }
58
+ }
59
+ /**
60
+ * A kernel read that was not admitted (its run is no longer the claim's run in the state its
61
+ * purpose needs, the authority refused it, its scope changed before dispatch): nothing was sent to
62
+ * the device. The knowledge read treats it as a device that could not be asked, never as an
63
+ * unreadable project.
34
64
  */
35
65
  export class KernelReadNotAdmitted extends Error {
36
66
  constructor(cause) {
@@ -4,7 +4,7 @@ import { PermissionProfileStore } from "../conversations/permission-profile-stor
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
5
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
6
  import type { DeviceSandbox } from "./device-sandbox.js";
7
- import { type KernelReadInvocation, type KernelReadMethod } from "./kernel-read.js";
7
+ import { type KernelReadMethod, type KernelReadTarget } from "./kernel-read.js";
8
8
  import { NetworkGrants } from "./network-grants.js";
9
9
  import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
10
10
  import { PermissionAuthorityLock } from "./permission-authority-lock.js";
@@ -94,19 +94,23 @@ export declare class SandboxOperationAuthority {
94
94
  executionGrants: import("./operation-authority-types.js").StartingExecutionGrants | null;
95
95
  }>;
96
96
  /**
97
- * The scope of one kernel read (permission activation L2, Hook 1): the conversation's profile
98
- * scope from the same authority snapshot admission reads, with the bound project as the working
99
- * root it becomes once read (the review's fallbacks apply: a root outside the mode or above the
100
- * home is refused), intersected with the one path the read may reach
101
- * ({@link kernelReadRoot}: the root's `stat`, `AGENTS.md`, `.agents/skills/**`). The restricted
102
- * {@link KERNEL_READ_PROFILE} whenever the runtime enforces it (the runtime then enforces the
103
- * read root, symlinks included); the conversation's admitted Full access only on an isolated
104
- * Full-only runtime; a host machine without restricted enforcement throws
97
+ * The scope of one kernel read (permission activation L2): the conversation's profile scope from
98
+ * the same authority snapshot admission reads, intersected with the one path the read may reach
99
+ * ({@link kernelReadCovering}). By purpose:
100
+ * - `project_root` (Hook 1): the bound project as the working root it becomes once read (the
101
+ * review's fallbacks apply: a root outside the mode or above the home is refused); the root's
102
+ * `stat`, `AGENTS.md`, `.agents/skills/**`.
103
+ * - `write_base` (streaming tool input spec §4.1): the working root admission decides for a tool
104
+ * call; `stat` and `readFile` of exactly the one path, which must lie strictly inside that
105
+ * working root, never the root itself (a path a `Write` reaches only by escalation gets no
106
+ * base).
107
+ * The restricted {@link KERNEL_READ_PROFILE} whenever the runtime enforces it (the runtime then
108
+ * enforces the read root, symlinks included); the conversation's admitted Full access only on an
109
+ * isolated Full-only runtime; a host machine without restricted enforcement throws
105
110
  * {@link KernelReadUnsupported} ({@link kernelReadRoute}). No write roots, no hosts, never a
106
- * per-call grant. Called under the run start's claim only (the intents
107
- * check that its run is still `queued`).
111
+ * per-call grant. Called under the run's claim only (the intents check its run state).
108
112
  */
109
- resolveKernelRead(ctx: SandboxUseContext, read: Pick<KernelReadInvocation, "purpose" | "root">, method: KernelReadMethod, path: string, signal: AbortSignal): Promise<SandboxOperationScope>;
113
+ resolveKernelRead(ctx: SandboxUseContext, read: KernelReadTarget, method: KernelReadMethod, path: string, signal: AbortSignal): Promise<SandboxOperationScope>;
110
114
  private scopeOf;
111
115
  private snapshot;
112
116
  /**
@@ -19,7 +19,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
19
19
  import { TransactionHost, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
20
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { hostGrantable } from "./device-sandbox.js";
22
- import { KernelReadUnsupported, kernelReadRoot, kernelReadRoute, } from "./kernel-read.js";
22
+ import { KernelReadUnsupported, kernelReadCovering, kernelReadRoute, } from "./kernel-read.js";
23
23
  import { coversHost } from "./modes.js";
24
24
  import { NetworkGrants } from "./network-grants.js";
25
25
  import { EscalationGrantMissingError, isExecutionMethod, parseStartingExecutionGrants, } from "./operation-authority-types.js";
@@ -324,30 +324,43 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
324
324
  return { scope, permissionGrantId, grantedHosts: hosts, executionGrants };
325
325
  }
326
326
  /**
327
- * The scope of one kernel read (permission activation L2, Hook 1): the conversation's profile
328
- * scope from the same authority snapshot admission reads, with the bound project as the working
329
- * root it becomes once read (the review's fallbacks apply: a root outside the mode or above the
330
- * home is refused), intersected with the one path the read may reach
331
- * ({@link kernelReadRoot}: the root's `stat`, `AGENTS.md`, `.agents/skills/**`). The restricted
332
- * {@link KERNEL_READ_PROFILE} whenever the runtime enforces it (the runtime then enforces the
333
- * read root, symlinks included); the conversation's admitted Full access only on an isolated
334
- * Full-only runtime; a host machine without restricted enforcement throws
327
+ * The scope of one kernel read (permission activation L2): the conversation's profile scope from
328
+ * the same authority snapshot admission reads, intersected with the one path the read may reach
329
+ * ({@link kernelReadCovering}). By purpose:
330
+ * - `project_root` (Hook 1): the bound project as the working root it becomes once read (the
331
+ * review's fallbacks apply: a root outside the mode or above the home is refused); the root's
332
+ * `stat`, `AGENTS.md`, `.agents/skills/**`.
333
+ * - `write_base` (streaming tool input spec §4.1): the working root admission decides for a tool
334
+ * call; `stat` and `readFile` of exactly the one path, which must lie strictly inside that
335
+ * working root, never the root itself (a path a `Write` reaches only by escalation gets no
336
+ * base).
337
+ * The restricted {@link KERNEL_READ_PROFILE} whenever the runtime enforces it (the runtime then
338
+ * enforces the read root, symlinks included); the conversation's admitted Full access only on an
339
+ * isolated Full-only runtime; a host machine without restricted enforcement throws
335
340
  * {@link KernelReadUnsupported} ({@link kernelReadRoute}). No write roots, no hosts, never a
336
- * per-call grant. Called under the run start's claim only (the intents
337
- * check that its run is still `queued`).
341
+ * per-call grant. Called under the run's claim only (the intents check its run state).
338
342
  */
339
343
  async resolveKernelRead(ctx, read, method, path, signal) {
340
- if (read.purpose !== "project_root")
344
+ if (read.purpose !== "project_root" && read.purpose !== "write_base")
341
345
  throw new ApiError("forbidden", "Unknown kernel read purpose");
342
- const covering = kernelReadRoot(read.root, method, path);
346
+ const covering = kernelReadCovering(read, method, path);
343
347
  if (covering === null)
344
- throw new ApiError("forbidden", "A kernel read reaches only the project's root, its AGENTS.md and its .agents/skills");
345
- const f = await this.snapshot(ctx, { runId: ctx.actor.runId ?? "", callId: "" }, signal, undefined, { projectUsable: true });
346
- const bound = await this.profiles.readOwnedRoot(ctx.orgId, ctx.holderConversationId, ctx.actor.accountId);
347
- if (bound.project_path === null ||
348
- canonicalRoot(bound.project_path) !== canonicalRoot(read.root) ||
349
- canonicalRoot(f.workingRoot) !== canonicalRoot(read.root))
350
- throw new ApiError("forbidden", "The kernel read's root is not the conversation's usable project root");
348
+ throw new ApiError("forbidden", read.purpose === "project_root"
349
+ ? "A kernel read reaches only the project's root, its AGENTS.md and its .agents/skills"
350
+ : "A write base read reaches only its one file, by stat or readFile");
351
+ const f = await this.snapshot(ctx, { runId: ctx.actor.runId ?? "", callId: "" }, signal, undefined, read.purpose === "project_root" ? { projectUsable: true } : {});
352
+ if (read.purpose === "project_root") {
353
+ const bound = await this.profiles.readOwnedRoot(ctx.orgId, ctx.holderConversationId, ctx.actor.accountId);
354
+ if (bound.project_path === null ||
355
+ canonicalRoot(bound.project_path) !== canonicalRoot(read.root) ||
356
+ canonicalRoot(f.workingRoot) !== canonicalRoot(read.root))
357
+ throw new ApiError("forbidden", "The kernel read's root is not the conversation's usable project root");
358
+ }
359
+ else if (
360
+ // exactly one file inside the working root, never the root directory itself
361
+ canonicalRoot(covering) === canonicalRoot(f.workingRoot) ||
362
+ !withinDirectory(covering, f.workingRoot))
363
+ throw new ApiError("forbidden", "The write base read is outside the conversation's working root");
351
364
  // the recorded runtime support decides the route: restricted when enforced, Full access only
352
365
  // on an isolated Full-only runtime, nothing on a host machine without restricted enforcement
353
366
  const availability = f.availability;
@@ -104,9 +104,10 @@ export declare class SandboxOperationIntents {
104
104
  accountId: string;
105
105
  }, instance: OperationInstance, method: "stat" | "list" | "scan", input: unknown, signal: AbortSignal): Promise<OperationIntent>;
106
106
  /**
107
- * The run start's kernel read (permission activation L2, Hook 1): the run must still be the
108
- * claim's execution, triggered by the actor and `queued` (a run start reads before its run is
109
- * running), checked in PG under the authority locks the caller already holds.
107
+ * The run of a kernel read (permission activation L2): the run must still be the claim's
108
+ * execution, triggered by the actor and in the state its purpose reads in, checked in PG under
109
+ * the authority locks the caller already holds. `project_root` reads before its run's first
110
+ * model call (`queued`); `write_base` reads while its run streams a `Write` (`running`).
110
111
  */
111
112
  private assertKernelReadRun;
112
113
  /**
@@ -202,7 +203,12 @@ export declare class SandboxOperationIntents {
202
203
  * retention expiry job settles what is never resolved.
203
204
  */
204
205
  deferBackgroundRecovery(id: string): Promise<void>;
205
- complete(id: string, executionId: string, result: unknown): Promise<void>;
206
+ complete(id: string, executionId: string, result: unknown,
207
+ /**
208
+ * A kernel read's purpose: required for a row with a run and no tool call (a kernel read),
209
+ * whose run state it decides; never defaulted, so a caller that forgets it fails loudly.
210
+ */
211
+ kernelRead?: KernelReadInvocation["purpose"]): Promise<void>;
206
212
  result(row: OperationIntent): Promise<unknown>;
207
213
  /**
208
214
  * The dispatcher with `executionId` gave up on its dispatch: its outcome is unknown. Fenced by
@@ -311,11 +311,18 @@ let SandboxOperationIntents = class SandboxOperationIntents {
311
311
  return row;
312
312
  }
313
313
  /**
314
- * The run start's kernel read (permission activation L2, Hook 1): the run must still be the
315
- * claim's execution, triggered by the actor and `queued` (a run start reads before its run is
316
- * running), checked in PG under the authority locks the caller already holds.
314
+ * The run of a kernel read (permission activation L2): the run must still be the claim's
315
+ * execution, triggered by the actor and in the state its purpose reads in, checked in PG under
316
+ * the authority locks the caller already holds. `project_root` reads before its run's first
317
+ * model call (`queued`); `write_base` reads while its run streams a `Write` (`running`).
317
318
  */
318
- async assertKernelReadRun(ctx, c) {
319
+ async assertKernelReadRun(ctx, read) {
320
+ const c = read.claim;
321
+ const status = read.purpose === "project_root"
322
+ ? "queued"
323
+ : read.purpose === "write_base"
324
+ ? "running"
325
+ : denied("Unknown kernel read purpose");
319
326
  const run = await this.db
320
327
  .selectFrom("runs")
321
328
  .select(["execution_id", "trigger_account_id", "status"])
@@ -326,8 +333,8 @@ let SandboxOperationIntents = class SandboxOperationIntents {
326
333
  if (!run ||
327
334
  run.execution_id !== c.executionId ||
328
335
  run.trigger_account_id !== ctx.actor.accountId ||
329
- run.status !== "queued")
330
- denied("The run start's execution claim is no longer current");
336
+ run.status !== status)
337
+ denied("The kernel read's execution claim is no longer current");
331
338
  }
332
339
  /**
333
340
  * Admits one kernel read (Hook 1), modelled on {@link admitBrowse}: a random operation id per
@@ -348,7 +355,7 @@ let SandboxOperationIntents = class SandboxOperationIntents {
348
355
  const scope = await this.authority.resolveKernelRead(ctx, read, method, input.path, signal);
349
356
  if (scope.rootConversationId !== c.rootId)
350
357
  denied("The kernel read's root no longer matches the execution claim");
351
- await this.assertKernelReadRun(ctx, c);
358
+ await this.assertKernelReadRun(ctx, read);
352
359
  const described = describeOperationPayload(input);
353
360
  const payload = payloadReference("input", described);
354
361
  const vector = await this.epochs.readLocked({
@@ -407,7 +414,7 @@ let SandboxOperationIntents = class SandboxOperationIntents {
407
414
  const initial = await this.read(id);
408
415
  await this.locks.acquire(subjectOf(initial), { kind: "admit" });
409
416
  const c = read.claim;
410
- await this.assertKernelReadRun(ctx, c);
417
+ await this.assertKernelReadRun(ctx, read);
411
418
  const row = await this.db
412
419
  .selectFrom("sandbox_operation_intents")
413
420
  .selectAll()
@@ -1040,16 +1047,29 @@ let SandboxOperationIntents = class SandboxOperationIntents {
1040
1047
  runAt,
1041
1048
  });
1042
1049
  }
1043
- async complete(id, executionId, result) {
1050
+ async complete(id, executionId, result,
1051
+ /**
1052
+ * A kernel read's purpose: required for a row with a run and no tool call (a kernel read),
1053
+ * whose run state it decides; never defaulted, so a caller that forgets it fails loudly.
1054
+ */
1055
+ kernelRead) {
1044
1056
  const initial = await this.read(id);
1045
1057
  if (initial.run_id !== null) {
1046
- // a kernel read (no tool call) serves a run start, which reads while its run is queued
1058
+ // a kernel read (no tool call) serves a run start, which reads while its run is queued, or a
1059
+ // write base, which reads while its run is running
1060
+ let status = "running";
1061
+ if (initial.call_id === null) {
1062
+ if (kernelRead === "project_root")
1063
+ status = "queued";
1064
+ else if (kernelRead !== "write_base")
1065
+ throw new Error("A kernel read's completion must name its purpose");
1066
+ }
1047
1067
  const run = await this.db
1048
1068
  .selectFrom("runs")
1049
1069
  .select("id")
1050
1070
  .where("id", "=", initial.run_id)
1051
1071
  .where("execution_id", "=", executionId)
1052
- .where("status", "=", initial.call_id === null ? "queued" : "running")
1072
+ .where("status", "=", status)
1053
1073
  .forShare()
1054
1074
  .executeTakeFirst();
1055
1075
  if (!run)
@@ -588,15 +588,38 @@ export declare class SandboxService {
588
588
  */
589
589
  applyLimitsIfRunning(use: SandboxUseContext, signal: AbortSignal): Promise<"applied" | "unchanged" | "not_running">;
590
590
  /**
591
- * A run start's kernel read of the bound project (permission activation L2, Hook 1): the use
592
- * a tool call's would be (the instance made or resumed, the read silent for the holder), whose
593
- * provider stats, reads and lists only, each call a kernel read admitted and claimed on its own
594
- * (`SandboxOperationIntents.admitKernelRead`: the run's current claim with its run still
595
- * `queued`, a random operation id, the profile scope narrowed to the root, its `AGENTS.md` and
596
- * its `.agents/skills`). Any other method is refused before admission. Only
597
- * `ProjectKnowledgeService` calls this: no tool context, Platform operation or route has it.
591
+ * A kernel read of the device on behalf of a run (permission activation L2), whose provider
592
+ * stats, reads and lists only, each call a kernel read admitted and claimed on its own
593
+ * (`SandboxOperationIntents.admitKernelRead`: the run's current claim with its run in the state
594
+ * the purpose needs, a random operation id, the profile scope narrowed to the one covering
595
+ * path). Any other method is refused before admission. No path lease is taken. By purpose:
596
+ * - `project_root` (Hook 1, the run `queued`): the use a tool call's would be (the instance made
597
+ * or resumed, the read silent for the holder), narrowed to the root, its `AGENTS.md` and its
598
+ * `.agents/skills`.
599
+ * - `write_base` (streaming tool input spec §4.1, the run `running`): only on the device's
600
+ * running instance, as an owner browse is ({@link ifRunning}): it never makes, wakes, resumes
601
+ * or rebuilds one (else {@link KernelReadInstanceNotRunning}) and touches no seen record;
602
+ * `stat` and `readFile` of exactly its path.
603
+ * Only the kernel's own run code calls this: no tool context, Platform operation or route has it.
598
604
  */
599
605
  withKernelRead<T>(ctx: SandboxUseContext, read: KernelReadInvocation, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
606
+ /**
607
+ * A `write_base` kernel read ({@link withKernelRead}) on the instance the device runs now, under
608
+ * a shared lease taken the way {@link ifRunning} takes it (B1 reconcile marker and retirement
609
+ * gate included): a device with no running instance, or one that changes instance before the
610
+ * lease, throws {@link KernelReadInstanceNotRunning} with nothing made, woken or sent.
611
+ *
612
+ * Unlike a use's `enter`, this path neither applies changed limits (`mustApply`, which needs the
613
+ * exclusive lease and may rebuild the instance) nor refreshes stale cloud evidence
614
+ * (`refreshCloudSupport`, B-15), since either would be lifecycle work a display-only read must
615
+ * not cause. That is acceptable here: the read only stats and reads one file, its scope carries
616
+ * no write roots (an instance boundary's own scope aside) and network `none`, and the boundary
617
+ * is the kernel-side covering-path check at admission and claim, not the instance's applied
618
+ * limits. Stale evidence still picks among the routes `kernelReadRoute` allows (Full access
619
+ * only on an instance boundary), so the read stays one path, read-only, with no network; a
620
+ * provider that no longer accepts the scope refuses it, and the person just gets no base.
621
+ */
622
+ private withRunningKernelRead;
600
623
  withOperations<T>(ctx: SandboxUseContext, invocation: OperationSessionInvocation, fn: (h: SandboxHandle, p: HeldProvider, info: SandboxUseInfo, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
601
624
  /**
602
625
  * Every use of the device's instance ({@link withOperations}, {@link withPreparation},