@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
@@ -113,6 +113,22 @@ export function tickerOf(t) {
113
113
  }
114
114
  /** How far back a DST transition can move a tick: longer than any gap (spec §5). */
115
115
  const TRANSITION_LOOKBACK_MS = 6 * 3600_000;
116
+ /**
117
+ * The cron library's search for the next date, or null when it gives up: it refuses to look more
118
+ * than a few years past the current date ("No execution date was found in the next 8 years"),
119
+ * which a yearly or Feb 29 expression reaches while the gap sample walks ahead. Any other error
120
+ * is thrown.
121
+ */
122
+ function nextOrNull(search) {
123
+ try {
124
+ return search();
125
+ }
126
+ catch (e) {
127
+ if (e instanceof Error && /No execution date was found/.test(e.message))
128
+ return null;
129
+ throw e;
130
+ }
131
+ }
116
132
  /**
117
133
  * {@link nextTick} for one trigger, with its `CronTime`s built once: callers that walk many ticks
118
134
  * (the gap sample, the catch-up enumeration) reuse one ticker instead of rebuilding per tick.
@@ -129,7 +145,10 @@ function ticker(t) {
129
145
  return (after) => {
130
146
  let cursor = after;
131
147
  for (let i = 0; i < 10; i++) {
132
- const tick = new Date(time.getNextDateFrom(cursor, t.timeZone).toMillis());
148
+ const next = nextOrNull(() => time.getNextDateFrom(cursor, t.timeZone).toMillis());
149
+ if (next === null)
150
+ return null;
151
+ const tick = new Date(next);
133
152
  const ms = tick.getTime();
134
153
  // CronTime moves a tick that falls in a DST gap to the next valid instant; the spec says a
135
154
  // skipped local time does not fire, so keep only ticks whose wall clock the expression
@@ -138,7 +157,7 @@ function ticker(t) {
138
157
  return tick;
139
158
  }
140
159
  const wall = localWallClock(tick, t.timeZone);
141
- if (wallTime.getNextDateFrom(new Date(wall - 1000), "UTC").toMillis() === wall)
160
+ if (nextOrNull(() => wallTime.getNextDateFrom(new Date(wall - 1000), "UTC").toMillis()) === wall)
142
161
  return tick;
143
162
  cursor = tick;
144
163
  }
@@ -27,6 +27,7 @@ import { orgAllows } from "../local-devices/network-grants.js";
27
27
  import { OrgLock } from "../orgs/org-lock.js";
28
28
  import { can, roleAtLeast } from "../orgs/roles.js";
29
29
  import { ProviderRegistry } from "../runtime/providers.js";
30
+ import { orgHostOutsideCeiling } from "../sandbox/modes.js";
30
31
  import { SandboxService } from "../sandbox/sandbox.service.js";
31
32
  import { isTimeZone } from "../time-zone.js";
32
33
  import { ToolRegistry } from "../tools/registry.js";
@@ -1111,7 +1112,8 @@ let ScheduledTasksService = class ScheduledTasksService {
1111
1112
  */
1112
1113
  async networkGrantContext(orgId) {
1113
1114
  const limits = await this.sandbox.ceilingLimits(orgId);
1114
- return { limits };
1115
+ const platform = this.config.get().sandbox.limits;
1116
+ return { limits, outsideCeiling: (h) => orgHostOutsideCeiling(platform, h) };
1115
1117
  }
1116
1118
  /**
1117
1119
  * The device a task's runs use, as far as the task tells: a `new` task's own device, a
@@ -118,7 +118,12 @@ export declare function skillLoadOffered(latest: Extract<ConversationEvent, {
118
118
  * with `skill`), so an agent whose skills are all manual-only can still copy an invoked skill's
119
119
  * files. Derived from the log, so a replay recomputes it.
120
120
  */
121
- invoked?: boolean): boolean;
121
+ invoked?: boolean,
122
+ /**
123
+ * Project root spec §4.5: the log recorded a bound project with skills (`hasProjectSkills`),
124
+ * which `Skill` loads as `project:<name>`. Derived from the log, never taken back.
125
+ */
126
+ projectSkills?: boolean): boolean;
122
127
  /** Whether `events` hold a person's skill invocation (a `user_message` with `skill`). */
123
128
  export declare const hasInvocation: (events: readonly ConversationEvent[]) => boolean;
124
129
  /** {@link skillLoadOffered} for a conversation, read from the database. */
@@ -17,6 +17,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
17
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
18
  import { KERNEL_LOGGER } from "../infra/tokens.js";
19
19
  import { CLAUDE_CODE_TOOL_MAP } from "../runtime/context/claude-tools.js";
20
+ import { PROJECT_SKILL_PREFIX, SKILL_NAME_MAX_CHARS } from "../runtime/context/project-root.js";
20
21
  import { catalogLine, sameSnapshot, } from "../runtime/context/skills.js";
21
22
  import { runEndedIn } from "../runtime/run-status.js";
22
23
  import { agentOwnSkillIds, agentSkills, builtinSkillIds, builtinSkillPlugins, } from "./usable.js";
@@ -191,8 +192,13 @@ export function skillLoadOffered(latest,
191
192
  * with `skill`), so an agent whose skills are all manual-only can still copy an invoked skill's
192
193
  * files. Derived from the log, so a replay recomputes it.
193
194
  */
194
- invoked = false) {
195
- return latest !== undefined || invoked;
195
+ invoked = false,
196
+ /**
197
+ * Project root spec §4.5: the log recorded a bound project with skills (`hasProjectSkills`),
198
+ * which `Skill` loads as `project:<name>`. Derived from the log, never taken back.
199
+ */
200
+ projectSkills = false) {
201
+ return latest !== undefined || invoked || projectSkills;
196
202
  }
197
203
  /** Whether `events` hold a person's skill invocation (a `user_message` with `skill`). */
198
204
  export const hasInvocation = (events) => events.some((e) => e.type === "user_message" && e.payload.skill !== undefined);
@@ -204,8 +210,16 @@ export async function skillLoadOfferedIn(db, eventLog, conversationId) {
204
210
  .selectFrom("conversation_events")
205
211
  .select("seq")
206
212
  .where("conversation_id", "=", conversationId)
207
- .where("type", "=", "user_message")
208
- .where(sql `payload -> 'skill' IS NOT NULL`)
213
+ .where((eb) => eb.or([
214
+ eb.and([eb("type", "=", "user_message"), sql `payload -> 'skill' IS NOT NULL`]),
215
+ // a project with a skill Skill can be called with (hasProjectSkills: `project:<name>`
216
+ // within the schema's cap; skill names are ASCII, so characters are UTF-16 code units)
217
+ eb.and([
218
+ eb("type", "=", "project_root"),
219
+ sql `EXISTS (SELECT 1 FROM jsonb_array_elements(payload -> 'skills') s
220
+ WHERE length(${PROJECT_SKILL_PREFIX}::text || (s ->> 'name')) <= ${SKILL_NAME_MAX_CHARS})`,
221
+ ]),
222
+ ]))
209
223
  .limit(1)
210
224
  .executeTakeFirst();
211
225
  return row !== undefined;
@@ -1,11 +1,16 @@
1
1
  import { AgentLookup } from "../agents/agent-lookup.js";
2
2
  import { type AgentDefinition } from "../agents/definition.js";
3
+ import { EventLog } from "../conversations/event-log.js";
3
4
  import type { EventPayload } from "../conversations/events.js";
4
5
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
6
+ import { ConversationDevices } from "../devices/conversation-devices.js";
5
7
  import { ApiError } from "../errors.js";
6
8
  import { KernelDb } from "../infra/database/kernel-db.js";
7
9
  import type { KernelLogger } from "../log.js";
10
+ import { type ProjectRootPayload } from "../runtime/context/project-root.js";
11
+ import { SandboxService } from "../sandbox/sandbox.service.js";
8
12
  import { StorageService } from "../storage/storage.service.js";
13
+ import { type ResolvedSkill } from "./catalog.js";
9
14
  /**
10
15
  * A person's skill invocation (phase D spec §3, §4): the `/` menu's list of the agent's invocable
11
16
  * skills, and the rendering of `/name args` into the model-visible text of their message. The skill
@@ -14,10 +19,19 @@ import { StorageService } from "../storage/storage.service.js";
14
19
  * manifest, and it is rendered by the SDK; nothing is executed (A1). The caller appends the text as
15
20
  * `content[0]` of the `user_message` together with {@link RenderedInvocation.skill}.
16
21
  */
22
+ /**
23
+ * Where a `/` menu entry comes from (project root spec §4.6; the palette groups by it): the agent's
24
+ * own skill, a plugin's, the org library or the platform (`platform`), or the conversation's
25
+ * project.
26
+ */
27
+ export type InvocableSource = "platform" | "plugin" | "agent" | "project";
17
28
  /** One skill of the `/` menu (`GET …/agents/:agentId/invocable-skills`). */
18
29
  export interface InvocableSkill {
30
+ /** A project skill's is its callable name, `project:<name>` (it has no row). */
19
31
  id: string;
32
+ /** The bare name; a project skill's callable name `project:<name>`. */
20
33
  name: string;
34
+ source: InvocableSource;
21
35
  /** The plugin (catalog item) it came from. */
22
36
  plugin?: string;
23
37
  description: string;
@@ -52,6 +66,27 @@ export declare const parseSlashCommand: (text: string) => {
52
66
  /** Why a person cannot invoke a skill (`skill.not_invocable` details). */
53
67
  export type NotInvocableReason = "not_found" | "not_user_invocable";
54
68
  export declare const notInvocable: (reason: NotInvocableReason, name: string) => ApiError;
69
+ /** Why a listed project skill cannot be used now (`skill.project_unavailable` details). */
70
+ export type ProjectUnavailableReason = "gone" | "outside_mode" | "unreadable" | "unparsable" | "unsupported" | "removed";
71
+ /** Where an effective skill comes from, for the `/` menu ({@link InvocableSource}). */
72
+ export declare const invocableSource: (r: {
73
+ scope: ResolvedSkill["scope"];
74
+ skill: {
75
+ plugin?: string | undefined;
76
+ };
77
+ }) => InvocableSource;
78
+ /**
79
+ * The `/` menu entries of a conversation's latest `project_root` (project root spec §4.6: what the
80
+ * model saw, never a fresh read of the device): its skills as `project:<name>`, sorted, none for an
81
+ * unavailable project or none. A skill whose callable name `Skill` cannot take is left out, as in
82
+ * the model's list.
83
+ */
84
+ export declare function projectInvocables(p: ProjectRootPayload | undefined): InvocableSkill[];
85
+ /**
86
+ * Whether a recorded project skill invocation (`project:<name>`) is still one of the latest usable
87
+ * `project_root`'s skills; null when it is.
88
+ */
89
+ export declare function projectSkillBlocked(p: ProjectRootPayload | undefined, name: string): NotInvocableReason | null;
55
90
  /**
56
91
  * Whether the skill a queued invocation recorded is still one a person can invoke in this
57
92
  * conversation (phase D Task 9, checked again at dispatch): the same skill (by id) among the
@@ -79,11 +114,21 @@ export declare class SkillInvoker {
79
114
  private readonly storage;
80
115
  private readonly agents;
81
116
  private readonly log;
82
- constructor(db: KernelDb, storage: StorageService, agents: Pick<AgentLookup, "get">, log: KernelLogger);
117
+ /** A bound conversation's latest `project_root` (its project skills). */
118
+ private readonly eventLog;
119
+ /** A project skill's SKILL.md is read through the conversation's device. */
120
+ private readonly sandbox;
121
+ private readonly devices;
122
+ constructor(db: KernelDb, storage: StorageService, agents: Pick<AgentLookup, "get">, log: KernelLogger,
123
+ /** A bound conversation's latest `project_root` (its project skills). */
124
+ eventLog: Pick<EventLog, "latestOfType">,
125
+ /** A project skill's SKILL.md is read through the conversation's device. */
126
+ sandbox: Pick<SandboxService, "withSandbox">, devices: Pick<ConversationDevices, "forTool" | "modeLevel" | "workingFacts">);
83
127
  /**
84
128
  * The `/` menu for `accountId`: the agent must be usable by them (`agent.not_found`), and with
85
129
  * `conversationId` the conversation must be theirs and the agent's (`conversation.not_found`);
86
- * then its trial drafts apply.
130
+ * then its trial drafts apply, and its latest usable `project_root` adds the project's skills
131
+ * after the agent's ({@link projectInvocables}).
87
132
  */
88
133
  listFor(orgId: string, agentId: string, accountId: string, conversationId?: string): Promise<InvocableSkill[]>;
89
134
  /**
@@ -101,16 +146,33 @@ export declare class SkillInvoker {
101
146
  * invocation (spec §4.2, §4.3, §6.3). Refusals: `skill.not_invocable` (400); arguments or a
102
147
  * rendered text over the limits → `validation_failed` (400); a storage failure or a SKILL.md
103
148
  * that fails its integrity check → `storage.unavailable` (503). Nothing is written here.
149
+ * `project:<name>` is the conversation's project skill ({@link prepareProject}).
104
150
  */
105
151
  prepare(a: {
106
152
  orgId: string;
107
153
  agentId: string;
154
+ /** The person sending (a project skill is read on the device as them). */
155
+ accountId: string;
108
156
  /** Absent for the first message of a conversation not created yet. */
109
157
  conversationId?: string;
110
158
  agent: AgentDefinition;
111
159
  name: string;
112
160
  args: string;
113
161
  }): Promise<RenderedInvocation>;
162
+ /**
163
+ * A person's invocation of `project:<name>` (project root spec §4.6): resolved from the
164
+ * conversation's latest `project_root` (what the model saw), then its SKILL.md is read through
165
+ * the conversation's device as `Skill` reads it ({@link readProjectSkill}) and rendered like any
166
+ * invocation, `${CLAUDE_SKILL_DIR}` being the skill's directory in the project. Always inline
167
+ * (`context: fork` is not honoured for project skills, as in `Skill`). Refusals:
168
+ * `skill.not_invocable` `not_found` (no conversation yet, no project, a name it does not list),
169
+ * `skill.project_unavailable` with its reason (the latest project is unavailable, or its file
170
+ * cannot be used), the device's own refusals as they are (`device.offline`, ...),
171
+ * `device.projects_unavailable` when the device cannot be asked.
172
+ */
173
+ private prepareProject;
174
+ /** {@link readProjectSkill} in a silent use of the conversation's device, as its owner. */
175
+ private readProjectFile;
114
176
  /**
115
177
  * The task of a fork invocation's sub-agent (spec §6.2), rendered at dispatch from the version
116
178
  * the person's message recorded (`skill.{id, source, version, arguments}`), never by name, so a
@@ -7,17 +7,24 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { escapeSkillInvocationTags, hasShellInjection, parseSkillMd, renderSkillBody, renderSkillInvocation, SKILL_ENTRY_FILE, SKILL_INVOCATION_LIMITS, skillDigest, } from "@capybara-hq/plugin-sdk";
10
+ import { escapeSkillInvocationTags, hasShellInjection, parseSkillMd, renderSkillBody, renderSkillInvocation, SKILL_ENTRY_FILE, SKILL_INVOCATION_LIMITS, skillDigest, skillSandboxDir, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { AgentLookup } from "../agents/agent-lookup.js";
13
13
  import { builtinDisabled } from "../agents/definition.js";
14
+ import { EventLog } from "../conversations/event-log.js";
15
+ import { ConversationDevices } from "../devices/conversation-devices.js";
16
+ import { providerUnreachable } from "../devices/device-projects.service.js";
14
17
  import { ApiError } from "../errors.js";
15
18
  import { KernelDb } from "../infra/database/kernel-db.js";
16
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
20
+ import { callableProjectSkills, projectSkillName, projectSkillOf, } from "../runtime/context/project-root.js";
17
21
  import { isGeneralAlias, resolveSkillForkType } from "../runtime/subagents/roster.js";
22
+ import { SandboxService } from "../sandbox/sandbox.service.js";
23
+ import { SandboxProviderUnreachableError } from "../sandbox/unreachable.js";
18
24
  import { StorageService } from "../storage/storage.service.js";
19
25
  import { BUILTIN } from "../tools/builtin-names.js";
20
- import { findSkillVersion, readSkillFile, SkillIntegrityError, } from "../tools/builtins/skill-load.js";
26
+ import { sessionWorkingRoot } from "../tools/builtins/sandbox/common.js";
27
+ import { findSkillVersion, PROJECT_DIR_DIGEST, ProjectSkillReadError, readProjectSkill, readSkillFile, SkillIntegrityError, } from "../tools/builtins/skill-load.js";
21
28
  import { invocationOf, resolveSkills } from "./catalog.js";
22
29
  import { skillFileStore } from "./usable.js";
23
30
  /** A leading `/<name>` or `/<plugin>:<name>`, then whitespace or the end (spec §3.2). */
@@ -44,6 +51,65 @@ function findSkill(all, name) {
44
51
  export const notInvocable = (reason, name) => new ApiError("skill.not_invocable", reason === "not_found"
45
52
  ? `Skill "${name}" is not one of this agent's skills`
46
53
  : `Skill "${name}" cannot be invoked by a person`, [{ reason }]);
54
+ /** A project skill the project lists but cannot be used now: the person is told why. */
55
+ const projectUnavailable = (reason, message) => new ApiError("skill.project_unavailable", message, [{ reason }]);
56
+ /** The refusal of a {@link ProjectSkillProblem}: its reason and the person's text. */
57
+ function projectProblemRefusal(name, p) {
58
+ switch (p.kind) {
59
+ case "outside_mode":
60
+ return projectUnavailable("outside_mode", `Skill "${name}" cannot be invoked: ${p.path} is outside what the device can read in ${p.mode} mode now`);
61
+ case "gone":
62
+ return projectUnavailable("gone", `Skill "${name}" cannot be invoked: ${p.path} is no longer on the device`);
63
+ case "read_failed":
64
+ return projectUnavailable("unreadable", `Skill "${name}" cannot be invoked: reading ${p.path} on the device failed (${p.why.slice(0, 300)})`);
65
+ case "invalid":
66
+ return projectUnavailable("unparsable", `Skill "${name}" cannot be invoked: ${p.path} is not a valid SKILL.md (${p.why.slice(0, 300)})`);
67
+ }
68
+ }
69
+ /** The longest a person's invocation waits for its project skill's SKILL.md on the device. */
70
+ const PROJECT_SKILL_READ_TIMEOUT_MS = 30_000;
71
+ /** Where an effective skill comes from, for the `/` menu ({@link InvocableSource}). */
72
+ export const invocableSource = (r) => r.scope === "agent" ? "agent" : r.skill.plugin !== undefined ? "plugin" : "platform";
73
+ /**
74
+ * The `/` menu entries of a conversation's latest `project_root` (project root spec §4.6: what the
75
+ * model saw, never a fresh read of the device): its skills as `project:<name>`, sorted, none for an
76
+ * unavailable project or none. A skill whose callable name `Skill` cannot take is left out, as in
77
+ * the model's list.
78
+ */
79
+ export function projectInvocables(p) {
80
+ if (p === undefined || p.unavailable !== undefined)
81
+ return [];
82
+ return callableProjectSkills(p)
83
+ .map((s) => ({
84
+ id: projectSkillName(s.name),
85
+ name: projectSkillName(s.name),
86
+ source: "project",
87
+ description: s.description,
88
+ version: 0,
89
+ manual: false,
90
+ fork: false,
91
+ }))
92
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
93
+ }
94
+ /**
95
+ * Whether a recorded project skill invocation (`project:<name>`) is still one of the latest usable
96
+ * `project_root`'s skills; null when it is.
97
+ */
98
+ export function projectSkillBlocked(p, name) {
99
+ return projectInvocables(p).some((s) => s.name === name) ? null : "not_found";
100
+ }
101
+ /** The payload of the conversation's latest `project_root`, read with `db`. */
102
+ async function latestProjectRoot(db, conversationId) {
103
+ const row = await db
104
+ .selectFrom("conversation_events")
105
+ .select("payload")
106
+ .where("conversation_id", "=", conversationId)
107
+ .where("type", "=", "project_root")
108
+ .orderBy("seq", "desc")
109
+ .limit(1)
110
+ .executeTakeFirst();
111
+ return row?.payload;
112
+ }
47
113
  /**
48
114
  * Whether the skill a queued invocation recorded is still one a person can invoke in this
49
115
  * conversation (phase D Task 9, checked again at dispatch): the same skill (by id) among the
@@ -51,6 +117,9 @@ export const notInvocable = (reason, name) => new ApiError("skill.not_invocable"
51
117
  * text stays as rendered when queued. Null when it is, else the reason.
52
118
  */
53
119
  export async function recordedSkillBlocked(db, a) {
120
+ if (projectSkillOf(a.skillId) !== undefined) {
121
+ return projectSkillBlocked(await latestProjectRoot(db, a.conversationId), a.skillId);
122
+ }
54
123
  const found = (await resolveSkills(db, a)).find((r) => r.skill.id === a.skillId);
55
124
  if (!found)
56
125
  return "not_found";
@@ -70,16 +139,27 @@ let SkillInvoker = class SkillInvoker {
70
139
  storage;
71
140
  agents;
72
141
  log;
73
- constructor(db, storage, agents, log) {
142
+ eventLog;
143
+ sandbox;
144
+ devices;
145
+ constructor(db, storage, agents, log,
146
+ /** A bound conversation's latest `project_root` (its project skills). */
147
+ eventLog,
148
+ /** A project skill's SKILL.md is read through the conversation's device. */
149
+ sandbox, devices) {
74
150
  this.db = db;
75
151
  this.storage = storage;
76
152
  this.agents = agents;
77
153
  this.log = log;
154
+ this.eventLog = eventLog;
155
+ this.sandbox = sandbox;
156
+ this.devices = devices;
78
157
  }
79
158
  /**
80
159
  * The `/` menu for `accountId`: the agent must be usable by them (`agent.not_found`), and with
81
160
  * `conversationId` the conversation must be theirs and the agent's (`conversation.not_found`);
82
- * then its trial drafts apply.
161
+ * then its trial drafts apply, and its latest usable `project_root` adds the project's skills
162
+ * after the agent's ({@link projectInvocables}).
83
163
  */
84
164
  async listFor(orgId, agentId, accountId, conversationId) {
85
165
  const agent = await this.agents.get(orgId, agentId, accountId);
@@ -96,12 +176,16 @@ let SkillInvoker = class SkillInvoker {
96
176
  if (!row)
97
177
  throw new ApiError("conversation.not_found", "Conversation not found");
98
178
  }
99
- return this.list({
179
+ const skills = await this.list({
100
180
  orgId,
101
181
  agentId,
102
182
  agent: agent.definition,
103
183
  ...(conversationId !== undefined && { conversationId }),
104
184
  });
185
+ if (conversationId === undefined)
186
+ return skills;
187
+ const latest = await this.eventLog.latestOfType(conversationId, "project_root");
188
+ return [...skills, ...projectInvocables(latest?.payload)];
105
189
  }
106
190
  /**
107
191
  * The agent's effective skills a person can invoke (`user` not false), sorted by name (code
@@ -117,6 +201,7 @@ let SkillInvoker = class SkillInvoker {
117
201
  out.push({
118
202
  id: r.skill.id,
119
203
  name: r.skill.name,
204
+ source: invocableSource(r),
120
205
  ...(r.skill.plugin !== undefined && { plugin: r.skill.plugin }),
121
206
  description: r.skill.description,
122
207
  version: r.skill.version,
@@ -133,8 +218,13 @@ let SkillInvoker = class SkillInvoker {
133
218
  * invocation (spec §4.2, §4.3, §6.3). Refusals: `skill.not_invocable` (400); arguments or a
134
219
  * rendered text over the limits → `validation_failed` (400); a storage failure or a SKILL.md
135
220
  * that fails its integrity check → `storage.unavailable` (503). Nothing is written here.
221
+ * `project:<name>` is the conversation's project skill ({@link prepareProject}).
136
222
  */
137
223
  async prepare(a) {
224
+ // project root spec §4.6: the prefix is the project's, never a plugin's qualified name
225
+ const bare = projectSkillOf(a.name);
226
+ if (bare !== undefined)
227
+ return this.prepareProject(a, bare);
138
228
  const all = await resolveSkills(this.db.db, a);
139
229
  const found = findSkill(all, a.name);
140
230
  if (!found)
@@ -186,6 +276,121 @@ let SkillInvoker = class SkillInvoker {
186
276
  }),
187
277
  };
188
278
  }
279
+ /**
280
+ * A person's invocation of `project:<name>` (project root spec §4.6): resolved from the
281
+ * conversation's latest `project_root` (what the model saw), then its SKILL.md is read through
282
+ * the conversation's device as `Skill` reads it ({@link readProjectSkill}) and rendered like any
283
+ * invocation, `${CLAUDE_SKILL_DIR}` being the skill's directory in the project. Always inline
284
+ * (`context: fork` is not honoured for project skills, as in `Skill`). Refusals:
285
+ * `skill.not_invocable` `not_found` (no conversation yet, no project, a name it does not list),
286
+ * `skill.project_unavailable` with its reason (the latest project is unavailable, or its file
287
+ * cannot be used), the device's own refusals as they are (`device.offline`, ...),
288
+ * `device.projects_unavailable` when the device cannot be asked.
289
+ */
290
+ async prepareProject(a, bare) {
291
+ const { conversationId } = a;
292
+ if (conversationId === undefined)
293
+ throw notInvocable("not_found", a.name);
294
+ const latest = (await this.eventLog.latestOfType(conversationId, "project_root"))?.payload;
295
+ if (latest?.unavailable !== undefined) {
296
+ throw projectUnavailable(latest.unavailable.reason, `Skill "${a.name}" cannot be invoked: the project "${latest.project}" is not available (${latest.unavailable.message})`);
297
+ }
298
+ if (projectSkillBlocked(latest, a.name) !== null || latest === undefined) {
299
+ throw notInvocable("not_found", a.name);
300
+ }
301
+ const file = await this.readProjectFile({ ...a, conversationId }, latest.root, bare);
302
+ const args = a.args.trim();
303
+ // the renderer's skills-root directory becomes the skill's directory in the project (a closing
304
+ // tag in the path stays inert, as in the body)
305
+ const dir = file.dir.replace(/<\//g, "<\\/");
306
+ const text = rendered(() => renderSkillInvocation({
307
+ name: a.name,
308
+ skillName: bare,
309
+ digest: PROJECT_DIR_DIGEST,
310
+ version: 0,
311
+ body: file.body,
312
+ invocation: file.invocation,
313
+ args: a.args,
314
+ lines: {
315
+ ...(hasShellInjection(file.body) &&
316
+ hasBuiltin(a.agent, BUILTIN.Bash) && { shellHint: true }),
317
+ },
318
+ })).replaceAll(skillSandboxDir(bare, PROJECT_DIR_DIGEST), dir);
319
+ const full = [
320
+ text,
321
+ ...(file.truncated
322
+ ? [
323
+ `Its SKILL.md was cut at 1 MiB when it was read; the rest of its instructions is missing.`,
324
+ ]
325
+ : []),
326
+ `Its other files, if any, are in ${dir}/ on the device; use them there.`,
327
+ ].join("\n\n");
328
+ // the closing lines count toward the limit too
329
+ if (full.length > SKILL_INVOCATION_LIMITS.renderedMaxChars) {
330
+ throw new ApiError("validation_failed", "Request validation failed", [
331
+ {
332
+ path: "text",
333
+ message: `the rendered skill must be at most ${SKILL_INVOCATION_LIMITS.renderedMaxChars} characters; shorten the arguments`,
334
+ },
335
+ ]);
336
+ }
337
+ return {
338
+ text: full,
339
+ skill: {
340
+ id: a.name,
341
+ version: 0,
342
+ source: "project",
343
+ name: a.name,
344
+ arguments: args,
345
+ mode: "inline",
346
+ },
347
+ };
348
+ }
349
+ /** {@link readProjectSkill} in a silent use of the conversation's device, as its owner. */
350
+ async readProjectFile(a, root, bare) {
351
+ try {
352
+ const deviceId = await this.devices.forTool(a.orgId, a.conversationId);
353
+ // a person invokes in a root conversation: it is its own sandbox conversation
354
+ const [level, working] = await Promise.all([
355
+ this.devices.modeLevel(a.orgId, deviceId),
356
+ this.devices.workingFacts(a.orgId, a.conversationId, a.conversationId, deviceId),
357
+ ]);
358
+ // unknown mode: the strict (sandbox) path checks stay (fail closed), as in a tool call
359
+ const mode = level?.mode ?? "sandbox";
360
+ return await this.sandbox.withSandbox({
361
+ orgId: a.orgId,
362
+ deviceId,
363
+ holderConversationId: a.conversationId,
364
+ // tells the model nothing: its next tool call still learns what the device did
365
+ silent: true,
366
+ actor: { accountId: a.accountId, conversationId: a.conversationId },
367
+ }, (h, p, info, signal) => readProjectSkill({
368
+ deviceId,
369
+ mode,
370
+ h,
371
+ roots: info.roots,
372
+ // the working root a tool call of this conversation would get (one rule)
373
+ workingRoot: sessionWorkingRoot(working, mode, info.roots.workspace),
374
+ p,
375
+ signal,
376
+ }, root, bare), AbortSignal.timeout(PROJECT_SKILL_READ_TIMEOUT_MS));
377
+ }
378
+ catch (e) {
379
+ if (e instanceof ProjectSkillReadError)
380
+ throw projectProblemRefusal(a.name, e.problem);
381
+ if (e instanceof ApiError)
382
+ throw e;
383
+ if (e instanceof SandboxProviderUnreachableError)
384
+ throw providerUnreachable();
385
+ this.log.warn("project skill unreadable: the device could not be asked", {
386
+ orgId: a.orgId,
387
+ conversationId: a.conversationId,
388
+ skill: a.name,
389
+ err: e,
390
+ });
391
+ throw new ApiError("device.projects_unavailable", "The device could not be reached to read the project skill; retry later");
392
+ }
393
+ }
189
394
  /**
190
395
  * The task of a fork invocation's sub-agent (spec §6.2), rendered at dispatch from the version
191
396
  * the person's message recorded (`skill.{id, source, version, arguments}`), never by name, so a
@@ -287,7 +492,10 @@ SkillInvoker = __decorate([
287
492
  __param(0, Inject(KernelDb)),
288
493
  __param(1, Inject(StorageService)),
289
494
  __param(2, Inject(AgentLookup)),
290
- __param(3, Inject(KERNEL_LOGGER))
495
+ __param(3, Inject(KERNEL_LOGGER)),
496
+ __param(4, Inject(EventLog)),
497
+ __param(5, Inject(SandboxService)),
498
+ __param(6, Inject(ConversationDevices))
291
499
  ], SkillInvoker);
292
500
  export { SkillInvoker };
293
501
  /**
@@ -9,7 +9,9 @@ import { AgentLookupModule } from "../agents/agent-lookup.js";
9
9
  import { CatalogImportModule } from "../catalog/catalog-import.module.js";
10
10
  import { AttachmentsModule } from "../conversations/attachments.module.js";
11
11
  import { EventLogModule } from "../conversations/event-log.js";
12
+ import { DevicesModule } from "../devices/devices.module.js";
12
13
  import { OrgLockModule } from "../orgs/org-lock.js";
14
+ import { SandboxModule } from "../sandbox/sandbox.module.js";
13
15
  import { StorageModule } from "../storage/storage.module.js";
14
16
  import { AgentSkillsService } from "./agent-skills.service.js";
15
17
  import { SkillsCatalogService } from "./catalog.js";
@@ -32,6 +34,9 @@ SkillsModule = __decorate([
32
34
  AgentLookupModule,
33
35
  // the owner's new version of a skill it promoted goes to the platform row (ruling P3-4)
34
36
  CatalogImportModule,
37
+ // a person's invocation of a project skill reads its SKILL.md on the conversation's device
38
+ DevicesModule,
39
+ SandboxModule,
35
40
  ],
36
41
  providers: [
37
42
  AgentSkillsService,
@@ -124,6 +124,12 @@ export interface CommandAskDetail {
124
124
  command: string;
125
125
  /** A write's target path. */
126
126
  path?: string;
127
+ /**
128
+ * The working root the call was reviewed against (project root spec §4.3), always recorded (the
129
+ * device's workspace in free mode): the approved call runs in a project root recorded here,
130
+ * whatever snapshot came after the ask. Absent when no device was resolved.
131
+ */
132
+ workingRoot?: string;
127
133
  /** The rule that asked, or null for a classifier ask (which offers `once` only). */
128
134
  rule: string | null;
129
135
  reason: string;
@@ -1,7 +1,7 @@
1
1
  import { DEFAULT_SANDBOX_ROOTS, ToolError, } from "@capybara-hq/plugin-sdk";
2
2
  import { backgroundMaxSeconds, LAUNCH_EXEC_TIMEOUT_MS, launchScript, newTaskId, startedText, taskOutputPath, taskSidPath, } from "../../../background/launch.js";
3
3
  import { KILL_SESSION_TIMEOUT_MS, killSession, SID_RE } from "../../../background/session.js";
4
- import { clip, display, inSandbox, mapSandboxError, noSandboxError, runBudgetNote, runTimeLeftMs, sandboxBaseTimeoutMs, sandboxConversationOf, unavailableWhenNoSandbox, withNotices, } from "./common.js";
4
+ import { clip, display, inSandbox, mapSandboxError, noSandboxError, runBudgetNote, runTimeLeftMs, sandboxBaseTimeoutMs, sandboxConversationOf, shellQuote, unavailableWhenNoSandbox, withNotices, } from "./common.js";
5
5
  import { parseDeviceCode } from "./device-code.js";
6
6
  /** The command timeout in seconds when `timeout` is not given, at most `sandbox.limits.maxCommandSeconds`. */
7
7
  export const BASH_DEFAULT_TIMEOUT_SECONDS = 120;
@@ -208,7 +208,8 @@ async function runInBackground(deps, ctx, input) {
208
208
  let launch;
209
209
  let notices;
210
210
  try {
211
- ({ value: launch, notices } = await inSandbox(deps, ctx, async ({ h, roots, p, signal }) => {
211
+ ({ value: launch, notices } = await inSandbox(deps, ctx, async (s) => {
212
+ const { h, roots, p, signal } = s;
212
213
  workspace = roots.workspace;
213
214
  // right after the launch a process may fork while it is killed: killSession repeats
214
215
  const kill = (sid) => killSession(p, h, sid);
@@ -227,7 +228,9 @@ async function runInBackground(deps, ctx, input) {
227
228
  let r;
228
229
  try {
229
230
  r = await p.exec(h, {
230
- command: launchScript(id, input.command, seconds),
231
+ // the launch keeps its task files under the workspace (`.capybara/tasks`, where
232
+ // TaskOutput and TaskStop find them); the command itself starts in the working root
233
+ command: launchScript(id, inWorkingRoot(input.command, s), seconds),
231
234
  cwd: roots.workspace,
232
235
  timeoutMs: LAUNCH_EXEC_TIMEOUT_MS,
233
236
  maxOutputBytes: LAUNCH_MAX_OUTPUT_BYTES,
@@ -331,6 +334,17 @@ async function runInBackground(deps, ctx, input) {
331
334
  display: display(`后台运行命令:${shown}`, `Started in the background: ${shown}`),
332
335
  };
333
336
  }
337
+ /**
338
+ * A background command's script, started in the conversation's working root: the launch itself
339
+ * runs in the workspace (its task files live under `.capybara/tasks` there), so for a bound
340
+ * project the script first changes into the project's root, and ends (exit 1) without running the
341
+ * command when it cannot.
342
+ */
343
+ function inWorkingRoot(command, s) {
344
+ if (s.workingRoot === s.roots.workspace)
345
+ return command;
346
+ return `cd -- ${shellQuote(s.workingRoot)} || exit 1\n${command}`;
347
+ }
334
348
  /** 内置工具 `Bash`:在本对话的沙箱里执行命令。 */
335
349
  export function sandboxBashTool(deps) {
336
350
  return {
@@ -370,7 +384,8 @@ export function sandboxBashTool(deps) {
370
384
  deviceId = s.deviceId;
371
385
  return s.p.exec(s.h, {
372
386
  command,
373
- cwd: s.roots.workspace,
387
+ // the working root: a bound project's root, else the workspace
388
+ cwd: s.workingRoot,
374
389
  timeoutMs: ms,
375
390
  maxOutputBytes: MAX_OUTPUT_BYTES,
376
391
  signal: s.signal,