@capybara-hq/kernel 0.1.0-rc.111 → 0.1.0-rc.113

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 (38) hide show
  1. package/dist/automations/errors.js +1 -1
  2. package/dist/automations/events/acceptance.d.ts +7 -2
  3. package/dist/automations/events/acceptance.js +7 -2
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/conversations/conversation-ref.d.ts +58 -0
  6. package/dist/conversations/conversation-ref.js +103 -0
  7. package/dist/conversations/conversations.controller.d.ts +6 -0
  8. package/dist/conversations/conversations.controller.js +23 -6
  9. package/dist/conversations/conversations.service.d.ts +40 -1
  10. package/dist/conversations/conversations.service.js +163 -11
  11. package/dist/conversations/events.d.ts +9 -0
  12. package/dist/conversations/events.js +14 -0
  13. package/dist/conversations/permission-profiles.controller.d.ts +3 -0
  14. package/dist/conversations/permission-profiles.controller.js +3 -0
  15. package/dist/db/kernel-schema.d.ts +11 -0
  16. package/dist/errors.d.ts +8 -0
  17. package/dist/errors.js +8 -0
  18. package/dist/inbox/inbox-items.service.d.ts +5 -3
  19. package/dist/inbox/inbox-items.service.js +12 -4
  20. package/dist/log.d.ts +6 -0
  21. package/dist/log.js +47 -19
  22. package/dist/platform/ops/agent-skills.ops.js +6 -2
  23. package/dist/platform/ops/inbox.ops.js +6 -4
  24. package/dist/push/recipients.js +2 -2
  25. package/dist/push/texts.d.ts +8 -2
  26. package/dist/push/texts.js +4 -1
  27. package/dist/sandbox/review/classifier.js +3 -1
  28. package/dist/skills/invocable.controller.d.ts +4 -0
  29. package/dist/skills/invocable.controller.js +5 -1
  30. package/dist/skills/invoke.d.ts +68 -2
  31. package/dist/skills/invoke.js +128 -13
  32. package/dist/skills/skills.schemas.d.ts +7 -1
  33. package/dist/skills/skills.schemas.js +11 -2
  34. package/dist/themes/render-css.js +9 -2
  35. package/package.json +2 -2
  36. package/src/migrations/0196_conversation_events_compaction_summary_idx.sql +8 -0
  37. package/src/migrations/0197_inbox_item_localized_text.sql +8 -0
  38. package/src/migrations/0198_acceptance_prompt.sql +10 -0
@@ -119,6 +119,70 @@ async function latestProjectRoot(db, conversationId) {
119
119
  .executeTakeFirst();
120
120
  return row?.payload;
121
121
  }
122
+ /** How many of the caller's bound conversations {@link latestKnownProjectRoot} looks through. */
123
+ const KNOWN_SNAPSHOT_CONVERSATIONS = 20;
124
+ /**
125
+ * The last known snapshot of a project (project skills before the first run, design §3.1): the
126
+ * newest usable `project_root` among the caller's own chat conversations bound to the same device,
127
+ * project name and root (each conversation's latest one). What a run of the same person read from
128
+ * that project; the device is never asked. Undefined when none is known.
129
+ */
130
+ export async function latestKnownProjectRoot(db, a) {
131
+ const rows = await db
132
+ .selectFrom("conversations as c")
133
+ .innerJoinLateral((eb) => eb
134
+ .selectFrom("conversation_events as e")
135
+ .select(["e.payload", "e.created_at"])
136
+ .whereRef("e.conversation_id", "=", "c.id")
137
+ .where("e.type", "=", "project_root")
138
+ .orderBy("e.seq", "desc")
139
+ .limit(1)
140
+ .as("p"), (join) => join.onTrue())
141
+ .select("p.payload")
142
+ .where("c.org_id", "=", a.orgId)
143
+ .where("c.account_id", "=", a.accountId)
144
+ .where("c.kind", "=", "chat")
145
+ .where("c.deleted_at", "is", null)
146
+ .where("c.device_id", "=", a.binding.deviceId)
147
+ .where("c.project_name", "=", a.binding.name)
148
+ .where("c.project_path", "=", a.binding.path)
149
+ .orderBy("p.created_at", "desc")
150
+ .limit(KNOWN_SNAPSHOT_CONVERSATIONS)
151
+ .execute();
152
+ return rows.map((r) => r.payload).find((p) => p.unavailable === undefined);
153
+ }
154
+ /**
155
+ * The snapshot a conversation's project skills come from: its own latest `project_root`, or, when
156
+ * its runs never recorded one, the last known snapshot of its binding among its owner's
157
+ * conversations ({@link latestKnownProjectRoot}). `own` says which. Undefined when neither exists.
158
+ */
159
+ export async function projectSnapshotOf(db, a,
160
+ /** The conversation's own latest `project_root` (default: read with `db`). */
161
+ ownLatest = () => latestProjectRoot(db, a.conversationId)) {
162
+ const own = await ownLatest();
163
+ if (own !== undefined)
164
+ return { payload: own, own: true };
165
+ const bound = await bindingOf(db, a);
166
+ if (bound === undefined)
167
+ return undefined;
168
+ const known = await latestKnownProjectRoot(db, { orgId: a.orgId, ...bound });
169
+ return known === undefined ? undefined : { payload: known, own: false };
170
+ }
171
+ /** The conversation's owner and project binding, or undefined for a free conversation. */
172
+ async function bindingOf(db, a) {
173
+ const row = await db
174
+ .selectFrom("conversations")
175
+ .select(["account_id", "device_id", "project_name", "project_path"])
176
+ .where("id", "=", a.conversationId)
177
+ .where("org_id", "=", a.orgId)
178
+ .executeTakeFirst();
179
+ if (!row || row.device_id === null || row.project_name === null || row.project_path === null)
180
+ return undefined;
181
+ return {
182
+ accountId: row.account_id,
183
+ binding: { deviceId: row.device_id, name: row.project_name, path: row.project_path },
184
+ };
185
+ }
122
186
  /**
123
187
  * Whether the skill a queued invocation recorded is still one a person can invoke in this
124
188
  * conversation (phase D Task 9, checked again at dispatch): the same skill (by id) among the
@@ -127,7 +191,8 @@ async function latestProjectRoot(db, conversationId) {
127
191
  */
128
192
  export async function recordedSkillBlocked(db, a) {
129
193
  if (projectSkillOf(a.skillId) !== undefined) {
130
- return projectSkillBlocked(await latestProjectRoot(db, a.conversationId), a.skillId);
194
+ const snapshot = await projectSnapshotOf(db, a);
195
+ return projectSkillBlocked(snapshot?.payload, a.skillId);
131
196
  }
132
197
  const found = (await resolveSkills(db, a)).find((r) => r.skill.id === a.skillId);
133
198
  if (!found)
@@ -144,7 +209,12 @@ export const forkLeadText = (name, agentType, args) => escapeSkillInvocationTags
144
209
  * `project:<name>` with its `Skill` tool, which reads it under the run's admission. Model-visible,
145
210
  * so English; tags in the arguments stay inert. Always inline, as before.
146
211
  */
147
- export function projectSkillStub(a, latest, bare) {
212
+ export function projectSkillStub(a, latest, bare,
213
+ /**
214
+ * Where `latest` comes from: `run`, this conversation's run start; `known`, the last known
215
+ * snapshot of the project from another conversation (no run of this one read it yet).
216
+ */
217
+ from = "run") {
148
218
  const skill = latest.skills.find((s) => s.name === bare);
149
219
  if (skill === undefined)
150
220
  throw notInvocable("not_found", a.name);
@@ -161,7 +231,7 @@ export function projectSkillStub(a, latest, bare) {
161
231
  const dir = `${root === "/" ? "" : root}/${PROJECT_SKILLS_DIR}/${bare}`;
162
232
  const text = escapeSkillInvocationTags([
163
233
  `The user invoked the project skill "${a.name}" with /${a.name}${args === "" ? "" : ` ${args}`}.`,
164
- `Its instructions are not included in this message: call ${BUILTIN.Skill} with the name "${a.name}" to load them from the project (its directory is ${dir}; the SKILL.md recorded at the run start has the digest ${skill.digest}), then follow them${args === "" ? "." : " with the user's arguments:"}`,
234
+ `Its instructions are not included in this message: call ${BUILTIN.Skill} with the name "${a.name}" to load them from the project (its directory is ${dir}; the SKILL.md ${from === "run" ? "recorded at the run start" : "last recorded for this project"} has the digest ${skill.digest}), then follow them${args === "" ? "." : " with the user's arguments:"}`,
165
235
  ...(args === "" ? [] : [args]),
166
236
  ].join("\n\n"));
167
237
  return {
@@ -204,7 +274,12 @@ let SkillInvoker = class SkillInvoker {
204
274
  * then its trial drafts apply, and its latest usable `project_root` adds the project's skills
205
275
  * after the agent's ({@link projectInvocables}).
206
276
  */
207
- async listFor(orgId, agentId, accountId, conversationId) {
277
+ async listFor(orgId, agentId, accountId, conversationId,
278
+ /**
279
+ * Without `conversationId`: the new conversation's picked device project (design §3.2), whose
280
+ * last known snapshot adds the project's skills.
281
+ */
282
+ pick) {
208
283
  const agent = await this.agents.get(orgId, agentId, accountId);
209
284
  if (conversationId !== undefined) {
210
285
  const row = await this.db
@@ -225,13 +300,34 @@ let SkillInvoker = class SkillInvoker {
225
300
  agent: agent.definition,
226
301
  ...(conversationId !== undefined && { conversationId }),
227
302
  });
228
- if (conversationId === undefined)
229
- return skills;
230
303
  // a project skill is loaded by the agent's Skill tool: none without it
231
304
  if (!hasBuiltin(agent.definition, BUILTIN.Skill))
232
305
  return skills;
233
- const latest = await this.eventLog.latestOfType(conversationId, "project_root");
234
- return [...skills, ...projectInvocables(latest?.payload)];
306
+ if (conversationId !== undefined) {
307
+ const snapshot = await this.conversationSnapshot(orgId, conversationId);
308
+ return [...skills, ...projectInvocables(snapshot?.payload)];
309
+ }
310
+ if (pick === undefined)
311
+ return skills;
312
+ const binding = await this.pickedBinding(pick.deviceId, pick.project);
313
+ if (binding === undefined)
314
+ return skills;
315
+ const known = await latestKnownProjectRoot(this.db.db, { orgId, accountId, binding });
316
+ return [...skills, ...projectInvocables(known)];
317
+ }
318
+ /**
319
+ * The device project a new conversation picked, by device and name, or undefined when the device
320
+ * has no project of that name. Only its last known snapshot among the caller's own conversations
321
+ * is used, so nothing of someone else's device can be read through it.
322
+ */
323
+ async pickedBinding(deviceId, name) {
324
+ const row = await this.db.db
325
+ .selectFrom("device_projects")
326
+ .select("path")
327
+ .where("device_id", "=", deviceId)
328
+ .where("name", "=", name)
329
+ .executeTakeFirst();
330
+ return row === undefined ? undefined : { deviceId, name, path: row.path };
235
331
  }
236
332
  /**
237
333
  * The agent's effective skills a person can invoke (`user` not false), sorted by name (code
@@ -333,10 +429,8 @@ let SkillInvoker = class SkillInvoker {
333
429
  * the `Skill` tool.
334
430
  */
335
431
  async prepareProject(a, bare) {
336
- const { conversationId } = a;
337
- if (conversationId === undefined)
338
- throw notInvocable("not_found", a.name);
339
- const latest = (await this.eventLog.latestOfType(conversationId, "project_root"))?.payload;
432
+ const snapshot = await this.projectSnapshot(a);
433
+ const latest = snapshot?.payload;
340
434
  if (latest?.unavailable !== undefined) {
341
435
  throw projectUnavailable(latest.unavailable.reason, `Skill "${a.name}" cannot be invoked: the project "${latest.project}" is not available (${latest.unavailable.message})`);
342
436
  }
@@ -346,7 +440,28 @@ let SkillInvoker = class SkillInvoker {
346
440
  // no device read at send time: the agent loads the skill with Skill
347
441
  if (!hasBuiltin(a.agent, BUILTIN.Skill))
348
442
  throw projectUnavailable("skill_tool_off", `Skill "${a.name}" cannot be invoked: this agent cannot load project skills; turn on its ${BUILTIN.Skill} tool`);
349
- return projectSkillStub(a, latest, bare);
443
+ return projectSkillStub(a, latest, bare, snapshot?.own === false ? "known" : "run");
444
+ }
445
+ /** {@link projectSnapshotOf}, the conversation's own latest read through the event log. */
446
+ conversationSnapshot(orgId, conversationId) {
447
+ return projectSnapshotOf(this.db.db, { orgId, conversationId }, async () => (await this.eventLog.latestOfType(conversationId, "project_root"))?.payload);
448
+ }
449
+ /**
450
+ * Where a send's project skill is rendered from (design §3.3): the conversation's own latest
451
+ * `project_root`, else the last known snapshot of its binding; for a conversation not created
452
+ * yet, the last known snapshot of the project it is created bound to.
453
+ */
454
+ async projectSnapshot(a) {
455
+ if (a.conversationId !== undefined)
456
+ return this.conversationSnapshot(a.orgId, a.conversationId);
457
+ if (a.project === undefined || a.deviceId === undefined || a.deviceId === null)
458
+ return undefined;
459
+ const known = await latestKnownProjectRoot(this.db.db, {
460
+ orgId: a.orgId,
461
+ accountId: a.accountId,
462
+ binding: { deviceId: a.deviceId, ...a.project },
463
+ });
464
+ return known === undefined ? undefined : { payload: known, own: false };
350
465
  }
351
466
  /**
352
467
  * The task of a fork invocation's sub-agent (spec §6.2), rendered at dispatch from the version
@@ -89,8 +89,14 @@ export declare const AgentSkillUploadBody: z.ZodObject<{
89
89
  export declare const AgentSkillRegisterBody: z.ZodObject<{
90
90
  uploadId: z.ZodString;
91
91
  }, z.core.$strict>;
92
- /** `?conversationId=` of `GET /agents/:agentId/invocable-skills`. */
92
+ /**
93
+ * `?conversationId=` of `GET /agents/:agentId/invocable-skills`; without it, `deviceId` and
94
+ * `project` name a new conversation's picked device project, whose last known snapshot lists the
95
+ * project's skills (project skills before the first run, design §3.2).
96
+ */
93
97
  export declare const InvocableSkillsQuerySchema: z.ZodObject<{
94
98
  conversationId: z.ZodOptional<z.ZodString>;
99
+ deviceId: z.ZodOptional<z.ZodString>;
100
+ project: z.ZodOptional<z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>;
95
101
  }, z.core.$strict>;
96
102
  export declare const SKILL_ROUTES: readonly RouteSchemas[];
@@ -2,6 +2,7 @@ import { hasControlChars, MEDIA_NAME_MAX_CHARS, SKILL_LIMITS } from "@capybara-h
2
2
  import { z } from "zod";
3
3
  import { SKILL_PACKAGE_UPLOAD_MAX_BYTES } from "../conversations/attachments.service.js";
4
4
  import { DOWNLOAD_AS } from "../conversations/conversations.schemas.js";
5
+ import { DeviceProjectName } from "../devices/dto.js";
5
6
  /** `POST /skills/uploads`: registers a skill package upload (a presigned form). */
6
7
  export const SkillUploadBody = z
7
8
  .object({
@@ -87,9 +88,17 @@ export const AgentSkillUploadBody = z
87
88
  .strict();
88
89
  /** `POST /agents/:agentId/skills`: an uploaded package registered as one of the agent's skills. */
89
90
  export const AgentSkillRegisterBody = z.object({ uploadId: z.string().min(1).max(100) }).strict();
90
- /** `?conversationId=` of `GET /agents/:agentId/invocable-skills`. */
91
+ /**
92
+ * `?conversationId=` of `GET /agents/:agentId/invocable-skills`; without it, `deviceId` and
93
+ * `project` name a new conversation's picked device project, whose last known snapshot lists the
94
+ * project's skills (project skills before the first run, design §3.2).
95
+ */
91
96
  export const InvocableSkillsQuerySchema = z
92
- .object({ conversationId: z.string().min(1).max(100).optional() })
97
+ .object({
98
+ conversationId: z.string().min(1).max(100).optional(),
99
+ deviceId: z.string().min(1).max(100).optional(),
100
+ project: DeviceProjectName.optional(),
101
+ })
93
102
  .strict();
94
103
  export const SKILL_ROUTES = [
95
104
  { route: "GET /api/v1/orgs/:orgId/skill-changes/:id", params: SkillChangePathParams },
@@ -2,7 +2,7 @@
2
2
  // definition was validated at import, but it is read back from a database row: every value is
3
3
  // checked again here with the SDK's grammars before it is written into CSS, so a changed row cannot
4
4
  // inject CSS. A value that fails is left out and reported.
5
- import { canonicalThemeValue, isThemeAssetPath, isThemeFontFamily, THEME_FONTS, THEME_OVERRIDABLE, THEME_TOKENS, } from "@capybara-hq/plugin-sdk";
5
+ import { canonicalThemeValue, isThemeAssetPath, isThemeFontFamily, THEME_FONTS, THEME_OVERRIDABLE, THEME_TOKENS, themeSchemeFallbacks, } from "@capybara-hq/plugin-sdk";
6
6
  const SCHEMES = ["dark", "light"];
7
7
  const GROUPS = ["color", "shadow"];
8
8
  const OVERRIDABLE = {
@@ -36,6 +36,7 @@ function schemeDeclarations(theme, scheme, full, skip) {
36
36
  const over = theme.schemes?.[scheme];
37
37
  if (!isRecord(over))
38
38
  return out;
39
+ const colors = new Set();
39
40
  for (const g of GROUPS) {
40
41
  const values = over[g];
41
42
  if (!isRecord(values))
@@ -44,10 +45,16 @@ function schemeDeclarations(theme, scheme, full, skip) {
44
45
  const v = OVERRIDABLE[g].has(n) ? canonicalThemeValue(g, raw) : undefined;
45
46
  if (v === undefined)
46
47
  skip(`schemes.${scheme}.${g}.${n}`);
47
- else
48
+ else {
48
49
  out.set(VARIABLE[g](n), v);
50
+ if (g === "color")
51
+ colors.add(n);
52
+ }
49
53
  }
50
54
  }
55
+ // A token the built-in palette fills only for itself (the SDK names them)
56
+ for (const [n, v] of Object.entries(themeSchemeFallbacks(colors)))
57
+ out.set(VARIABLE.color(n), v);
51
58
  const radius = over.radius;
52
59
  if (isRecord(radius)) {
53
60
  for (const [n, raw] of Object.entries(radius)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.111",
3
+ "version": "0.1.0-rc.113",
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.88"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.89"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -0,0 +1,8 @@
1
+ -- @ conversations (spec §1): a message referencing another conversation reads that conversation's
2
+ -- latest `compaction_summary` at send time, as do skill loads (`invokedInContext`); a summary is
3
+ -- written rarely, so without this partial index the lookup scans the conversation's events
4
+ -- backwards. `conversation_events` has no `org_id`, so no RLS policy. Not CONCURRENTLY, like the
5
+ -- other index migrations (0025, 0094, 0133).
6
+ CREATE INDEX IF NOT EXISTS conversation_events_compaction_summary_idx
7
+ ON conversation_events (conversation_id, seq)
8
+ WHERE type = 'compaction_summary';
@@ -0,0 +1,8 @@
1
+ -- Localized inbox item texts: `ctx.inbox.post` takes a title and a body as a single string or as
2
+ -- `{ zh, en }` (like its action labels). A bilingual text is kept as given in `title_localized` /
3
+ -- `body_localized`, and `title` / `body` keep its English text, so every reader of the single
4
+ -- string (the Platform tool's English rows, a replica still on the previous version) reads one.
5
+ -- Null: the post gave a single string (or no body).
6
+
7
+ ALTER TABLE inbox_items ADD COLUMN IF NOT EXISTS title_localized jsonb;
8
+ ALTER TABLE inbox_items ADD COLUMN IF NOT EXISTS body_localized jsonb;
@@ -0,0 +1,10 @@
1
+ -- The acceptance automation's prompt states the mechanism for any directed event (an assignment,
2
+ -- an unassignment, an answer, ...), not "this work was assigned to you". Acceptance automations
3
+ -- that still carry the old kernel text, unedited, get the new one; a prompt the person edited stays
4
+ -- as it is. Past fires keep the text their messages recorded (the event log is never rewritten).
5
+
6
+ UPDATE automations
7
+ SET prompt = 'The events above were directed to you and your agent by their source; your acceptance rule for that source delivers them to this automation. Each one names its type, its subject and the source''s own summary of what happened. Decide from them what, if anything, is now expected of you: do it within what you are allowed to do and report what you did, or say why nothing needs doing.',
8
+ updated_at = now()
9
+ WHERE origin = 'acceptance'
10
+ AND prompt = 'This work was assigned to you. Read the assigned item, do what it asks within what you are allowed to do, and report what you did.';