@capybara-hq/kernel 0.1.0-rc.31 → 0.1.0-rc.33

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 (104) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/inbound.d.ts +0 -25
  3. package/dist/channels/inbound.js +26 -1
  4. package/dist/channels/phrases.d.ts +28 -0
  5. package/dist/channels/phrases.js +28 -0
  6. package/dist/conversations/conversations.controller.d.ts +4 -1
  7. package/dist/conversations/conversations.controller.js +14 -2
  8. package/dist/conversations/conversations.service.d.ts +43 -3
  9. package/dist/conversations/conversations.service.js +93 -19
  10. package/dist/conversations/event-log.d.ts +3 -3
  11. package/dist/conversations/event-log.js +3 -3
  12. package/dist/conversations/events.d.ts +24 -0
  13. package/dist/conversations/events.js +69 -0
  14. package/dist/ctx/create-ctx.d.ts +26 -4
  15. package/dist/ctx/create-ctx.js +54 -34
  16. package/dist/db/kernel-schema.d.ts +20 -0
  17. package/dist/devices/conversation-devices.d.ts +57 -3
  18. package/dist/devices/conversation-devices.js +63 -11
  19. package/dist/devices/device-projects.service.d.ts +162 -0
  20. package/dist/devices/device-projects.service.js +503 -0
  21. package/dist/devices/devices.controller.d.ts +15 -2
  22. package/dist/devices/devices.controller.js +60 -3
  23. package/dist/devices/devices.module.js +15 -2
  24. package/dist/devices/devices.schemas.js +9 -1
  25. package/dist/devices/dto.d.ts +31 -0
  26. package/dist/devices/dto.js +38 -1
  27. package/dist/devices/working-root.d.ts +41 -0
  28. package/dist/devices/working-root.js +50 -0
  29. package/dist/errors.d.ts +39 -0
  30. package/dist/errors.js +39 -0
  31. package/dist/evals/run-replay.d.ts +9 -1
  32. package/dist/evals/run-replay.js +15 -1
  33. package/dist/extensions/permission-set.d.ts +7 -6
  34. package/dist/extensions/permission-set.js +9 -6
  35. package/dist/extensions/permission-view.d.ts +4 -4
  36. package/dist/extensions/permission-view.js +10 -5
  37. package/dist/http/app.d.ts +8 -2
  38. package/dist/http/app.js +12 -2
  39. package/dist/http/plugin-dispatch.d.ts +55 -18
  40. package/dist/http/plugin-dispatch.js +124 -29
  41. package/dist/http/plugin-route-access.d.ts +56 -0
  42. package/dist/http/plugin-route-access.js +192 -0
  43. package/dist/identity/auth.guard.d.ts +26 -12
  44. package/dist/identity/auth.guard.js +62 -33
  45. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  46. package/dist/infra/throttler/named-throttlers.js +16 -0
  47. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  48. package/dist/infra/throttler/throttler.guard.js +2 -1
  49. package/dist/kernel.module.js +3 -0
  50. package/dist/local-devices/local-device-provider.d.ts +37 -1
  51. package/dist/local-devices/local-device-provider.js +33 -0
  52. package/dist/local-devices/machines.d.ts +2 -1
  53. package/dist/local-devices/machines.js +4 -1
  54. package/dist/local-devices/policy-summary.js +1 -0
  55. package/dist/local-devices/relay.d.ts +2 -0
  56. package/dist/local-devices/relay.js +3 -1
  57. package/dist/local-devices/targets.d.ts +6 -1
  58. package/dist/local-devices/targets.js +14 -0
  59. package/dist/overrides.d.ts +7 -0
  60. package/dist/overrides.js +4 -0
  61. package/dist/platform/ops/agent-skills.ops.js +2 -1
  62. package/dist/platform/ops/devices.ops.d.ts +3 -1
  63. package/dist/platform/ops/devices.ops.js +136 -3
  64. package/dist/runtime/context/build.d.ts +3 -0
  65. package/dist/runtime/context/build.js +14 -0
  66. package/dist/runtime/context/compaction.js +2 -0
  67. package/dist/runtime/context/project-root.d.ts +43 -0
  68. package/dist/runtime/context/project-root.js +85 -0
  69. package/dist/runtime/model-call.js +25 -1
  70. package/dist/runtime/project/knowledge.d.ts +129 -0
  71. package/dist/runtime/project/knowledge.js +248 -0
  72. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  73. package/dist/runtime/project/knowledge.service.js +288 -0
  74. package/dist/runtime/run-worker.d.ts +5 -0
  75. package/dist/runtime/run-worker.js +27 -6
  76. package/dist/runtime/runtime.module.js +7 -0
  77. package/dist/sandbox/review/review.service.d.ts +14 -2
  78. package/dist/sandbox/review/review.service.js +2 -0
  79. package/dist/sandbox/review/rules.d.ts +6 -4
  80. package/dist/sandbox/review/rules.js +185 -62
  81. package/dist/sandbox/review/types.d.ts +14 -0
  82. package/dist/sandbox/sandbox.service.d.ts +16 -1
  83. package/dist/sandbox/sandbox.service.js +75 -3
  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/pipeline.d.ts +1 -1
  101. package/dist/tools/pipeline.js +53 -8
  102. package/dist/tools/registry.d.ts +6 -0
  103. package/package.json +3 -3
  104. package/src/migrations/0133_project_root.sql +30 -0
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { KernelDb } from "../infra/database/kernel-db.js";
12
+ import { deviceFeaturesOf } from "./policy-summary.js";
12
13
  const ROOT_KEYS = ["workspace", "skills", "tmp"];
13
14
  /** Whether two sets of roots name the same three directories. */
14
15
  export const sameRoots = (a, b) => ROOT_KEYS.every((k) => a[k] === b[k]);
@@ -65,6 +66,19 @@ let DeviceTargets = class DeviceTargets {
65
66
  return null;
66
67
  return r;
67
68
  }
69
+ /**
70
+ * The features the device's active machine announced in its last hello (known ones only);
71
+ * empty without an active machine.
72
+ */
73
+ async machineFeatures(deviceId) {
74
+ const row = await this.db
75
+ .selectFrom("device_machines")
76
+ .select("features")
77
+ .where("device_id", "=", deviceId)
78
+ .where("revoked_at", "is", null)
79
+ .executeTakeFirst();
80
+ return deviceFeaturesOf(row?.features);
81
+ }
68
82
  };
69
83
  DeviceTargets = __decorate([
70
84
  Injectable(),
@@ -10,12 +10,14 @@ import { USAGE_SUBSCRIBERS_CLOCK } from "./extensions/usage-subscribers.js";
10
10
  import { FILE_PREVIEW_TIMEOUT } from "./files/previewers.js";
11
11
  import { GIT_UPSTREAM_ORIGIN, type GitUpstreamOrigin } from "./git/gateway.js";
12
12
  import { GIT_IDENTITY_API_BASE, type GitIdentityApiBase } from "./git/identity.js";
13
+ import { PLUGIN_PUBLIC_WRITE_LIMIT } from "./http/plugin-route-access.js";
13
14
  import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
14
15
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
15
16
  import { OUTBOX_STRICT_CONFLICTS } from "./infra/outbox/outbox.service.js";
16
17
  import { PRESENCE_INTERVAL_MS } from "./infra/presence/replica-presence.js";
17
18
  import type { KernelQueueName } from "./infra/queue/queue-names.js";
18
19
  import { DEVICE_POLICY_AFTER_CALL } from "./local-devices/device-policy.service.js";
20
+ import { PROJECT_KNOWLEDGE_TIMEOUT } from "./runtime/project/knowledge.service.js";
19
21
  import { LIST_MODELS_TIMEOUT } from "./runtime/providers.js";
20
22
  import { RUN_CONTEXT_CLOCK } from "./runtime/run-context.service.js";
21
23
  import { ENSURE_RUN_FAILS } from "./runtime/run-queue.js";
@@ -54,6 +56,9 @@ import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
54
56
  * direct call after a commit skipped by a crash);
55
57
  * - `DEVICE_POLICY_AFTER_CALL`: called after a device policy op's call, before its outcome is
56
58
  * recorded (throwing stands for a crash between the call and the resolve transaction);
59
+ * - `PROJECT_KNOWLEDGE_TIMEOUT`: the run-start read of a bound project's time limit, read at every
60
+ * read (a test shortens it for one run);
61
+ * - `PLUGIN_PUBLIC_WRITE_LIMIT`: a lower limit for unsafe methods on `public` extension routes;
57
62
  * - `SCOPE_BACKSTOP_DELAY`: the delay of a confirmation's scope sync backstop (ruling R24);
58
63
  * - `APP_INTERCEPTOR`: one more global interceptor (a probe of the matched routes).
59
64
  */
@@ -81,6 +86,8 @@ interface KernelSeams {
81
86
  [OUTBOX_FAST_PATH_SETTLED]: (pass: Promise<void>) => void;
82
87
  [ENSURE_RUN_FAILS]: () => boolean;
83
88
  [SCOPE_BACKSTOP_DELAY]: number;
89
+ [PROJECT_KNOWLEDGE_TIMEOUT]: () => number;
90
+ [PLUGIN_PUBLIC_WRITE_LIMIT]: number;
84
91
  [DEVICE_POLICY_AFTER_CALL]: (opId: string) => void;
85
92
  [APP_INTERCEPTOR]: NestInterceptor;
86
93
  }
package/dist/overrides.js CHANGED
@@ -8,11 +8,13 @@ import { USAGE_SUBSCRIBERS_CLOCK } from "./extensions/usage-subscribers.js";
8
8
  import { FILE_PREVIEW_TIMEOUT } from "./files/previewers.js";
9
9
  import { GIT_UPSTREAM_ORIGIN } from "./git/gateway.js";
10
10
  import { GIT_IDENTITY_API_BASE } from "./git/identity.js";
11
+ import { PLUGIN_PUBLIC_WRITE_LIMIT } from "./http/plugin-route-access.js";
11
12
  import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
12
13
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
13
14
  import { OUTBOX_STRICT_CONFLICTS } from "./infra/outbox/outbox.service.js";
14
15
  import { PRESENCE_INTERVAL_MS } from "./infra/presence/replica-presence.js";
15
16
  import { DEVICE_POLICY_AFTER_CALL } from "./local-devices/device-policy.service.js";
17
+ import { PROJECT_KNOWLEDGE_TIMEOUT } from "./runtime/project/knowledge.service.js";
16
18
  import { LIST_MODELS_TIMEOUT } from "./runtime/providers.js";
17
19
  import { RUN_CONTEXT_CLOCK } from "./runtime/run-context.service.js";
18
20
  import { ENSURE_RUN_FAILS } from "./runtime/run-queue.js";
@@ -47,6 +49,8 @@ const SEAM_TOKENS = [
47
49
  OUTBOX_FAST_PATH_SETTLED,
48
50
  ENSURE_RUN_FAILS,
49
51
  SCOPE_BACKSTOP_DELAY,
52
+ PROJECT_KNOWLEDGE_TIMEOUT,
53
+ PLUGIN_PUBLIC_WRITE_LIMIT,
50
54
  DEVICE_POLICY_AFTER_CALL,
51
55
  APP_INTERCEPTOR,
52
56
  ];
@@ -185,7 +185,7 @@ let AgentSkillsOperations = class AgentSkillsOperations {
185
185
  }),
186
186
  defineOperation({
187
187
  id: "agents.invocable-skills",
188
- description: "List the skills a person can invoke with / on an agent (its effective skills: org, platform and its own), by name: id, name, state (manual for manual-only), description, version and the plugin. Optionally pass a conversation of yours with that agent to include its trial drafts.",
188
+ description: "List the skills a person can invoke with / on an agent (its effective skills: org, platform and its own), by name: id, name, source (platform, plugin, agent or project), state (manual for manual-only), description, version and the plugin. Optionally pass a conversation of yours with that agent to include its trial drafts and, for a conversation bound to a project, the project's skills as project:<name>.",
189
189
  input: z
190
190
  .object({
191
191
  agentId: AgentId,
@@ -210,6 +210,7 @@ let AgentSkillsOperations = class AgentSkillsOperations {
210
210
  items: (await this.invoker.listFor(ctx.orgId, input.agentId, ctx.actorAccountId, input.conversationId)).map((s) => ({
211
211
  id: s.id,
212
212
  name: s.name,
213
+ source: s.source,
213
214
  state: s.manual ? "manual" : "active",
214
215
  description: clip(s.description),
215
216
  version: s.version,
@@ -1,4 +1,5 @@
1
1
  import { type OnModuleInit } from "@nestjs/common";
2
+ import { DeviceProjectsService } from "../../devices/device-projects.service.js";
2
3
  import { DevicesService } from "../../devices/devices.service.js";
3
4
  import { KernelDb } from "../../infra/database/kernel-db.js";
4
5
  import { PlatformOperations } from "../registry.js";
@@ -11,8 +12,9 @@ import { PlatformOperations } from "../registry.js";
11
12
  export declare class DevicesOperations implements OnModuleInit {
12
13
  private readonly registry;
13
14
  private readonly devices;
15
+ private readonly projects;
14
16
  private readonly kdb;
15
- constructor(registry: PlatformOperations, devices: DevicesService, kdb: KernelDb);
17
+ constructor(registry: PlatformOperations, devices: DevicesService, projects: DeviceProjectsService, kdb: KernelDb);
16
18
  /**
17
19
  * Whether `id` is the device the run works in: the one its root conversation is bound to
18
20
  * (sub-agents use the root's). Deleting or wiping it would pull the sandbox from under the run.
@@ -9,8 +9,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { z } from "zod";
12
+ import { DeviceProjectsService } from "../../devices/device-projects.service.js";
12
13
  import { DevicesService } from "../../devices/devices.service.js";
13
- import { DeviceNameBody, DeviceParams } from "../../devices/dto.js";
14
+ import { DeviceNameBody, DeviceParams, DeviceProjectAddBody, DeviceProjectParams, } from "../../devices/dto.js";
14
15
  import { deviceLabel } from "../../devices/label.js";
15
16
  import { KernelDb } from "../../infra/database/kernel-db.js";
16
17
  import { rootConversationOf } from "../../runtime/subagents/child.js";
@@ -74,10 +75,12 @@ const row = (e) => ({
74
75
  let DevicesOperations = class DevicesOperations {
75
76
  registry;
76
77
  devices;
78
+ projects;
77
79
  kdb;
78
- constructor(registry, devices, kdb) {
80
+ constructor(registry, devices, projects, kdb) {
79
81
  this.registry = registry;
80
82
  this.devices = devices;
83
+ this.projects = projects;
81
84
  this.kdb = kdb;
82
85
  }
83
86
  /**
@@ -301,6 +304,135 @@ let DevicesOperations = class DevicesOperations {
301
304
  device: row(await this.devices.rename(ctx.orgId, ctx.actorAccountId, input.deviceId, input.name, undefined, viaAgent("devices.rename", ctx))),
302
305
  }),
303
306
  }),
307
+ defineOperation({
308
+ id: "devices.list-projects",
309
+ description: "List the projects of one of your devices that its current mode can read (name and absolute path), plus the mode, the base a new project's path is relative to (the workspace in sandbox mode and on a cloud device, your home directory in auto mode), how many stored projects the mode hides, and whether the device offers projects at all. Takes the id from devices.list.",
310
+ input: DeviceId,
311
+ example: { deviceId: "4e8a0c1d-6b2f-4a37-8d19-3c5e7f9a1b20" },
312
+ authz: { orgAction: "agents.use" },
313
+ mirrors: ["GET /api/v1/orgs/:orgId/devices/:id/projects"],
314
+ renames: { deviceId: "id" },
315
+ confirm: "read",
316
+ errors: [
317
+ {
318
+ code: "device.not_found",
319
+ next: "Check the id with devices.list: you only see your own devices.",
320
+ },
321
+ ],
322
+ run: (input, ctx) => this.projects.list(ctx.orgId, ctx.actorAccountId, input.deviceId),
323
+ }),
324
+ defineOperation({
325
+ id: "devices.project-candidates",
326
+ description: "Ask one of your devices for project suggestions: the directories under its base (and the base itself) that hold .git or AGENTS.md, at most two levels down, each with its path relative to the base and a suggested name. Directory names only, never file contents. Takes the id from devices.list; add one with devices.add-project.",
327
+ input: DeviceId,
328
+ example: { deviceId: "4e8a0c1d-6b2f-4a37-8d19-3c5e7f9a1b20" },
329
+ authz: { orgAction: "agents.use" },
330
+ mirrors: ["GET /api/v1/orgs/:orgId/devices/:id/projects/candidates"],
331
+ renames: { deviceId: "id" },
332
+ confirm: "read",
333
+ errors: [
334
+ {
335
+ code: "device.not_found",
336
+ next: "Check the id with devices.list: you only see your own devices.",
337
+ },
338
+ {
339
+ code: "device.offline",
340
+ next: "Its machine is offline: ask the person to start capybara-device on it, then call again.",
341
+ },
342
+ {
343
+ code: "device.project_home_unknown",
344
+ next: "Ask the person to update capybara-device on that machine and reconnect it.",
345
+ },
346
+ ],
347
+ run: (input, ctx) => this.projects.candidates(ctx.orgId, ctx.actorAccountId, input.deviceId),
348
+ }),
349
+ defineOperation({
350
+ id: "devices.add-project",
351
+ description: "Add a project to one of your devices: path is relative to the device's base (see devices.list-projects; empty for the base itself), never absolute, and must stay inside what the device reads in its current mode; name defaults to the directory's name (1-64 characters, no /, unique on the device). The device is asked first, so a missing directory, a file or an unreadable path is refused. At most 100 projects per device. Takes the id from devices.list.",
352
+ input: DeviceId.extend(DeviceProjectAddBody.shape).strict(),
353
+ example: { deviceId: "4e8a0c1d-6b2f-4a37-8d19-3c5e7f9a1b20", path: "src/capybara" },
354
+ authz: { orgAction: "agents.use" },
355
+ mirrors: ["POST /api/v1/orgs/:orgId/devices/:id/projects"],
356
+ renames: { deviceId: "id" },
357
+ confirm: "personal",
358
+ errors: [
359
+ {
360
+ code: "device.not_found",
361
+ next: "Check the id with devices.list: you only see your own devices.",
362
+ },
363
+ {
364
+ code: "device.project_name_taken",
365
+ next: "The device has a project with this name: pass another name, or read them with devices.list-projects.",
366
+ },
367
+ {
368
+ code: "device.project_limit_reached",
369
+ next: "The device is at the limit: remove a project with devices.remove-project first.",
370
+ },
371
+ {
372
+ code: "device.project_outside_mode",
373
+ next: "Pick a directory inside the device's workspace, or ask the person to switch the device to auto mode on its machine.",
374
+ },
375
+ {
376
+ code: "device.project_path_missing",
377
+ next: "Check the path with devices.project-candidates or ask the person for it.",
378
+ },
379
+ {
380
+ code: "device.project_path_too_broad",
381
+ next: "Pass the project's own directory: the owner's home or a directory below it, never / or an ancestor of the home.",
382
+ },
383
+ {
384
+ code: "device.project_path_unreadable",
385
+ next: "Pass a directory the device can read (not a file).",
386
+ },
387
+ {
388
+ code: "device.projects_unsupported",
389
+ next: "This device offers no projects: work without one, or ask the person to update capybara-device.",
390
+ },
391
+ {
392
+ code: "device.offline",
393
+ next: "Its machine is offline: ask the person to start capybara-device on it, then call again.",
394
+ },
395
+ ],
396
+ precheck: (i, ctx) => precheckBy(() => this.projects.checkAdd(ctx.orgId, ctx.actorAccountId, i.deviceId, i.name)),
397
+ summary: async (i, ctx) => {
398
+ const n = await this.label(ctx, i.deviceId);
399
+ const where = i.path === "" ? "." : i.path;
400
+ return {
401
+ zh: `在设备「${n}」上添加项目 ${named(where)}${i.name === undefined ? "" : `(名称「${named(i.name)}」)`}`,
402
+ en: `Add project ${named(where)} to device "${n}"${i.name === undefined ? "" : ` (named "${named(i.name)}")`}`,
403
+ };
404
+ },
405
+ run: async (input, ctx) => ({
406
+ project: await this.projects.add(ctx.orgId, ctx.actorAccountId, input.deviceId, { path: input.path, ...(input.name !== undefined && { name: input.name }) }, undefined, viaAgent("devices.add-project", ctx)),
407
+ }),
408
+ }),
409
+ defineOperation({
410
+ id: "devices.remove-project",
411
+ description: "Remove a project from one of your devices by name: only the entry goes, never the directory or its files; conversations already bound to it keep their path. Removing a project that is not there succeeds. Takes the id from devices.list and the name from devices.list-projects.",
412
+ input: DeviceId.extend({ name: DeviceProjectParams.shape.name }).strict(),
413
+ example: { deviceId: "4e8a0c1d-6b2f-4a37-8d19-3c5e7f9a1b20", name: "capybara" },
414
+ authz: { orgAction: "agents.use" },
415
+ mirrors: ["DELETE /api/v1/orgs/:orgId/devices/:id/projects/:name"],
416
+ renames: { deviceId: "id" },
417
+ confirm: "personal",
418
+ errors: [
419
+ {
420
+ code: "device.not_found",
421
+ next: "Check the id with devices.list: you only see your own devices.",
422
+ },
423
+ ],
424
+ summary: async (i, ctx) => {
425
+ const n = await this.label(ctx, i.deviceId);
426
+ return {
427
+ zh: `从设备「${n}」移除项目「${named(i.name)}」(目录和文件保留)`,
428
+ en: `Remove project "${named(i.name)}" from device "${n}" (the directory and files stay)`,
429
+ };
430
+ },
431
+ run: async (input, ctx) => {
432
+ await this.projects.remove(ctx.orgId, ctx.actorAccountId, input.deviceId, input.name, undefined, viaAgent("devices.remove-project", ctx));
433
+ return { deviceId: input.deviceId, name: input.name, removed: true };
434
+ },
435
+ }),
304
436
  ]);
305
437
  }
306
438
  };
@@ -308,6 +440,7 @@ DevicesOperations = __decorate([
308
440
  Injectable(),
309
441
  __param(0, Inject(PlatformOperations)),
310
442
  __param(1, Inject(DevicesService)),
311
- __param(2, Inject(KernelDb))
443
+ __param(2, Inject(DeviceProjectsService)),
444
+ __param(3, Inject(KernelDb))
312
445
  ], DevicesOperations);
313
446
  export { DevicesOperations };
@@ -249,6 +249,9 @@ export declare function summaryText(summary: string): string;
249
249
  * `plugin_context` (`role: "system"` at its position, `pluginContextText`, nothing for empty
250
250
  * text; covered by the summary: the latest non-empty one per plugin, in plugin-name order,
251
251
  * follows the summary after `device_paths`) /
252
+ * `project_root` (`role: "system"` at its position, `projectRootText`, so after the agent's own
253
+ * instructions; covered by the summary: the latest one follows the summary after the plugin
254
+ * context) /
252
255
  * `background_task_finished`(`role: "system"`, the text of
253
256
  * {@link renderBackgroundFinished}, placed like a user_message)/ `subagent_delivery` (likewise,
254
257
  * the text of {@link renderSubagentDelivery});`tool_result` 事件还原为紧随其 assistant 消息之后的一条 user 消息
@@ -7,6 +7,7 @@ import { renderSubagentDelivery } from "../subagents/render.js";
7
7
  import { devicePathsAt, devicePathsText } from "./device-paths.js";
8
8
  import { LEGACY_CATALOG_HEADER, LEGACY_SKILL_TEXTS, usesLegacyToolNames } from "./legacy-text.js";
9
9
  import { pluginContextsAfterSummary, pluginContextText } from "./plugin-context.js";
10
+ import { latestProjectRoot, projectRootText } from "./project-root.js";
10
11
  import { currentRunContext, runContextEvents, runContextFullText, runContextText, scheduleHeader, senderLines, } from "./run-context.js";
11
12
  import { invokedSkillNames, invokedSkillsText, SKILL_TEXTS, skillsCatalogEvents, snapshotChangeText, snapshotCurrentText, snapshotSystemText, systemSkillsCatalog, } from "./skills.js";
12
13
  import { toolsChangedText } from "./tool-changes.js";
@@ -362,6 +363,9 @@ export function summaryText(summary) {
362
363
  * `plugin_context` (`role: "system"` at its position, `pluginContextText`, nothing for empty
363
364
  * text; covered by the summary: the latest non-empty one per plugin, in plugin-name order,
364
365
  * follows the summary after `device_paths`) /
366
+ * `project_root` (`role: "system"` at its position, `projectRootText`, so after the agent's own
367
+ * instructions; covered by the summary: the latest one follows the summary after the plugin
368
+ * context) /
365
369
  * `background_task_finished`(`role: "system"`, the text of
366
370
  * {@link renderBackgroundFinished}, placed like a user_message)/ `subagent_delivery` (likewise,
367
371
  * the text of {@link renderSubagentDelivery});`tool_result` 事件还原为紧随其 assistant 消息之后的一条 user 消息
@@ -603,6 +607,11 @@ export function buildModelRequest(input) {
603
607
  for (const text of pluginContextsAfterSummary(events, after)) {
604
608
  messages.push({ role: "system", content: text });
605
609
  }
610
+ // project root spec §4.5: the project in effect at the boundary follows the summary again, so
611
+ // its instructions and skills (or the line that it is unavailable) outlive the summary
612
+ const project = latestProjectRoot(events, after);
613
+ if (project)
614
+ messages.push({ role: "system", content: projectRootText(project) });
606
615
  // 被摘要覆盖的变更提醒不再发送:摘要时生效的目录与 system 里的不同 → 紧随摘要补上完整的当前目录
607
616
  const covered = skillSnaps.filter((e) => e.seq <= after).at(-1);
608
617
  // (phase B: plus the current pinned skills and tool-name map when they differ from system's)
@@ -688,6 +697,11 @@ export function buildModelRequest(input) {
688
697
  messages.push({ role: "system", content: text });
689
698
  break;
690
699
  }
700
+ // the bound project as a run start read it (project root spec §4.5): recorded before the
701
+ // run's first model call, so it follows the agent's instructions and stays append-only
702
+ case "project_root":
703
+ messages.push({ role: "system", content: projectRootText(e.payload) });
704
+ break;
691
705
  // hook_denied is not model-visible: the model sees only the denied tool call's tool_result
692
706
  // (and nothing for a denied model request), so request building skips it
693
707
  case "hook_denied":
@@ -323,6 +323,8 @@ function transcriptLine(e) {
323
323
  case "skill_fork_result":
324
324
  return `User: ${e.payload.text}`;
325
325
  // device_paths is left out too: the latest one follows the summary (build.ts)
326
+ // project_root likewise (project root spec §4.5): the latest one follows the summary whole,
327
+ // so the summary never carries the project's instructions in a paraphrase
326
328
  // run_context is left out: its current values follow the summary anyway (build.ts), and
327
329
  // stale names should not be summarised as current
328
330
  case "tool_result":
@@ -0,0 +1,43 @@
1
+ import type { ConversationEvent, EventPayload } from "../../conversations/events.js";
2
+ /**
3
+ * The `project_root` event in a request (project root spec §4.5): a bound conversation's project
4
+ * as its run start read it. Rendered at its position as a system message, so it follows the
5
+ * agent's own instructions (in `system`) and the request stays append-only; after a summary that
6
+ * covers it, the latest one follows the summary again. A pure function of the payload: the request
7
+ * is rebuilt from the log and never from the device, so it needs no `DriftReason`.
8
+ * Model-visible text is English.
9
+ */
10
+ /** The payload of a `project_root` event. */
11
+ export type ProjectRootPayload = EventPayload<"project_root">;
12
+ /** The prefix of a project skill's callable name (spec §4.5: never collides with a catalog skill). */
13
+ export declare const PROJECT_SKILL_PREFIX = "project:";
14
+ /**
15
+ * The longest name `Skill` takes (its input schema's `maxLength`). A project skill whose callable
16
+ * name is longer is left out of the rendered list: the schema stays as it is, since changing it
17
+ * would change every recorded tool definition.
18
+ */
19
+ export declare const SKILL_NAME_MAX_CHARS = 64;
20
+ /** A project skill's callable name, `project:<name>`. */
21
+ export declare const projectSkillName: (name: string) => string;
22
+ /** The bare name of `project:<name>`, or undefined for any other name. */
23
+ export declare const projectSkillOf: (asked: string) => string | undefined;
24
+ /** The project's skills `Skill` can be called with (callable name within the schema's cap). */
25
+ export declare function callableProjectSkills(p: ProjectRootPayload): ProjectRootPayload["skills"];
26
+ /** The names of the project's skills left out because their callable name is too long. */
27
+ export declare function overlongProjectSkills(p: ProjectRootPayload): string[];
28
+ /**
29
+ * The system message of a `project_root` event. Usable: a header naming the project and its root,
30
+ * the `AGENTS.md` text (a note when it was cut), the line that the agent's own instructions win on
31
+ * a direct conflict, and the skills as catalog lines named `project:<name>` (a note when the list
32
+ * was cut). Unavailable: one line with the reason, saying earlier project instructions and skills
33
+ * no longer apply.
34
+ */
35
+ export declare function projectRootText(p: ProjectRootPayload): string;
36
+ /** The latest `project_root` payload at or before `uptoSeq` (any order of `events`). */
37
+ export declare function latestProjectRoot(events: readonly ConversationEvent[], uptoSeq: number): ProjectRootPayload | undefined;
38
+ /**
39
+ * Whether the log ever recorded a project with a skill `Skill` can be called with (the ones the
40
+ * rendering lists, {@link callableProjectSkills}): then `Skill` is offered (like a skills catalog
41
+ * snapshot, never taken back, so the tool set and the cache prefix stay stable).
42
+ */
43
+ export declare const hasProjectSkills: (events: readonly ConversationEvent[]) => boolean;
@@ -0,0 +1,85 @@
1
+ import { SKILL_LOAD } from "../../tools/builtin-names.js";
2
+ import { catalogLine } from "./skills.js";
3
+ /** The prefix of a project skill's callable name (spec §4.5: never collides with a catalog skill). */
4
+ export const PROJECT_SKILL_PREFIX = "project:";
5
+ /**
6
+ * The longest name `Skill` takes (its input schema's `maxLength`). A project skill whose callable
7
+ * name is longer is left out of the rendered list: the schema stays as it is, since changing it
8
+ * would change every recorded tool definition.
9
+ */
10
+ export const SKILL_NAME_MAX_CHARS = 64;
11
+ /** A project skill's callable name, `project:<name>`. */
12
+ export const projectSkillName = (name) => `${PROJECT_SKILL_PREFIX}${name}`;
13
+ /** The bare name of `project:<name>`, or undefined for any other name. */
14
+ export const projectSkillOf = (asked) => asked.startsWith(PROJECT_SKILL_PREFIX) ? asked.slice(PROJECT_SKILL_PREFIX.length) : undefined;
15
+ /** The project's skills `Skill` can be called with (callable name within the schema's cap). */
16
+ export function callableProjectSkills(p) {
17
+ return p.skills.filter((s) => projectSkillName(s.name).length <= SKILL_NAME_MAX_CHARS);
18
+ }
19
+ /** The names of the project's skills left out because their callable name is too long. */
20
+ export function overlongProjectSkills(p) {
21
+ return p.skills
22
+ .filter((s) => projectSkillName(s.name).length > SKILL_NAME_MAX_CHARS)
23
+ .map((s) => s.name);
24
+ }
25
+ /**
26
+ * `AGENTS.md` as it goes inside `<agents-md>…</agents-md>`: every closing tag of the block in the
27
+ * repository's text (any case, any spaces: `</agents-md`, `< / AGENTS-MD`) has its `<` written as
28
+ * `&lt;`, so the text cannot end the block and forge what follows. Deterministic: the same payload
29
+ * renders the same bytes.
30
+ */
31
+ function inertAgentsMd(text) {
32
+ return text.replace(/<(?=\s*\/\s*agents-md)/gi, "&lt;");
33
+ }
34
+ /**
35
+ * The system message of a `project_root` event. Usable: a header naming the project and its root,
36
+ * the `AGENTS.md` text (a note when it was cut), the line that the agent's own instructions win on
37
+ * a direct conflict, and the skills as catalog lines named `project:<name>` (a note when the list
38
+ * was cut). Unavailable: one line with the reason, saying earlier project instructions and skills
39
+ * no longer apply.
40
+ */
41
+ export function projectRootText(p) {
42
+ if (p.unavailable !== undefined) {
43
+ return (`The project "${p.project}" (${p.root}) is not available this run (${p.unavailable.reason}): ` +
44
+ `${p.unavailable.message} Its earlier project instructions and skills no longer apply; work without them.`);
45
+ }
46
+ const parts = [
47
+ `This conversation works in the project "${p.project}", rooted at ${p.root} on the device. ` +
48
+ "This replaces any earlier project instructions and skills.",
49
+ ];
50
+ if (p.agentsMd !== undefined) {
51
+ parts.push(`The project's AGENTS.md (the repository's instructions for working in it):\n<agents-md>\n${inertAgentsMd(p.agentsMd)}\n</agents-md>`);
52
+ if (p.agentsMdTruncated === true) {
53
+ parts.push(`AGENTS.md was cut at 64 KiB; read ${p.root}/AGENTS.md for the rest.`);
54
+ }
55
+ }
56
+ parts.push("Follow the project's instructions while you work in it, but where they directly conflict " +
57
+ "with your own instructions, your own instructions win.");
58
+ const skills = [...callableProjectSkills(p)].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
59
+ const first = skills[0];
60
+ if (first !== undefined) {
61
+ const lines = skills.map((s) => catalogLine({ name: projectSkillName(s.name), description: s.description }));
62
+ parts.push(`Project skills (call ${SKILL_LOAD} with the name, e.g. ${projectSkillName(first.name)}, to read one before a matching task):\n${lines.join("\n")}`);
63
+ }
64
+ if (p.skillsTruncated === true) {
65
+ parts.push("The project has more skills than are listed here.");
66
+ }
67
+ return parts.join("\n\n");
68
+ }
69
+ /** The latest `project_root` payload at or before `uptoSeq` (any order of `events`). */
70
+ export function latestProjectRoot(events, uptoSeq) {
71
+ let found;
72
+ for (const e of events) {
73
+ if (e.type !== "project_root" || e.seq > uptoSeq)
74
+ continue;
75
+ if (!found || e.seq > found.seq)
76
+ found = { seq: e.seq, payload: e.payload };
77
+ }
78
+ return found?.payload;
79
+ }
80
+ /**
81
+ * Whether the log ever recorded a project with a skill `Skill` can be called with (the ones the
82
+ * rendering lists, {@link callableProjectSkills}): then `Skill` is offered (like a skills catalog
83
+ * snapshot, never taken back, so the tool set and the cache prefix stay stable).
84
+ */
85
+ export const hasProjectSkills = (events) => events.some((e) => e.type === "project_root" && callableProjectSkills(e.payload).length > 0);
@@ -8,6 +8,7 @@ import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./conte
8
8
  import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, } from "./context/compaction.js";
9
9
  import { applyFit, estimateAfterFit, planFit, planningBounds, planReactiveTrim, planSqueezedFit, sentOutputCap, } from "./context/fit.js";
10
10
  import { guardToolPairs } from "./context/pairing.js";
11
+ import { hasProjectSkills, overlongProjectSkills } from "./context/project-root.js";
11
12
  import { TOOLS_UNSUPPORTED_REMINDER, turnLimitReminder } from "./context/reminders.js";
12
13
  import { calibrate, estimateTokens } from "./context/tokens.js";
13
14
  import { toolSetChange } from "./context/tool-changes.js";
@@ -112,7 +113,7 @@ export async function resolveAgentTools(deps, input, events) {
112
113
  sandboxConversationId: input.parent?.rootConversationId ?? input.conversationId,
113
114
  replay: input.conversationKind === "eval",
114
115
  source: input.source,
115
- skillLoad: skillLoadOffered(events.findLast((e) => e.type === "skills_catalog"), hasInvocation(events)),
116
+ skillLoad: skillLoadOffered(events.findLast((e) => e.type === "skills_catalog"), hasInvocation(events), hasProjectSkills(events)),
116
117
  });
117
118
  return {
118
119
  tools: resolved.tools,
@@ -221,6 +222,28 @@ export function runModelStep(deps, input) {
221
222
  export function runFinalWrapUp(deps, input, reason = "max_steps") {
222
223
  return runStep(deps, input, reason);
223
224
  }
225
+ /**
226
+ * Project root spec §4.5: a project skill whose callable name `project:<name>` is longer than the
227
+ * `Skill` schema takes is left out of the rendered list; said once, at the first step of the run
228
+ * that recorded the `project_root` (the rendering itself is pure and logs nothing).
229
+ */
230
+ function logOverlongProjectSkills(deps, input, events) {
231
+ const { conversationId, runId } = input;
232
+ const recorded = events.findLast((e) => e.type === "project_root");
233
+ if (recorded?.type !== "project_root" || recorded.runId !== runId)
234
+ return;
235
+ if (events.some((e) => e.type === "model_call" && e.runId === runId))
236
+ return;
237
+ const names = overlongProjectSkills(recorded.payload);
238
+ if (names.length === 0)
239
+ return;
240
+ deps.log.warn("project skills left out: their project:<name> is longer than Skill takes", {
241
+ conversationId,
242
+ runId,
243
+ project: recorded.payload.project,
244
+ skills: names,
245
+ });
246
+ }
224
247
  async function runStep(deps, input,
225
248
  /** The final call's reason, or null for an ordinary step. */
226
249
  wrapUpReason) {
@@ -244,6 +267,7 @@ wrapUpReason) {
244
267
  if (events.some((e) => e.type === "model_call" && e.runId === runId && e.payload.step === step)) {
245
268
  sink({ kind: "step_reset", runId, step });
246
269
  }
270
+ logOverlongProjectSkills(deps, input, events);
247
271
  // sticky (M-4): a model.request denial already logged for this step (any attempt, e.g. a crash
248
272
  // after recording it) is final: fail the same way, before compaction or any model call. Read from
249
273
  // the events just loaded, so it costs no query (M-2).