@capybara-hq/kernel 0.1.0-rc.95 → 0.1.0-rc.96

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.
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.77";
211
+ readonly sdk: "0.1.0-rc.78";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -284,7 +284,7 @@ let ConversationsService = class ConversationsService {
284
284
  const deviceId = await this.devices.forNew(orgId, accountId, pick);
285
285
  const next = await this.planSwitch(orgId, agent.definition, NO_SELECTION, input);
286
286
  const extra = await this.resolveExtra(orgId, accountId, input);
287
- const invoked = await this.prepareSkill(orgId, accountId, agentId, undefined, agent.definition, input);
287
+ const invoked = await this.prepareSkill(orgId, accountId, agentId, { conversationId: undefined, deviceId }, agent.definition, input);
288
288
  const id = randomUUID();
289
289
  let all;
290
290
  try {
@@ -946,7 +946,7 @@ let ConversationsService = class ConversationsService {
946
946
  const extra = await this.resolveExtra(orgId, accountId, input);
947
947
  const invoked = agent === undefined
948
948
  ? undefined
949
- : await this.prepareSkill(orgId, accountId, conv.agentId, conversationId, agent, input);
949
+ : await this.prepareSkill(orgId, accountId, conv.agentId, { conversationId, deviceId: conv.deviceId }, agent, input);
950
950
  // one transaction: the sender, time zone and language are read with the message's write
951
951
  // (run context spec §3.2)
952
952
  let current = conv.selection;
@@ -1159,14 +1159,18 @@ let ConversationsService = class ConversationsService {
1159
1159
  * Renders the message's skill invocation (phase D), or undefined when it has none. Resolved
1160
1160
  * against the agent's current version and, for an existing conversation, its trial drafts.
1161
1161
  */
1162
- async prepareSkill(orgId, accountId, agentId, conversationId, agent, input) {
1162
+ async prepareSkill(orgId, accountId, agentId,
1163
+ /** The conversation (absent before it is created) and its device (its skills root). */
1164
+ where, agent, input) {
1163
1165
  if (input.skill === undefined)
1164
1166
  return undefined;
1167
+ const { conversationId, deviceId } = where;
1165
1168
  return this.invoker.prepare({
1166
1169
  orgId,
1167
1170
  agentId,
1168
1171
  accountId,
1169
1172
  ...(conversationId !== undefined && { conversationId }),
1173
+ deviceId,
1170
1174
  agent,
1171
1175
  name: input.skill.name,
1172
1176
  args: input.text,
@@ -1181,7 +1185,7 @@ let ConversationsService = class ConversationsService {
1181
1185
  if (input.skill === undefined)
1182
1186
  return undefined;
1183
1187
  const agent = await this.agents.get(orgId, conv.agentId, accountId);
1184
- return this.prepareSkill(orgId, accountId, conv.agentId, conv.id, agent.definition, input);
1188
+ return this.prepareSkill(orgId, accountId, conv.agentId, { conversationId: conv.id, deviceId: conv.deviceId }, agent.definition, input);
1185
1189
  }
1186
1190
  /**
1187
1191
  * Reads the `@` resources with the sender's credentials (nothing when there are none). Shared
@@ -106,6 +106,7 @@ export async function advanceSkillForks(d, a) {
106
106
  rendered = await d.invoker.renderTask({
107
107
  orgId: ctx.orgId,
108
108
  conversationId: ctx.conversationId,
109
+ deviceConversationId: ctx.parent?.rootConversationId ?? ctx.conversationId,
109
110
  skill,
110
111
  });
111
112
  }
@@ -46,6 +46,7 @@ export async function templateSkillMessages(d, a) {
46
46
  const { task } = await d.invoker.renderTask({
47
47
  orgId: a.ctx.orgId,
48
48
  conversationId: a.ctx.conversationId,
49
+ deviceConversationId: a.ctx.parent?.rootConversationId ?? a.ctx.conversationId,
49
50
  skill: record,
50
51
  });
51
52
  text = `${templateSkillLeadText(s.name)}\n\n${task(a.child)}`;
@@ -1,4 +1,4 @@
1
- import { type SandboxExecutionRef } from "@capybara-hq/plugin-sdk";
1
+ import { type SandboxExecutionRef, type ToolErrorKind } from "@capybara-hq/plugin-sdk";
2
2
  import type { Selectable } from "kysely";
3
3
  import type { SandboxOperationIntentsTable } from "../db/kernel-schema.js";
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -63,14 +63,18 @@ export declare function operationIdFor(i: Pick<OperationInvocation, "callId" | "
63
63
  claim: Pick<ExecutionClaim, "runId">;
64
64
  }): string;
65
65
  /**
66
- * A definite pre-effect failure recorded as an operation's result: `denied` and `unsupported`
67
- * refusals, and `not_sent` (the request was refused before it was sent, its connection changed:
68
- * `DeviceRequestNotSentError`), which is never an unknown outcome either.
66
+ * A definite failure recorded as an operation's result: `denied` and `unsupported` refusals,
67
+ * `not_sent` (the request was refused before it was sent, its connection changed:
68
+ * `DeviceRequestNotSentError`), which is never an unknown outcome either, and `failed`: the
69
+ * provider's own typed answer that the operation finished and failed (a `ToolError`, #903),
70
+ * replayed as that `ToolError` with its `toolKind`.
69
71
  */
70
- export type OperationFailureKind = "denied" | "unsupported" | "not_sent";
72
+ export type OperationFailureKind = "denied" | "unsupported" | "not_sent" | "failed";
71
73
  export interface OperationFailure {
72
74
  kind: OperationFailureKind;
73
75
  message: string;
76
+ /** The answered `ToolError`'s kind (`failed` only). */
77
+ toolKind?: ToolErrorKind;
74
78
  }
75
79
  /**
76
80
  * Why a managed background start was refused, as `background_tasks.lost_reason` keeps it after
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHash, randomUUID } from "node:crypto";
11
- import { parseSandboxExecutionRef, parseSandboxOperationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
11
+ import { parseSandboxExecutionRef, parseSandboxOperationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, ToolError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { STOP_CLAIM_TTL_MS } from "../background/store.js";
@@ -62,6 +62,8 @@ export function launchRefusedText(kind) {
62
62
  return "the command or its output file is outside what this conversation may use on the device; choose a working directory this conversation may write to";
63
63
  case "unsupported":
64
64
  return "the device refused it because it cannot enforce its sandbox limits; ask the device's owner to update its device program (or a super admin to update its device plugin), or continue without the device";
65
+ case "failed":
66
+ return "the device answered that the start failed; check the command and its working directory, then retry the call";
65
67
  default:
66
68
  return "the device refused the start; check that the device is connected, then retry the call";
67
69
  }
@@ -77,6 +79,8 @@ export function operationResult(value) {
77
79
  throw new DeviceRequestNotSentError(f.message);
78
80
  if (f.kind === "unsupported")
79
81
  throw new SandboxPermissionUnsupportedError(f.message);
82
+ if (f.kind === "failed")
83
+ throw new ToolError(f.message, { kind: f.toolKind ?? "error" });
80
84
  }
81
85
  return hydrateOperationBytes(value);
82
86
  }
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { posix } from "node:path";
11
- import { DeviceAccessError, isDeviceOfflineError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceAccessError, isDeviceOfflineError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, ToolError, } from "@capybara-hq/plugin-sdk";
12
12
  import { asPlatform } from "../infra/database/org-scope.js";
13
13
  import { runOutsideTransaction } from "../infra/database/transaction-host.js";
14
14
  import { createHeldOperations, withKernelGeneration, } from "./held-operations.js";
@@ -25,6 +25,17 @@ const failureKindOf = (error) => isDeviceRequestNotSent(error)
25
25
  : isSandboxScopeDeniedError(error)
26
26
  ? "denied"
27
27
  : "unsupported";
28
+ /** Native methods without effects: rerunning one is harmless, so its answer never stays unknown. */
29
+ const READ_ONLY_METHODS = new Set(["readFile", "stat", "list", "scan"]);
30
+ /**
31
+ * The provider's own typed answer that the operation finished and failed (#903): a `ToolError`.
32
+ * A read's answer is definite whatever its kind. An effectful operation's is definite only when
33
+ * the remote answered (`error`, not `unavailable`: a transport loss or timeout proves nothing)
34
+ * and only on a fresh dispatch: an answer to a reconciliation may describe the earlier dispatch's
35
+ * effect (a file it already wrote), so the recorded operation stays unknown.
36
+ */
37
+ const definiteFailureAnswer = (error, method, reconciling) => error instanceof ToolError &&
38
+ (READ_ONLY_METHODS.has(method) || (error.kind !== "unavailable" && !reconciling));
28
39
  /**
29
40
  * A provider found the instance gone before it sent the request (#643): a
30
41
  * `DeviceRequestNotSentError` whose `cause` is a `SandboxGoneError`. Nothing ran, so the operation
@@ -1402,6 +1413,12 @@ let SandboxService = class SandboxService {
1402
1413
  }));
1403
1414
  throw error;
1404
1415
  }
1416
+ if (definiteFailureAnswer(error, method, reconciling)) {
1417
+ await runOutsideTransaction(() => this.operationIntents.complete(admitted.operation_id, identity.claim.executionId, {
1418
+ $failure: { kind: "failed", message: error.message, toolKind: error.kind },
1419
+ }));
1420
+ throw error;
1421
+ }
1405
1422
  await runOutsideTransaction(() => this.operationIntents.unknown(admitted.operation_id, admitted.execution_id));
1406
1423
  // The machine's files are gone (R24): the operation stays unknown, and the caller still
1407
1424
  // records the files lost so later calls fail without reaching the machine.
@@ -41,6 +41,15 @@ export interface InvocableSkill {
41
41
  /** Runs as a sub-agent when a person invokes it. */
42
42
  fork: boolean;
43
43
  }
44
+ /**
45
+ * The skills root of device `deviceId` as last known (#904): its instance's handle
46
+ * (`rootsOf`, e.g. a connected machine's `<home>/<device>/skills`), else `/skills`. Read from the
47
+ * database only: no device call, no binding. An invocation renders `${CLAUDE_SKILL_DIR}` and its
48
+ * files line under it, so the path the model reads is the one `Skill` copies the files to.
49
+ */
50
+ export declare function knownSkillsRoot(db: KernelSchemaDb, orgId: string, deviceId: string | null | undefined): Promise<string>;
51
+ /** {@link knownSkillsRoot} of the device conversation `conversationId` is bound to. */
52
+ export declare function conversationSkillsRoot(db: KernelSchemaDb, orgId: string, conversationId: string): Promise<string>;
44
53
  /** The `skill` field of a `user_message`. */
45
54
  export type InvocationRecord = NonNullable<EventPayload<"user_message">["skill"]>;
46
55
  /** The result of {@link SkillInvoker.prepare}. */
@@ -160,6 +169,11 @@ export declare class SkillInvoker {
160
169
  accountId: string;
161
170
  /** Absent for the first message of a conversation not created yet. */
162
171
  conversationId?: string;
172
+ /**
173
+ * The conversation's device (the one a new conversation is created with); its skills root
174
+ * names the skill's directory ({@link knownSkillsRoot}). Null or absent: `/skills`.
175
+ */
176
+ deviceId?: string | null;
163
177
  agent: AgentDefinition;
164
178
  name: string;
165
179
  args: string;
@@ -189,6 +203,11 @@ export declare class SkillInvoker {
189
203
  renderTask(a: {
190
204
  orgId: string;
191
205
  conversationId: string;
206
+ /**
207
+ * The root conversation of the tree, whose device the sub-agent uses (its skills root names
208
+ * the skill's directory, {@link conversationSkillsRoot}). Default `conversationId`.
209
+ */
210
+ deviceConversationId?: string;
192
211
  skill: InvocationRecord;
193
212
  }): Promise<{
194
213
  task: (child: Pick<AgentDefinition, "disabledTools" | "subagentTools">) => string;
@@ -7,7 +7,7 @@ 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, rootsOf, SKILL_ENTRY_FILE, SKILL_INVOCATION_LIMITS, SKILLS_SANDBOX_ROOT, skillDigest, } 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";
@@ -23,6 +23,34 @@ import { BUILTIN } from "../tools/builtin-names.js";
23
23
  import { findSkillVersion, readSkillFile, SkillIntegrityError, } from "../tools/builtins/skill-load.js";
24
24
  import { invocationOf, resolveSkills } from "./catalog.js";
25
25
  import { skillFileStore } from "./usable.js";
26
+ /**
27
+ * The skills root of device `deviceId` as last known (#904): its instance's handle
28
+ * (`rootsOf`, e.g. a connected machine's `<home>/<device>/skills`), else `/skills`. Read from the
29
+ * database only: no device call, no binding. An invocation renders `${CLAUDE_SKILL_DIR}` and its
30
+ * files line under it, so the path the model reads is the one `Skill` copies the files to.
31
+ */
32
+ export async function knownSkillsRoot(db, orgId, deviceId) {
33
+ if (deviceId === null || deviceId === undefined)
34
+ return SKILLS_SANDBOX_ROOT;
35
+ const row = await db
36
+ .selectFrom("device_instances")
37
+ .select("handle")
38
+ .where("device_id", "=", deviceId)
39
+ .where("org_id", "=", orgId)
40
+ .executeTakeFirst();
41
+ const handle = row?.handle;
42
+ return handle ? rootsOf(handle).skills : SKILLS_SANDBOX_ROOT;
43
+ }
44
+ /** {@link knownSkillsRoot} of the device conversation `conversationId` is bound to. */
45
+ export async function conversationSkillsRoot(db, orgId, conversationId) {
46
+ const conv = await db
47
+ .selectFrom("conversations")
48
+ .select("device_id")
49
+ .where("id", "=", conversationId)
50
+ .where("org_id", "=", orgId)
51
+ .executeTakeFirst();
52
+ return knownSkillsRoot(db, orgId, conv?.device_id);
53
+ }
26
54
  /** A leading `/<name>` or `/<plugin>:<name>`, then whitespace or the end (spec §3.2). */
27
55
  const SLASH_COMMAND_RE = /^\/([a-z0-9-]+(?::[a-z0-9-]+)?)(?:\s|$)/;
28
56
  /** `/name args` at the very start of a message, or null (`/etc/hosts`, ` /x`, `/Upper`). */
@@ -267,6 +295,7 @@ let SkillInvoker = class SkillInvoker {
267
295
  invocation: inv,
268
296
  args: a.args,
269
297
  lines,
298
+ skillsRoot: await knownSkillsRoot(this.db.db, a.orgId, a.deviceId),
270
299
  };
271
300
  // a SKILL.md whose body alone renders over the limit can never be invoked: say so, rather than
272
301
  // "shorten the arguments"
@@ -352,6 +381,7 @@ let SkillInvoker = class SkillInvoker {
352
381
  });
353
382
  const inv = invocationOf(found.manifest);
354
383
  const others = found.manifest.files.some((f) => f.path !== SKILL_ENTRY_FILE);
384
+ const skillsRoot = await conversationSkillsRoot(this.db.db, a.orgId, a.deviceConversationId ?? a.conversationId);
355
385
  const task = (child) => renderSkillInvocation({
356
386
  name: skill.name,
357
387
  skillName: skill.name,
@@ -366,6 +396,7 @@ let SkillInvoker = class SkillInvoker {
366
396
  hasBuiltin(child, BUILTIN.Bash) && { shellHint: true }),
367
397
  },
368
398
  lead: false,
399
+ skillsRoot,
369
400
  });
370
401
  const asked = inv.fork?.agent;
371
402
  const unknown = asked !== undefined && !isGeneralAlias(asked) && skill.agentType === "general-purpose";
@@ -351,12 +351,19 @@ function launchRefusedWhy(e) {
351
351
  ? "denied"
352
352
  : isSandboxPermissionUnsupportedError(e)
353
353
  ? "unsupported"
354
- : undefined),
354
+ : e instanceof ToolError
355
+ ? "failed"
356
+ : undefined),
355
357
  };
356
358
  }
357
- /** A typed refusal: the provider or admission proved the start had no effect. */
359
+ /**
360
+ * A typed refusal: the provider or admission proved the start had no effect, or the provider
361
+ * answered that it failed (a `ToolError`, recorded as a definite failure: #903).
362
+ */
358
363
  const isRefusal = (e) => !isSandboxOperationOutcomeUnknownError(e) &&
359
- (isSandboxScopeDeniedError(e) || isSandboxPermissionUnsupportedError(e));
364
+ (isSandboxScopeDeniedError(e) ||
365
+ isSandboxPermissionUnsupportedError(e) ||
366
+ e instanceof ToolError);
360
367
  /**
361
368
  * Sandbox-specific signals in a command's output: the EPERM a Seatbelt or Landlock write denial
362
369
  * gives, the read-only bind of the Linux sandbox and Seatbelt's own deny report.
@@ -375,6 +375,49 @@ async function invokedEntry(db, ctx, name) {
375
375
  conversationId: scope.conversationId,
376
376
  };
377
377
  }
378
+ /**
379
+ * Whether the caller's context already holds this version's instructions from an inline
380
+ * invocation (#904): a `user_message` of the caller's log whose `skill` record is this id, source
381
+ * and version in `inline` mode (a person's `/name`, or a template skill at a sub-agent's start),
382
+ * with the same arguments (absent `args` count as the same), that the latest compaction summary
383
+ * does not cover or re-renders as an opening message. `Skill` then copies the files and names
384
+ * their directory without repeating the instructions. Read from the log, so a replay agrees.
385
+ */
386
+ async function invokedInContext(db, conversationId, entry, args) {
387
+ // only the `skill` field: a message's content holds the rendered skill (up to 200k characters)
388
+ const rows = await db
389
+ .selectFrom("conversation_events")
390
+ .select(["seq", sql `payload -> 'skill'`.as("skill")])
391
+ .where("conversation_id", "=", conversationId)
392
+ .where("type", "=", "user_message")
393
+ .where(sql `payload -> 'skill' IS NOT NULL`)
394
+ .execute();
395
+ const seqs = rows.flatMap((r) => {
396
+ const k = r.skill;
397
+ const same = k.mode === "inline" &&
398
+ k.id === entry.id &&
399
+ k.source === entry.source &&
400
+ k.version === entry.version &&
401
+ (args === undefined || args.trim() === k.arguments);
402
+ return same ? [Number(r.seq)] : [];
403
+ });
404
+ if (seqs.length === 0)
405
+ return false;
406
+ const summary = await db
407
+ .selectFrom("conversation_events")
408
+ .select(sql `payload`.as("payload"))
409
+ .where("conversation_id", "=", conversationId)
410
+ .where("type", "=", "compaction_summary")
411
+ .orderBy("seq", "desc")
412
+ .limit(1)
413
+ .executeTakeFirst();
414
+ if (!summary)
415
+ return true;
416
+ const { coversUpToSeq, openingSeqs = [] } = summary.payload;
417
+ return seqs.some((seq) => seq > coversUpToSeq || openingSeqs.includes(seq));
418
+ }
419
+ /** The `Skill` line in place of instructions an inline invocation already gave (#904). */
420
+ const invokedInstructionsText = (name, dir) => `Its instructions are in the invocation of "${name}" above and are not repeated here; in them, \${CLAUDE_SKILL_DIR} is ${dir}.`;
378
421
  /**
379
422
  * The line before a forked skill's instructions (spec §4.4): run it through `Agent` when this step
380
423
  * offers the tool and the skill's type is in the agent's roster, else follow it yourself.
@@ -650,6 +693,17 @@ export function skillLoadTool(deps) {
650
693
  }
651
694
  const invocation = invocationOf(manifest);
652
695
  const fork = invocation.fork;
696
+ if (await invokedInContext(deps.db, ctx.conversationId, entry, args)) {
697
+ const text = [
698
+ `Loaded skill "${name}" (version ${entry.version}).`,
699
+ filesText,
700
+ invokedInstructionsText(name, skillSandboxDir(name, digest, skillsRoot)),
701
+ ].join("\n\n");
702
+ return {
703
+ content: [{ type: "text", text: withNotices(notices, text) }],
704
+ display: display(`加载技能 ${name}(版本 ${entry.version})`, `Loaded skill ${name} (version ${entry.version})`),
705
+ };
706
+ }
653
707
  let instructions;
654
708
  try {
655
709
  instructions = renderSkillBody(parsed.body.trim(), invocation, args ?? "", name, digest, skillsRoot);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.95",
3
+ "version": "0.1.0-rc.96",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.77"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.78"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",