@capybara-hq/kernel 0.1.0-rc.32 → 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 (85) 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/db/kernel-schema.d.ts +20 -0
  15. package/dist/devices/conversation-devices.d.ts +57 -3
  16. package/dist/devices/conversation-devices.js +63 -11
  17. package/dist/devices/device-projects.service.d.ts +162 -0
  18. package/dist/devices/device-projects.service.js +503 -0
  19. package/dist/devices/devices.controller.d.ts +15 -2
  20. package/dist/devices/devices.controller.js +60 -3
  21. package/dist/devices/devices.module.js +15 -2
  22. package/dist/devices/devices.schemas.js +9 -1
  23. package/dist/devices/dto.d.ts +31 -0
  24. package/dist/devices/dto.js +38 -1
  25. package/dist/devices/working-root.d.ts +41 -0
  26. package/dist/devices/working-root.js +50 -0
  27. package/dist/errors.d.ts +39 -0
  28. package/dist/errors.js +39 -0
  29. package/dist/evals/run-replay.d.ts +9 -1
  30. package/dist/evals/run-replay.js +15 -1
  31. package/dist/local-devices/local-device-provider.d.ts +37 -1
  32. package/dist/local-devices/local-device-provider.js +33 -0
  33. package/dist/local-devices/machines.d.ts +2 -1
  34. package/dist/local-devices/machines.js +4 -1
  35. package/dist/local-devices/policy-summary.js +1 -0
  36. package/dist/local-devices/relay.d.ts +2 -0
  37. package/dist/local-devices/relay.js +3 -1
  38. package/dist/local-devices/targets.d.ts +6 -1
  39. package/dist/local-devices/targets.js +14 -0
  40. package/dist/overrides.d.ts +4 -0
  41. package/dist/overrides.js +2 -0
  42. package/dist/platform/ops/agent-skills.ops.js +2 -1
  43. package/dist/platform/ops/devices.ops.d.ts +3 -1
  44. package/dist/platform/ops/devices.ops.js +136 -3
  45. package/dist/runtime/context/build.d.ts +3 -0
  46. package/dist/runtime/context/build.js +14 -0
  47. package/dist/runtime/context/compaction.js +2 -0
  48. package/dist/runtime/context/project-root.d.ts +43 -0
  49. package/dist/runtime/context/project-root.js +85 -0
  50. package/dist/runtime/model-call.js +25 -1
  51. package/dist/runtime/project/knowledge.d.ts +129 -0
  52. package/dist/runtime/project/knowledge.js +248 -0
  53. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  54. package/dist/runtime/project/knowledge.service.js +288 -0
  55. package/dist/runtime/run-worker.d.ts +5 -0
  56. package/dist/runtime/run-worker.js +27 -6
  57. package/dist/runtime/runtime.module.js +7 -0
  58. package/dist/sandbox/review/review.service.d.ts +14 -2
  59. package/dist/sandbox/review/review.service.js +2 -0
  60. package/dist/sandbox/review/rules.d.ts +6 -4
  61. package/dist/sandbox/review/rules.js +185 -62
  62. package/dist/sandbox/review/types.d.ts +14 -0
  63. package/dist/sandbox/sandbox.service.d.ts +16 -1
  64. package/dist/sandbox/sandbox.service.js +75 -3
  65. package/dist/skills/catalog.d.ts +6 -1
  66. package/dist/skills/catalog.js +18 -4
  67. package/dist/skills/invoke.d.ts +64 -2
  68. package/dist/skills/invoke.js +214 -6
  69. package/dist/skills/skills.module.js +5 -0
  70. package/dist/tools/approvals.service.d.ts +6 -0
  71. package/dist/tools/builtins/sandbox/bash.js +19 -4
  72. package/dist/tools/builtins/sandbox/common.d.ts +36 -6
  73. package/dist/tools/builtins/sandbox/common.js +69 -8
  74. package/dist/tools/builtins/sandbox/edit.js +2 -2
  75. package/dist/tools/builtins/sandbox/glob.js +3 -2
  76. package/dist/tools/builtins/sandbox/grep.js +2 -1
  77. package/dist/tools/builtins/sandbox/read.js +3 -3
  78. package/dist/tools/builtins/sandbox/write.js +2 -2
  79. package/dist/tools/builtins/skill-load.d.ts +47 -2
  80. package/dist/tools/builtins/skill-load.js +160 -2
  81. package/dist/tools/pipeline.d.ts +1 -1
  82. package/dist/tools/pipeline.js +53 -8
  83. package/dist/tools/registry.d.ts +6 -0
  84. package/package.json +2 -2
  85. package/src/migrations/0133_project_root.sql +30 -0
@@ -44,6 +44,26 @@ const EXCLUSIVE_WAIT_MS = 10 * 60_000;
44
44
  const PENDING_KILL_TIMEOUT_MS = 30_000;
45
45
  /** A background task's session id as `echo $!` printed it; anything else is never put in a command. */
46
46
  const SID_RE = /^[1-9][0-9]{0,9}$/;
47
+ const noticeKey = (deviceId, holder) => `capk:sandbox-notice:${deviceId}:${holder}`;
48
+ /** A stored {@link DeferredNotice}, or null (none, or not one). */
49
+ function parseDeferred(raw) {
50
+ if (raw === null)
51
+ return null;
52
+ try {
53
+ const v = JSON.parse(raw);
54
+ if (typeof v.seen !== "string")
55
+ return null;
56
+ return {
57
+ seen: v.seen,
58
+ fresh: v.fresh === true,
59
+ restarted: v.restarted === true,
60
+ filesReset: v.filesReset === true,
61
+ };
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
47
67
  /** The signal of one provider call in maintenance: aborted on timeout or when the lease is lost. */
48
68
  const opSignal = (lease) => AbortSignal.any([lease.signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]);
49
69
  /** The provider-side name of a device's file system and instance. */
@@ -599,7 +619,8 @@ let SandboxService = class SandboxService {
599
619
  // decides the shared fast path only (read again before each shared lease is used): the
600
620
  // exclusive path reads it again under the lease
601
621
  const want = () => this.wantedLimits(ctx, p);
602
- let e = await this.seenBy(env, holder, await this.enter(ctx, p, signal, null, want));
622
+ const seen = (x) => ctx.silent ? this.deferNotice(env, holder, x) : this.seenBy(env, holder, x);
623
+ let e = await seen(await this.enter(ctx, p, signal, null, want));
603
624
  try {
604
625
  try {
605
626
  return await this.runAs(e, ctx, p, fn, signal);
@@ -613,7 +634,7 @@ let SandboxService = class SandboxService {
613
634
  const gone = { handle: e.handle, createdAt: e.createdAt };
614
635
  const prev = e;
615
636
  await this.leave(env, prev);
616
- e = await this.seenBy(env, holder, await this.enter(ctx, p, signal, gone, want));
637
+ e = await seen(await this.enter(ctx, p, signal, gone, want));
617
638
  // a reset seen on the first try still has to be told (it covers the restart)
618
639
  const info = prev.info.filesReset
619
640
  ? { fresh: true, restarted: false, filesReset: true }
@@ -670,6 +691,43 @@ let SandboxService = class SandboxService {
670
691
  }
671
692
  return deviceFilesLost(p.plugin === LOCAL_PROVIDER);
672
693
  }
694
+ /**
695
+ * A silent use ({@link SandboxUseContext.silent}) of `holder`: the seen record is left alone, so
696
+ * the holder's next ordinary use compares against the instance it last saw itself (and learns
697
+ * of a restart or a files reset since); a creation or rebuild this use caused is kept
698
+ * (`capk:sandbox-notice:<env>:<holder>`, merged with an earlier one for the same instance, same
699
+ * TTL as the seen record) for {@link seenBy} to tell. Best effort: a Redis error only logs.
700
+ */
701
+ async deferNotice(deviceId, holder, e) {
702
+ if (!e.info.fresh && !e.info.restarted && e.info.filesReset !== true)
703
+ return e;
704
+ try {
705
+ const ttl = (this.config.get().sandbox.limits.destroyAfterInactiveDays + 1) * 86_400;
706
+ const seen = `${e.createdAt}:${e.fsResets}`;
707
+ const key = noticeKey(deviceId, holder);
708
+ const mine = {
709
+ seen,
710
+ fresh: e.info.fresh,
711
+ restarted: e.info.restarted,
712
+ filesReset: e.info.filesReset === true,
713
+ };
714
+ // swapped in, then merged with an earlier silent use's notice for the same instance
715
+ const prev = parseDeferred(await this.redis.set(key, JSON.stringify(mine), "EX", ttl, "GET"));
716
+ if (prev !== null && prev.seen === seen) {
717
+ const merged = {
718
+ seen,
719
+ fresh: mine.fresh || prev.fresh,
720
+ restarted: mine.restarted || prev.restarted,
721
+ filesReset: mine.filesReset || prev.filesReset,
722
+ };
723
+ await this.redis.set(key, JSON.stringify(merged), "EX", ttl);
724
+ }
725
+ }
726
+ catch (err) {
727
+ this.log.warn("cannot keep the sandbox notice of a silent use", { deviceId, holder, err });
728
+ }
729
+ return e;
730
+ }
673
731
  /**
674
732
  * Records that `holder` uses the instance of `e` (`capk:sandbox-seen:<env>:<holder>` =
675
733
  * `<created_at>:<fs_resets>`, with a TTL of the inactivity destruction plus a day). When the
@@ -679,10 +737,24 @@ let SandboxService = class SandboxService {
679
737
  * (sandbox-docker's volumes are named after the device). Best effort: a Redis error only
680
738
  * logs.
681
739
  */
682
- async seenBy(deviceId, holder, e) {
740
+ async seenBy(deviceId, holder, entered) {
741
+ let e = entered;
683
742
  try {
684
743
  const ttl = (this.config.get().sandbox.limits.destroyAfterInactiveDays + 1) * 86_400;
685
744
  const seen = `${e.createdAt}:${e.fsResets}`;
745
+ // what a silent use of this holder caused on this same instance is told now
746
+ const deferred = parseDeferred(await this.redis.getdel(noticeKey(deviceId, holder)));
747
+ if (deferred !== null && deferred.seen === seen) {
748
+ e = {
749
+ ...e,
750
+ info: e.info.filesReset === true || deferred.filesReset
751
+ ? { fresh: e.info.fresh || deferred.fresh, restarted: false, filesReset: true }
752
+ : {
753
+ fresh: e.info.fresh || deferred.fresh,
754
+ restarted: e.info.restarted || deferred.restarted,
755
+ },
756
+ };
757
+ }
686
758
  const prev = await this.redis.set(`capk:sandbox-seen:${deviceId}:${holder}`, seen, "EX", ttl, "GET");
687
759
  if (prev !== null && prev !== seen) {
688
760
  // `<createdAt>:<fsResets>`: another reset count means the files were reset since; another
@@ -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;