@capybara-hq/kernel 0.1.0-rc.112 → 0.1.0-rc.114

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 (72) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/actions.js +2 -0
  3. package/dist/channels/cards.d.ts +4 -3
  4. package/dist/channels/cards.js +18 -3
  5. package/dist/channels/phrases.d.ts +15 -0
  6. package/dist/channels/phrases.js +9 -0
  7. package/dist/conversations/conversations.service.js +19 -5
  8. package/dist/conversations/events.d.ts +13 -0
  9. package/dist/conversations/events.js +24 -3
  10. package/dist/ctx/create-ctx.d.ts +1 -1
  11. package/dist/ctx/create-ctx.js +6 -1
  12. package/dist/db/kernel-schema.d.ts +26 -0
  13. package/dist/device-access/device-access.service.d.ts +74 -3
  14. package/dist/device-access/device-access.service.js +221 -7
  15. package/dist/devices/devices.service.js +3 -0
  16. package/dist/errors.d.ts +6 -0
  17. package/dist/errors.js +6 -0
  18. package/dist/extensions/permission-set.d.ts +11 -1
  19. package/dist/extensions/permission-set.js +15 -1
  20. package/dist/extensions/permission-view.d.ts +3 -2
  21. package/dist/extensions/permission-view.js +15 -2
  22. package/dist/infra/outbox/registry.d.ts +14 -0
  23. package/dist/infra/outbox/registry.js +14 -0
  24. package/dist/orgs/offboarding.js +5 -1
  25. package/dist/platform/ops/agent-skills.ops.js +6 -2
  26. package/dist/roles/worker.module.js +3 -0
  27. package/dist/runtime/maintenance.d.ts +4 -2
  28. package/dist/runtime/maintenance.js +14 -4
  29. package/dist/sandbox/device-sandbox.d.ts +12 -0
  30. package/dist/sandbox/device-sandbox.js +2 -0
  31. package/dist/sandbox/device-services.d.ts +42 -2
  32. package/dist/sandbox/device-services.js +74 -14
  33. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  34. package/dist/sandbox/loopback-expiry.job.js +50 -0
  35. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  36. package/dist/sandbox/loopback-grant-records.js +239 -0
  37. package/dist/sandbox/loopback-grants.d.ts +119 -0
  38. package/dist/sandbox/loopback-grants.js +454 -0
  39. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  40. package/dist/sandbox/loopback-live-ports.js +43 -0
  41. package/dist/sandbox/permission-call-types.d.ts +3 -2
  42. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  43. package/dist/sandbox/permission-facts.d.ts +4 -0
  44. package/dist/sandbox/permission-facts.js +4 -0
  45. package/dist/sandbox/review/classifier.d.ts +26 -4
  46. package/dist/sandbox/review/classifier.js +31 -4
  47. package/dist/sandbox/review/index.d.ts +3 -3
  48. package/dist/sandbox/review/index.js +2 -2
  49. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  50. package/dist/sandbox/review/permission-candidate.js +6 -5
  51. package/dist/sandbox/review/review.service.d.ts +69 -0
  52. package/dist/sandbox/review/review.service.js +117 -0
  53. package/dist/sandbox/sandbox.module.d.ts +1 -1
  54. package/dist/sandbox/sandbox.module.js +13 -2
  55. package/dist/skills/invocable.controller.d.ts +4 -0
  56. package/dist/skills/invocable.controller.js +5 -1
  57. package/dist/skills/invoke.d.ts +68 -2
  58. package/dist/skills/invoke.js +128 -13
  59. package/dist/skills/skills.schemas.d.ts +7 -1
  60. package/dist/skills/skills.schemas.js +11 -2
  61. package/dist/tools/approvals.service.d.ts +82 -6
  62. package/dist/tools/approvals.service.js +233 -11
  63. package/dist/tools/call-scope.d.ts +9 -1
  64. package/dist/tools/loopback-asks.d.ts +52 -0
  65. package/dist/tools/loopback-asks.js +70 -0
  66. package/dist/tools/network-asks.d.ts +2 -1
  67. package/dist/tools/network-asks.js +10 -5
  68. package/dist/tools/pipeline.d.ts +59 -3
  69. package/dist/tools/pipeline.js +403 -40
  70. package/dist/tools/tools.module.js +3 -0
  71. package/package.json +2 -2
  72. package/src/migrations/0199_device_loopback_grants.sql +59 -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 },
@@ -15,6 +15,7 @@ import type { FileCardDetail } from "../platform/file-ref.js";
15
15
  import { type PersonFieldSpec } from "../platform/person-fields.js";
16
16
  import { SealedInputs } from "../platform/sealed-inputs.js";
17
17
  import { RunResume } from "../runtime/run-jobs.js";
18
+ import { LoopbackGrants } from "../sandbox/loopback-grants.js";
18
19
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
19
20
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
20
21
  import type { PermissionCandidate, PermissionEscalation, PermissionExpansion } from "../sandbox/permission-call-types.js";
@@ -108,14 +109,33 @@ export interface ServiceNetworkAskDetail extends NetworkAskDetailBase {
108
109
  /** The call's attempt (`tool_call_started`) that asked: the re-run takes the next one. */
109
110
  attempt: number;
110
111
  }
111
- /** A network ask's `detail`: a command's or a device service's. */
112
- export type NetworkAskDetail = CommandNetworkAskDetail | ServiceNetworkAskDetail;
112
+ /**
113
+ * A device service's loopback port ask (browser loopback port grants): an extension declaring
114
+ * `permissions.deviceAccess.loopbackPorts` whose service was refused a local port of the person's
115
+ * own device. It offers only `session` (a grant held by the conversation's root for 24 hours);
116
+ * approved, the grant is written in the decision's transaction and the call runs again, otherwise
117
+ * its kept result is written with the outcome's note. `service` names the extension whose service
118
+ * asked, `url` the page it was loading when known; `database` marks a well-known database port.
119
+ */
120
+ export interface LoopbackAskDetail extends Omit<NetworkAskDetailBase, "appliesAt" | "grantedHosts" | "outcome"> {
121
+ kind: "loopback";
122
+ service: string;
123
+ url: string | null;
124
+ port: number;
125
+ database: boolean;
126
+ /** The call's attempt (`tool_call_started`) that asked: the re-run takes the next one. */
127
+ attempt: number;
128
+ /** What took effect once approved: the root conversation's grant. */
129
+ outcome?: "session";
130
+ }
131
+ /** A network ask's `detail`: a command's, a device service's, or a loopback port's. */
132
+ export type NetworkAskDetail = CommandNetworkAskDetail | ServiceNetworkAskDetail | LoopbackAskDetail;
113
133
  /** `Omit` over each member of a union. */
114
134
  type OmitEach<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
115
135
  /** A network ask's detail as the API shows it: without the kept call result. */
116
136
  export type NetworkAskView = OmitEach<NetworkAskDetail, "result">;
117
- /** The hosts a network ask asked about, whichever kind it is. */
118
- export declare function networkAskHosts(detail: Pick<NetworkAskDetail, "hosts" | "kind">): string[];
137
+ /** The hosts a network ask asked about, whichever kind it is (a loopback port ask: none). */
138
+ export declare function networkAskHosts(detail: Pick<CommandNetworkAskDetail, "hosts" | "kind"> | Pick<ServiceNetworkAskDetail, "hosts" | "kind"> | Pick<LoopbackAskDetail, "kind">): string[];
119
139
  /**
120
140
  * A git push ask's `detail` (sandbox git credentials spec §7): the host, the repository
121
141
  * (`<owner>/<repo>`, normalized) and the refs of the push the gateway held, the command that ran
@@ -416,7 +436,7 @@ export interface NetworkAskInput {
416
436
  requestedFor: string;
417
437
  /** The tool key the ask is recorded under: the call's (`Bash` for a command). */
418
438
  toolKey: string;
419
- detail: OmitEach<NetworkAskDetail, "grantedHosts" | "outcome">;
439
+ detail: OmitEach<CommandNetworkAskDetail | ServiceNetworkAskDetail, "grantedHosts" | "outcome">;
420
440
  /**
421
441
  * What the device's provider enforces (device-provider spec §6.3, `networkAskOffer`): `once` (a
422
442
  * run grant) only with per-operation hosts, `always` (add to the device's own list) only when
@@ -424,6 +444,10 @@ export interface NetworkAskInput {
424
444
  */
425
445
  scopes: ("once" | "always")[];
426
446
  }
447
+ /** A new loopback port ask, made by the tool pipeline ({@link ApprovalsService.requestLoopback}). */
448
+ export type LoopbackAskInput = Omit<NetworkAskInput, "detail" | "scopes"> & {
449
+ detail: LoopbackAskDetail;
450
+ };
427
451
  /** The tool key a git ask is recorded under (the push ran in a `Bash` command). */
428
452
  export declare const GIT_ASK_TOOL_KEY = "Bash";
429
453
  /**
@@ -491,6 +515,8 @@ export declare class ApprovalsService {
491
515
  private readonly devices;
492
516
  private readonly permissionLocks?;
493
517
  private readonly permissionGrants?;
518
+ /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
519
+ private readonly loopback?;
494
520
  constructor(db: KernelDb, config: Pick<KernelConfigService, "get">, eventLog: Pick<EventLog, "appendIn" | "notify">, events: Pick<KernelEvents, "emit">, txHost: TransactionHost, automations: Pick<AutomationStore, "addGrant">,
495
521
  /** A trial approval is kept only for a tool the task may hold as a grant (its agent's tools). */
496
522
  registry: Pick<ToolRegistry, "forAgent">,
@@ -505,7 +531,9 @@ export declare class ApprovalsService {
505
531
  /** A person's entered values are sealed in the decision's transaction (§4.3). */
506
532
  sealed: Pick<SealedInputs, "sealIn">,
507
533
  /** A network ask's "add to this device's list" writes the device's own network list. */
508
- devices: Pick<DevicesService, "lockNetworkAddSubject" | "addNetworkHostsIn">, permissionLocks?: PermissionAuthorityLock | undefined, permissionGrants?: PermissionCallGrants | undefined);
534
+ devices: Pick<DevicesService, "lockNetworkAddSubject" | "addNetworkHostsIn">, permissionLocks?: PermissionAuthorityLock | undefined, permissionGrants?: PermissionCallGrants | undefined,
535
+ /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
536
+ loopback?: Pick<LoopbackGrants, "grantIn" | "refusalNow" | "liveLockedIn"> | undefined);
509
537
  /**
510
538
  * 新建 pending 审批(`expires_at` = 现在 + `tools.approvalTimeoutHours`)并写 `approval_requested`,同一事务。
511
539
  * 按 (run_id, call_id, attempt) 幂等:已存在则返回已有记录(不覆盖),事件按 `approval_requested:<approvalId>` 幂等。
@@ -531,6 +559,14 @@ export declare class ApprovalsService {
531
559
  * approval of the call follows it). One per call: a second request returns the first.
532
560
  */
533
561
  requestNetwork(input: NetworkAskInput): Promise<ApprovalRecord>;
562
+ /**
563
+ * A loopback port ask (browser loopback port grants): a pending approval of kind `network` for
564
+ * the device owner, offering only `session`, expiring like a tool approval, and its
565
+ * `approval_requested` (the call's tool key, the display-only `loopback`: service, port and
566
+ * whether it is a database port; no `network` field), in one transaction. One per call: a
567
+ * second request returns the first (whatever its kind).
568
+ */
569
+ requestLoopback(input: LoopbackAskInput): Promise<ApprovalRecord>;
534
570
  private requestNetworkIn;
535
571
  /**
536
572
  * A git push ask (sandbox git credentials spec §7): a pending approval of kind `git` for the
@@ -576,6 +612,46 @@ export declare class ApprovalsService {
576
612
  * resumes the run in its transaction and is announced after the commit.
577
613
  */
578
614
  private decideNetwork;
615
+ /**
616
+ * A loopback port ask's decision (browser loopback port grants), under {@link decideNetwork}'s
617
+ * lock and checks (the device owner, a signed-in session, still pending): an approval takes
618
+ * scope `session` and no hosts. The device's ceilings are read again first; refused, the ask
619
+ * stays pending (`approval.loopback_unavailable`). The grant
620
+ * (`LoopbackGrants.grantIn`, source `human`, the call and the attempt that asked) is written in
621
+ * the decision's transaction before its conversation, approval and run rows: the grant reads the
622
+ * root conversation `FOR SHARE` and a conversation's deletion locks its runs after its own row.
623
+ */
624
+ private decideLoopback;
625
+ /**
626
+ * The owner granted a port from the browser panel (`ctx.deviceAccess.grantLoopbackPort`): the
627
+ * pending loopback asks for that port of the same device service in the same conversation tree
628
+ * are approved as the owner's decision (the grant they find is the panel's), so their calls run
629
+ * again now instead of waiting for the approval timeout, and only while the panel's grant is
630
+ * still live (a revoke in the meantime wins). An ask decided meanwhile, or one the owner may no
631
+ * longer decide, is left as it is; any other failure leaves that ask pending and is returned (the
632
+ * caller logs it), and the others are still settled.
633
+ */
634
+ settleLoopbackAsks(orgId: string, accountId: string, key: {
635
+ deviceId: string;
636
+ serviceId: string;
637
+ rootConversationId: string;
638
+ port: number;
639
+ }): Promise<{
640
+ approved: number;
641
+ failed: {
642
+ approvalId: string;
643
+ err: unknown;
644
+ }[];
645
+ }>;
646
+ /**
647
+ * A loopback port ask's approval in one transaction: the tree's root conversation row first
648
+ * (`FOR NO KEY UPDATE`, the order a run's fence takes it in), then the grant, then the decision.
649
+ * Taking the root before the grant's `FOR SHARE` read and its (device, service) lock keeps one
650
+ * lock order with a concurrent panel grant (root share, then that lock): without it the
651
+ * decision held the root shared, the panel waited on the service lock, and the decision's
652
+ * append then waited to update the root behind the panel's share (a deadlock).
653
+ */
654
+ private decideLoopbackIn;
579
655
  /**
580
656
  * A git push ask's decision (sandbox git credentials spec §7): only the asked actor
581
657
  * (`requested_for`) decides, in a signed-in session (a personal access token is refused, as for