@capybara-hq/kernel 0.1.0-rc.37 → 0.1.0-rc.38

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 (67) hide show
  1. package/dist/admin/admin.module.d.ts +2 -1
  2. package/dist/admin/admin.module.js +5 -1
  3. package/dist/admin/org-network.controller.d.ts +30 -0
  4. package/dist/admin/org-network.controller.js +77 -0
  5. package/dist/admin/org-network.schemas.d.ts +16 -0
  6. package/dist/admin/org-network.schemas.js +27 -0
  7. package/dist/admin/org-network.service.d.ts +41 -0
  8. package/dist/admin/org-network.service.js +101 -0
  9. package/dist/catalog/marketplaces.service.d.ts +1 -1
  10. package/dist/config/schema.d.ts +1 -0
  11. package/dist/config/schema.js +8 -2
  12. package/dist/conversations/event-log.js +4 -1
  13. package/dist/ctx/create-ctx.d.ts +8 -1
  14. package/dist/ctx/create-ctx.js +12 -1
  15. package/dist/ctx/net.d.ts +50 -0
  16. package/dist/ctx/net.js +67 -0
  17. package/dist/db/kernel-schema.d.ts +10 -0
  18. package/dist/devices/devices.service.js +2 -1
  19. package/dist/errors.d.ts +5 -0
  20. package/dist/errors.js +5 -0
  21. package/dist/extensions/extensions.module.js +3 -0
  22. package/dist/extensions/host.d.ts +7 -1
  23. package/dist/extensions/host.js +13 -3
  24. package/dist/http/api.module.js +2 -0
  25. package/dist/infra/database/transaction-host.d.ts +32 -1
  26. package/dist/infra/database/transaction-host.js +30 -4
  27. package/dist/infra/database/xact-lock.d.ts +16 -0
  28. package/dist/infra/database/xact-lock.js +28 -1
  29. package/dist/net/public-address.d.ts +21 -1
  30. package/dist/net/public-address.js +56 -10
  31. package/dist/net/safe-fetch.d.ts +4 -1
  32. package/dist/net/safe-fetch.js +15 -4
  33. package/dist/orgs/directory-sync.js +2 -0
  34. package/dist/orgs/members.service.js +5 -0
  35. package/dist/orgs/network-allowances.service.d.ts +79 -0
  36. package/dist/orgs/network-allowances.service.js +371 -0
  37. package/dist/orgs/offboarding.d.ts +3 -1
  38. package/dist/orgs/offboarding.js +9 -2
  39. package/dist/orgs/org-lock.d.ts +28 -2
  40. package/dist/orgs/org-lock.js +59 -4
  41. package/dist/orgs/orgs.controller.d.ts +11 -2
  42. package/dist/orgs/orgs.controller.js +19 -3
  43. package/dist/orgs/orgs.module.d.ts +2 -1
  44. package/dist/orgs/orgs.module.js +5 -1
  45. package/dist/orgs/orgs.schemas.d.ts +12 -0
  46. package/dist/orgs/orgs.schemas.js +5 -0
  47. package/dist/orgs/orgs.service.js +6 -1
  48. package/dist/overrides.d.ts +4 -0
  49. package/dist/overrides.js +2 -0
  50. package/dist/platform/ops/orgs.ops.d.ts +7 -1
  51. package/dist/platform/ops/orgs.ops.js +122 -3
  52. package/dist/platform/route-schemas.js +3 -0
  53. package/dist/runtime/checkpointer.d.ts +3 -0
  54. package/dist/runtime/checkpointer.js +7 -4
  55. package/dist/runtime/langgraph-loop.js +8 -3
  56. package/dist/runtime/run-execution.d.ts +56 -3
  57. package/dist/runtime/run-execution.js +77 -8
  58. package/dist/runtime/step-log.d.ts +5 -0
  59. package/dist/runtime/step-log.js +9 -4
  60. package/dist/runtime/waits.js +3 -1
  61. package/dist/tools/connector-content.js +1 -0
  62. package/dist/tools/connectors.service.js +9 -6
  63. package/dist/tools/drift.d.ts +5 -1
  64. package/dist/tools/drift.js +9 -4
  65. package/dist/tools/pipeline.js +1 -0
  66. package/package.json +3 -3
  67. package/src/migrations/0145_org_network_allowances.sql +12 -0
@@ -1,5 +1,6 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { XactLock } from "../infra/database/xact-lock.js";
3
4
  export interface ExecutionClaim {
4
5
  runId: string;
5
6
  conversationId: string;
@@ -7,17 +8,69 @@ export interface ExecutionClaim {
7
8
  rootId: string;
8
9
  executionId: string;
9
10
  }
11
+ /**
12
+ * Runs `fn` (a tool step, a sub-agent dispatch) with every fenced transaction it opens admitted
13
+ * exclusively, even one that asks for shared admission (an event append made by a tool). Tool code
14
+ * takes org-level locks (`OrgLock`, agents, memberships, devices) after the conversation rows,
15
+ * which only the exclusive admission (the org row first) keeps in the global lock order; a
16
+ * transaction asking for shared admission takes none (an org-level lock in one throws,
17
+ * `assertNotSharedAdmission`), so this scope is not what keeps the order: it keeps tool steps
18
+ * serialized per org as the design states, and is defence in depth for a write a tool makes
19
+ * through a path marked shared.
20
+ */
21
+ export declare function withExclusiveAdmission<T>(fn: () => Promise<T>): Promise<T>;
22
+ /**
23
+ * Whether the caller runs inside {@link withExclusiveAdmission} (a tool step, a dispatch). A test
24
+ * seam: the kernel never reads it (the fence reads the scope directly); tests use it to prove which
25
+ * loop steps run under exclusive admission (`langgraph-loop.test.ts`).
26
+ */
27
+ export declare function inExclusiveAdmission(): boolean;
10
28
  /** Internal interruption: a revoked execution must never write its own terminal failure. */
11
29
  export declare class ExecutionRevoked extends Error {
12
30
  constructor();
13
31
  }
14
- /** Claims serialize on the same conversation lock as the event log and all fenced writes. */
32
+ /**
33
+ * Claims serialize on the same conversation lock as the event log and all fenced writes.
34
+ *
35
+ * The fence admits every writable transaction of a claimed run in one of two modes, then locks the
36
+ * root and the current conversation rows `FOR NO KEY UPDATE` and compares `runs.execution_id`:
37
+ * - **exclusive** (the default, and every transaction inside a tool step,
38
+ * {@link withExclusiveAdmission}: conformance with the design and defence in depth): the org row
39
+ * `FOR NO KEY UPDATE`, `OrgLock`'s mode. These
40
+ * transactions serialize per org with each other and with org admin writes, so whatever they
41
+ * lock after the conversation rows (`OrgLock`, agents, memberships, the default device) stays in
42
+ * the order org row → conversations that offboarding and the decisions take.
43
+ * - **shared** (a transaction opened with `admission: "shared"`: the run loop's event appends,
44
+ * checkpoint writes and suspend): the org admission lock shared
45
+ * (`XactLock.admitOrgShared`), and the org row read without a lock. These transactions lock
46
+ * nothing org-level after the conversation rows (enforced: `OrgLock`, the membership locks and
47
+ * `XactLock.lock` throw in one, `assertNotSharedAdmission`; only READ COMMITTED), so the runs of
48
+ * one org append in parallel.
49
+ * Org deletion and offboarding take the admission lock exclusively first
50
+ * (`OrgLock.lockForRemoval`): they wait for the admitted writes, keep new ones out (a later one
51
+ * then sees the org deleted), and are not starved by a stream of them (the lock queues fairly).
52
+ *
53
+ * Global order: org admission lock → org row → root conversation → conversation; a writer that
54
+ * locks several conversation or run rows of one tree locks the tree's root first (the fence
55
+ * does, so every fenced write of a tree serializes on its root). A claim never
56
+ * opens a nested fenced `requires_new` transaction (shared or not) and waits for it while its
57
+ * outer fenced transaction is open: the inner one waits for the outer's root row (and, behind a
58
+ * queued deletion, for the admission lock) on another connection, which PostgreSQL cannot see as
59
+ * a deadlock.
60
+ */
15
61
  export declare class RunExecution {
16
62
  private readonly db;
63
+ private readonly xactLock;
17
64
  readonly txHost: TransactionHost;
18
- constructor(db: KernelDb, txHost: TransactionHost);
65
+ constructor(db: KernelDb, xactLock: XactLock, txHost: TransactionHost);
19
66
  claim(conversationId: string, runId: string, executionId: string, live?: () => boolean): Promise<ExecutionClaim | null>;
20
67
  withClaim<T>(claim: ExecutionClaim, live: () => boolean, fn: () => Promise<T>): Promise<T>;
21
- /** Org, root, current conversation; allow FK references while excluding deletion and writes. */
68
+ /**
69
+ * The admission (see the class), then the root and the current conversation; NO KEY UPDATE
70
+ * allows foreign key references while excluding deletion and other writers. The root stays
71
+ * `FOR NO KEY UPDATE` in both modes: a sub-agent's handback appends to its parent (the root at
72
+ * depth 1) under `FOR UPDATE`, so two siblings holding the root only shared would deadlock
73
+ * upgrading it.
74
+ */
22
75
  private lockLiveConversation;
23
76
  }
@@ -7,24 +7,79 @@ 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 { AsyncLocalStorage } from "node:async_hooks";
10
11
  import { Inject, Injectable } from "@nestjs/common";
11
12
  import { KernelDb } from "../infra/database/kernel-db.js";
12
13
  import { TransactionHost, withTransactionFence } from "../infra/database/transaction-host.js";
13
14
  import { Transactional } from "../infra/database/transactional.decorator.js";
15
+ import { XactLock } from "../infra/database/xact-lock.js";
14
16
  import { isLive } from "./run-liveness.js";
15
17
  import { rootConversationOf } from "./subagents/child.js";
18
+ /** Set inside a tool step: every fenced transaction there is admitted exclusively. */
19
+ const exclusiveScope = new AsyncLocalStorage();
20
+ /**
21
+ * Runs `fn` (a tool step, a sub-agent dispatch) with every fenced transaction it opens admitted
22
+ * exclusively, even one that asks for shared admission (an event append made by a tool). Tool code
23
+ * takes org-level locks (`OrgLock`, agents, memberships, devices) after the conversation rows,
24
+ * which only the exclusive admission (the org row first) keeps in the global lock order; a
25
+ * transaction asking for shared admission takes none (an org-level lock in one throws,
26
+ * `assertNotSharedAdmission`), so this scope is not what keeps the order: it keeps tool steps
27
+ * serialized per org as the design states, and is defence in depth for a write a tool makes
28
+ * through a path marked shared.
29
+ */
30
+ export function withExclusiveAdmission(fn) {
31
+ return exclusiveScope.run(true, fn);
32
+ }
33
+ /**
34
+ * Whether the caller runs inside {@link withExclusiveAdmission} (a tool step, a dispatch). A test
35
+ * seam: the kernel never reads it (the fence reads the scope directly); tests use it to prove which
36
+ * loop steps run under exclusive admission (`langgraph-loop.test.ts`).
37
+ */
38
+ export function inExclusiveAdmission() {
39
+ return exclusiveScope.getStore() === true;
40
+ }
16
41
  /** Internal interruption: a revoked execution must never write its own terminal failure. */
17
42
  export class ExecutionRevoked extends Error {
18
43
  constructor() {
19
44
  super("execution revoked");
20
45
  }
21
46
  }
22
- /** Claims serialize on the same conversation lock as the event log and all fenced writes. */
47
+ /**
48
+ * Claims serialize on the same conversation lock as the event log and all fenced writes.
49
+ *
50
+ * The fence admits every writable transaction of a claimed run in one of two modes, then locks the
51
+ * root and the current conversation rows `FOR NO KEY UPDATE` and compares `runs.execution_id`:
52
+ * - **exclusive** (the default, and every transaction inside a tool step,
53
+ * {@link withExclusiveAdmission}: conformance with the design and defence in depth): the org row
54
+ * `FOR NO KEY UPDATE`, `OrgLock`'s mode. These
55
+ * transactions serialize per org with each other and with org admin writes, so whatever they
56
+ * lock after the conversation rows (`OrgLock`, agents, memberships, the default device) stays in
57
+ * the order org row → conversations that offboarding and the decisions take.
58
+ * - **shared** (a transaction opened with `admission: "shared"`: the run loop's event appends,
59
+ * checkpoint writes and suspend): the org admission lock shared
60
+ * (`XactLock.admitOrgShared`), and the org row read without a lock. These transactions lock
61
+ * nothing org-level after the conversation rows (enforced: `OrgLock`, the membership locks and
62
+ * `XactLock.lock` throw in one, `assertNotSharedAdmission`; only READ COMMITTED), so the runs of
63
+ * one org append in parallel.
64
+ * Org deletion and offboarding take the admission lock exclusively first
65
+ * (`OrgLock.lockForRemoval`): they wait for the admitted writes, keep new ones out (a later one
66
+ * then sees the org deleted), and are not starved by a stream of them (the lock queues fairly).
67
+ *
68
+ * Global order: org admission lock → org row → root conversation → conversation; a writer that
69
+ * locks several conversation or run rows of one tree locks the tree's root first (the fence
70
+ * does, so every fenced write of a tree serializes on its root). A claim never
71
+ * opens a nested fenced `requires_new` transaction (shared or not) and waits for it while its
72
+ * outer fenced transaction is open: the inner one waits for the outer's root row (and, behind a
73
+ * queued deletion, for the admission lock) on another connection, which PostgreSQL cannot see as
74
+ * a deadlock.
75
+ */
23
76
  let RunExecution = class RunExecution {
24
77
  db;
78
+ xactLock;
25
79
  txHost;
26
- constructor(db, txHost) {
80
+ constructor(db, xactLock, txHost) {
27
81
  this.db = db;
82
+ this.xactLock = xactLock;
28
83
  this.txHost = txHost;
29
84
  }
30
85
  async claim(conversationId, runId, executionId, live = () => true) {
@@ -52,9 +107,11 @@ let RunExecution = class RunExecution {
52
107
  return run ? claim : null;
53
108
  }
54
109
  withClaim(claim, live, fn) {
55
- return withTransactionFence(async () => {
56
- if (!live() || !(await this.lockLiveConversation(claim)))
110
+ return withTransactionFence(async ({ shared }) => {
111
+ const admitShared = shared && !exclusiveScope.getStore();
112
+ if (!live() || !(await this.lockLiveConversation(claim, admitShared))) {
57
113
  throw new ExecutionRevoked();
114
+ }
58
115
  const run = await this.db
59
116
  .selectFrom("runs")
60
117
  .select("execution_id")
@@ -63,15 +120,26 @@ let RunExecution = class RunExecution {
63
120
  .executeTakeFirst();
64
121
  if (run?.execution_id !== claim.executionId || !live())
65
122
  throw new ExecutionRevoked();
123
+ return admitShared ? "shared" : "exclusive";
66
124
  }, fn);
67
125
  }
68
- /** Org, root, current conversation; allow FK references while excluding deletion and writes. */
69
- async lockLiveConversation(claim) {
126
+ /**
127
+ * The admission (see the class), then the root and the current conversation; NO KEY UPDATE
128
+ * allows foreign key references while excluding deletion and other writers. The root stays
129
+ * `FOR NO KEY UPDATE` in both modes: a sub-agent's handback appends to its parent (the root at
130
+ * depth 1) under `FOR UPDATE`, so two siblings holding the root only shared would deadlock
131
+ * upgrading it.
132
+ */
133
+ async lockLiveConversation(claim, shared = false) {
134
+ // shared: after the admission lock, a plain read sees a committed deletion (a new statement
135
+ // under READ COMMITTED), and the deletion cannot commit before this transaction ends
136
+ if (shared)
137
+ await this.xactLock.admitOrgShared(claim.orgId);
70
138
  const org = await this.db
71
139
  .selectFrom("orgs")
72
140
  .select("deleted_at")
73
141
  .where("id", "=", claim.orgId)
74
- .forNoKeyUpdate()
142
+ .$call((q) => (shared ? q : q.forNoKeyUpdate()))
75
143
  .executeTakeFirst();
76
144
  if (!org || !isLive(org.deleted_at))
77
145
  return false;
@@ -101,6 +169,7 @@ __decorate([
101
169
  RunExecution = __decorate([
102
170
  Injectable(),
103
171
  __param(0, Inject(KernelDb)),
104
- __param(1, Inject(TransactionHost))
172
+ __param(1, Inject(XactLock)),
173
+ __param(2, Inject(TransactionHost))
105
174
  ], RunExecution);
106
175
  export { RunExecution };
@@ -13,6 +13,11 @@ export type StepAuditEntry = Parameters<typeof audit>[1];
13
13
  * definitions it sent, a denial with its audit row, usage events with their owed `usage.report`
14
14
  * deliveries (transactional outbox spec §8.1), and a sub-agent's usage counted on its parent run.
15
15
  * The step functions (`model-call.ts`, `hook-calls.ts`) reach it through their deps.
16
+ *
17
+ * Run loop hot-path writes: each transaction asks the run fence for shared admission
18
+ * (`RunExecution`), so the runs of one org write in parallel. They lock only the conversation rows,
19
+ * the run rows of the same tree and rows of their own; never anything org-level (`OrgLock`,
20
+ * agents, memberships).
16
21
  */
17
22
  export declare class StepLog {
18
23
  private readonly kdb;
@@ -24,6 +24,11 @@ import { UsageReportJobs, UsageReportJobsModule } from "./usage-report-jobs.js";
24
24
  * definitions it sent, a denial with its audit row, usage events with their owed `usage.report`
25
25
  * deliveries (transactional outbox spec §8.1), and a sub-agent's usage counted on its parent run.
26
26
  * The step functions (`model-call.ts`, `hook-calls.ts`) reach it through their deps.
27
+ *
28
+ * Run loop hot-path writes: each transaction asks the run fence for shared admission
29
+ * (`RunExecution`), so the runs of one org write in parallel. They lock only the conversation rows,
30
+ * the run rows of the same tree and rows of their own; never anything org-level (`OrgLock`,
31
+ * agents, memberships).
27
32
  */
28
33
  let StepLog = class StepLog {
29
34
  kdb;
@@ -97,16 +102,16 @@ let StepLog = class StepLog {
97
102
  }
98
103
  };
99
104
  __decorate([
100
- Transactional({ propagation: "requires_new" })
105
+ Transactional({ propagation: "requires_new", admission: "shared" })
101
106
  ], StepLog.prototype, "appendReported", null);
102
107
  __decorate([
103
- Transactional({ propagation: "requires_new" })
108
+ Transactional({ propagation: "requires_new", admission: "shared" })
104
109
  ], StepLog.prototype, "appendCounted", null);
105
110
  __decorate([
106
- Transactional({ propagation: "requires_new" })
111
+ Transactional({ propagation: "requires_new", admission: "shared" })
107
112
  ], StepLog.prototype, "appendAudited", null);
108
113
  __decorate([
109
- Transactional({ propagation: "requires_new" })
114
+ Transactional({ propagation: "requires_new", admission: "shared" })
110
115
  ], StepLog.prototype, "appendWithSpecs", null);
111
116
  StepLog = __decorate([
112
117
  Injectable(),
@@ -153,6 +153,8 @@ let Waits = class Waits {
153
153
  * {@link suspend}'s transaction: the conditional `running → waiting` and the wait's timeout job
154
154
  * owed with it ({@link oweTimeout}). False when the run was no longer running (nothing written).
155
155
  */
156
+ // a run loop hot-path write: shared admission under the run fence (`RunExecution`); it updates
157
+ // only the run row and owes its timeout
156
158
  async suspendIn(runId, waitingFor) {
157
159
  const row = await this.db
158
160
  .updateTable("runs")
@@ -722,7 +724,7 @@ let Waits = class Waits {
722
724
  }
723
725
  };
724
726
  __decorate([
725
- Transactional({ propagation: "requires_new" })
727
+ Transactional({ propagation: "requires_new", admission: "shared" })
726
728
  ], Waits.prototype, "suspendIn", null);
727
729
  __decorate([
728
730
  Transactional()
@@ -135,6 +135,7 @@ let ConnectorContent = class ConnectorContent {
135
135
  await this.credentials.onUnauthorized(orgId, app.id, auth, accountId, stale);
136
136
  },
137
137
  signal: AbortSignal.timeout(timeoutMs),
138
+ orgId,
138
139
  });
139
140
  return redactDeep(await work(session), redact());
140
141
  }
@@ -374,7 +374,7 @@ let ConnectorsService = class ConnectorsService {
374
374
  : undefined;
375
375
  let listed;
376
376
  if (auth.type !== "oauth_code") {
377
- listed = await this.drift.listTools(input.connector, endpoint, async () => {
377
+ listed = await this.drift.listTools(orgId, input.connector, endpoint, async () => {
378
378
  if (auth.type === "none")
379
379
  return { headers: {} };
380
380
  if (oauth?.tokens) {
@@ -383,7 +383,7 @@ let ConnectorsService = class ConnectorsService {
383
383
  if (!secret)
384
384
  throw new CredentialMissing(id, auth.ownership);
385
385
  return this.credentials.injectionFor(id, auth, secret);
386
- }, { orgId, slug });
386
+ }, { slug });
387
387
  }
388
388
  // the guide the wizard and 补充配置 showed: the template's current one (spec §11)
389
389
  const tpl = input.template;
@@ -704,7 +704,11 @@ let ConnectorsService = class ConnectorsService {
704
704
  let inspection;
705
705
  if (connector.inspect) {
706
706
  try {
707
- inspection = await connector.inspect({ endpoint, signal: AbortSignal.timeout(timeoutMs) });
707
+ inspection = await connector.inspect({
708
+ endpoint,
709
+ signal: AbortSignal.timeout(timeoutMs),
710
+ orgId,
711
+ });
708
712
  }
709
713
  catch (e) {
710
714
  const message = e instanceof ToolError
@@ -722,8 +726,7 @@ let ConnectorsService = class ConnectorsService {
722
726
  let tools = null;
723
727
  let issues = [];
724
728
  if (inject) {
725
- const listed = await this.drift.listTools(input.connector, endpoint, inject, {
726
- orgId,
729
+ const listed = await this.drift.listTools(orgId, input.connector, endpoint, inject, {
727
730
  preview: true,
728
731
  });
729
732
  const snap = snapshot(slug, listed.specs, listed.resources);
@@ -1289,7 +1292,7 @@ let ConnectorsService = class ConnectorsService {
1289
1292
  async refresh(orgId, connectorId, actorAccountId, actorTokenId, opts = {}) {
1290
1293
  const app = await this.row(this.db, orgId, connectorId);
1291
1294
  const auth = app.auth;
1292
- const { specs, resources } = await this.drift.listTools(app.connector, app.endpoint, () => this.credentials.injection(orgId, connectorId, auth, actorAccountId), { orgId, connectorId }, (last) => this.credentials.onUnauthorized(orgId, connectorId, auth, actorAccountId, last));
1295
+ const { specs, resources } = await this.drift.listTools(orgId, app.connector, app.endpoint, () => this.credentials.injection(orgId, connectorId, auth, actorAccountId), { connectorId }, (last) => this.credentials.onUnauthorized(orgId, connectorId, auth, actorAccountId, last));
1293
1296
  const { rows, issues } = snapshot(app.slug, specs, resources);
1294
1297
  return this.refreshIn(orgId, connectorId, actorAccountId, actorTokenId, opts, rows, issues);
1295
1298
  }
@@ -92,7 +92,11 @@ export declare class ToolDrift {
92
92
  * 清单里回显的凭据按本次注入的值打码(见 redact.ts)。凭据缺失原样抛 `credential.missing`;
93
93
  * 其余失败一律 502 `connector.connect_failed`,消息只带上游错误的类名(不带消息,消息里可能回显凭据)。
94
94
  */
95
- listTools(connector: string, endpoint: unknown, auth: () => Promise<AuthInjection>, logCtx: Record<string, unknown>,
95
+ listTools(
96
+ /** The org the session serves (`ConnectorOpenArgs.orgId`). */
97
+ orgId: string, connector: string, endpoint: unknown, auth: () => Promise<AuthInjection>,
98
+ /** Extra log fields (the org id is added from `orgId`). */
99
+ logCtx: Record<string, unknown>,
96
100
  /** 收到 401:OAuth 连接器在刷新锁内刷新(参数为最后一次注入的鉴权)。 */
97
101
  onUnauthorized?: (last: AuthInjection | undefined) => Promise<void>): Promise<{
98
102
  specs: unknown;
@@ -209,7 +209,11 @@ let ToolDrift = class ToolDrift {
209
209
  * 清单里回显的凭据按本次注入的值打码(见 redact.ts)。凭据缺失原样抛 `credential.missing`;
210
210
  * 其余失败一律 502 `connector.connect_failed`,消息只带上游错误的类名(不带消息,消息里可能回显凭据)。
211
211
  */
212
- async listTools(connector, endpoint, auth, logCtx,
212
+ async listTools(
213
+ /** The org the session serves (`ConnectorOpenArgs.orgId`). */
214
+ orgId, connector, endpoint, auth,
215
+ /** Extra log fields (the org id is added from `orgId`). */
216
+ logCtx,
213
217
  /** 收到 401:OAuth 连接器在刷新锁内刷新(参数为最后一次注入的鉴权)。 */
214
218
  onUnauthorized = async () => { }) {
215
219
  const c = this.registry.findConnector(connector);
@@ -231,6 +235,7 @@ let ToolDrift = class ToolDrift {
231
235
  auth: tracked,
232
236
  onUnauthorized: () => onUnauthorized(injected.at(-1)),
233
237
  signal,
238
+ orgId,
234
239
  });
235
240
  const specs = await session.listTools();
236
241
  return {
@@ -242,12 +247,12 @@ let ToolDrift = class ToolDrift {
242
247
  if (e instanceof CredentialMissing)
243
248
  throw e;
244
249
  // 日志经 logger 打码(凭据值已在构造注入时登记)
245
- this.log.warn("connector listTools failed", { ...logCtx, connector, err: e });
250
+ this.log.warn("connector listTools failed", { ...logCtx, orgId, connector, err: e });
246
251
  throw new ApiError("connector.connect_failed", connectFailedMessage(e, redactorFor(injected)));
247
252
  }
248
253
  finally {
249
254
  await session?.close().catch((e) => {
250
- this.log.warn("connector session close failed", { ...logCtx, connector, err: e });
255
+ this.log.warn("connector session close failed", { ...logCtx, orgId, connector, err: e });
251
256
  });
252
257
  }
253
258
  }
@@ -450,7 +455,7 @@ let ToolDrift = class ToolDrift {
450
455
  let reason = "no_credential";
451
456
  for (const accountId of accounts) {
452
457
  try {
453
- listed = await this.listTools(app.connector, app.endpoint, () => this.credentials.injection(orgId, connectorId, auth, accountId), { orgId, connectorId, trigger }, (last) => this.credentials.onUnauthorized(orgId, connectorId, auth, accountId, last));
458
+ listed = await this.listTools(orgId, app.connector, app.endpoint, () => this.credentials.injection(orgId, connectorId, auth, accountId), { connectorId, trigger }, (last) => this.credentials.onUnauthorized(orgId, connectorId, auth, accountId, last));
454
459
  break;
455
460
  }
456
461
  catch (e) {
@@ -1518,6 +1518,7 @@ let ToolPipeline = class ToolPipeline {
1518
1518
  await credentials.onUnauthorized(orgId, connectorId, auth, ctx.accountId, stale);
1519
1519
  },
1520
1520
  signal,
1521
+ orgId,
1521
1522
  onElicit: elicit.handle,
1522
1523
  onToolsChanged: () => {
1523
1524
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.37",
3
+ "version": "0.1.0-rc.38",
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": {
@@ -65,7 +65,7 @@
65
65
  "yaml": "^2.9.1",
66
66
  "yauzl": "3.4.0",
67
67
  "zod": "^4.6.7",
68
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.27"
68
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.29"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -74,7 +74,7 @@
74
74
  "@types/ws": "^8.18.2",
75
75
  "@types/yauzl": "3.4.0",
76
76
  "ws": "^8.22.0",
77
- "@capybara-hq/testing": "0.1.0-rc.21"
77
+ "@capybara-hq/testing": "0.1.0-rc.23"
78
78
  },
79
79
  "scripts": {
80
80
  "build": "tsc -b"
@@ -0,0 +1,12 @@
1
+ -- Internal endpoints a super admin lets one org's extension requests reach (plugin safe fetch spec):
2
+ -- `ctx.net.fetch` made for the org may connect to a private address only when the target matches
3
+ -- one of these entries. `entry` is a hostname, a `*.domain` wildcard, an IP, a CIDR, or an origin
4
+ -- `http(s)://host:port` (validated and normalized by the kernel, `orgs/network-allowances.service.ts`).
5
+ CREATE TABLE IF NOT EXISTS org_network_allowances (
6
+ id uuid PRIMARY KEY,
7
+ org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
8
+ entry text NOT NULL,
9
+ created_by text REFERENCES accounts(id) ON DELETE SET NULL,
10
+ created_at timestamptz NOT NULL DEFAULT now(),
11
+ UNIQUE (org_id, entry)
12
+ );