@capybara-hq/kernel 0.1.0-rc.104 → 0.1.0-rc.105

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 (49) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/conversations/conversations.service.d.ts +2 -0
  3. package/dist/conversations/conversations.service.js +6 -1
  4. package/dist/conversations/events.d.ts +2 -1
  5. package/dist/conversations/events.js +7 -6
  6. package/dist/errors.d.ts +13 -0
  7. package/dist/errors.js +13 -0
  8. package/dist/handoff/app-schemes.d.ts +28 -0
  9. package/dist/handoff/app-schemes.js +41 -0
  10. package/dist/handoff/handoff-paths.d.ts +26 -0
  11. package/dist/handoff/handoff-paths.js +25 -0
  12. package/dist/handoff/handoff-tickets.d.ts +28 -0
  13. package/dist/handoff/handoff-tickets.js +111 -0
  14. package/dist/handoff/handoff.controller.d.ts +24 -0
  15. package/dist/handoff/handoff.controller.js +74 -0
  16. package/dist/handoff/handoff.module.d.ts +7 -0
  17. package/dist/handoff/handoff.module.js +26 -0
  18. package/dist/handoff/handoff.schemas.d.ts +13 -0
  19. package/dist/handoff/handoff.schemas.js +3 -0
  20. package/dist/handoff/handoff.service.d.ts +49 -0
  21. package/dist/handoff/handoff.service.js +96 -0
  22. package/dist/http/api.module.js +8 -0
  23. package/dist/http/meta.controller.d.ts +1 -0
  24. package/dist/http/meta.controller.js +7 -0
  25. package/dist/identity/sso.controller.d.ts +30 -6
  26. package/dist/identity/sso.controller.js +51 -17
  27. package/dist/identity/sso.d.ts +10 -2
  28. package/dist/identity/sso.js +15 -3
  29. package/dist/overrides.d.ts +4 -4
  30. package/dist/overrides.js +1 -1
  31. package/dist/platform/exclusions.js +5 -0
  32. package/dist/platform/ops/connectors.ops.js +4 -2
  33. package/dist/runtime/compaction.service.d.ts +3 -1
  34. package/dist/runtime/compaction.service.js +3 -1
  35. package/dist/runtime/context/compaction.d.ts +27 -1
  36. package/dist/runtime/context/compaction.js +87 -32
  37. package/dist/runtime/model-call.d.ts +6 -4
  38. package/dist/runtime/model-call.js +17 -7
  39. package/dist/runtime/project/knowledge.service.d.ts +16 -7
  40. package/dist/runtime/project/knowledge.service.js +31 -13
  41. package/dist/tools/connectors.service.d.ts +4 -13
  42. package/dist/tools/connectors.service.js +12 -21
  43. package/dist/tools/oauth/flow.d.ts +16 -2
  44. package/dist/tools/oauth/flow.js +23 -4
  45. package/dist/tools/oauth/oauth.controller.d.ts +19 -7
  46. package/dist/tools/oauth/oauth.controller.js +42 -12
  47. package/dist/tools/oauth/oauth.schemas.d.ts +14 -1
  48. package/dist/tools/oauth/oauth.schemas.js +4 -1
  49. package/package.json +3 -3
@@ -129,6 +129,19 @@ export function turnsSinceSummary(events) {
129
129
  const floor = latestSummary([...events])?.payload.coversUpToSeq ?? Number.NEGATIVE_INFINITY;
130
130
  return events.filter((e) => e.type === "user_message" && e.seq > floor).length;
131
131
  }
132
+ /**
133
+ * The share of the model's context window a manual compaction keeps verbatim at most (context
134
+ * compaction spec §4.7, maintainer decision 2026-11-28).
135
+ */
136
+ export const MANUAL_TAIL_SHARE = 0.2;
137
+ /**
138
+ * The kept tail's budget of a manual compaction (spec §4.7, maintainer decision 2026-11-28): about
139
+ * {@link MANUAL_TAIL_SHARE} of the model's context window, never more than the tail budget every
140
+ * compaction has (`tailBudget`, the planning target minus the system prompt and tool definitions).
141
+ */
142
+ export function manualTailBudget(contextWindow, tailBudget) {
143
+ return Math.min(tailBudget, Math.floor(contextWindow * MANUAL_TAIL_SHARE));
144
+ }
132
145
  /**
133
146
  * The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
134
147
  * not a rule) and transcribe everything older that the previous summary does not cover yet (that
@@ -143,8 +156,13 @@ export function turnsSinceSummary(events) {
143
156
  * right after the summary (build.ts). A latest turn without a tool pair is kept whole (the hard fit
144
157
  * guard handles the rest). `coversUpToSeq` is the largest seq before the first kept event. Returns
145
158
  * null when there is nothing to summarize.
159
+ *
160
+ * `opts.manual` (a manual compact run, spec §4.7, maintainer decision 2026-11-28) ignores
161
+ * `keepRecentTurns`: the kept tail starts at the latest user turn, and inside it the same cut at
162
+ * tool-pair boundaries keeps only what fits `budget` (the caller passes {@link manualTailBudget}),
163
+ * never less than the latest tool pair.
146
164
  */
147
- export function compactionPlan(events, settings, budget) {
165
+ export function compactionPlan(events, settings, budget, opts = {}) {
148
166
  const sorted = [...events].sort((a, b) => a.seq - b.seq);
149
167
  const prev = latestSummary(sorted);
150
168
  const floor = prev ? prev.payload.coversUpToSeq : Number.NEGATIVE_INFINITY;
@@ -158,42 +176,38 @@ export function compactionPlan(events, settings, budget) {
158
176
  // run outcome notes (./run-outcome.ts), read from the whole log: a run's start may be older
159
177
  const notes = runOutcomeNotes(sorted);
160
178
  const tail = tailTokens(candidate, notes);
161
- const keep = settings.keepRecentTurns;
162
179
  let boundary;
163
- if (keep <= 0)
164
- boundary = candidate.length;
165
- else if (userIdx.length < keep)
166
- boundary = 0;
167
- else
168
- boundary = userIdx[userIdx.length - keep];
169
- boundary = keepToolPairs(atPair, userIdx, boundary);
170
- if (boundary < candidate.length && tail[boundary] > budget) {
171
- // size-aware tail: drop earlier kept turns until the rest fits the budget
172
- for (const start of userIdx) {
173
- if (start <= boundary)
174
- continue;
175
- boundary = keepToolPairs(atPair, userIdx, start);
176
- if (tail[boundary] <= budget)
177
- break;
180
+ if (opts.manual === true) {
181
+ // every turn before the latest user turn is summarized; without a user message since the
182
+ // last summary the whole range is the (continuing) latest turn
183
+ boundary = keepToolPairs(atPair, userIdx, userIdx.at(-1) ?? 0);
184
+ if (boundary < candidate.length && tail[boundary] > budget) {
185
+ boundary = cutInsideTurn(candidate, atPair, tail, boundary, budget);
178
186
  }
179
- // the latest user turn alone is over the budget: cut inside it at a tool-pair boundary,
180
- // oldest first, never past the latest tool pair (spec §4.2, revision 2026-11-15)
181
- if (tail[boundary] > budget) {
182
- let limit = -1;
183
- for (let i = candidate.length - 1; i > boundary && limit < 0; i--) {
184
- const e = candidate[i];
185
- if (e.type === "assistant_message" && e.payload.content.some((b) => b.type === "tool_call"))
186
- limit = i;
187
- }
188
- let chosen = boundary;
189
- for (let j = boundary + 1; j <= limit; j++) {
190
- if (!atPair[j])
187
+ }
188
+ else {
189
+ const keep = settings.keepRecentTurns;
190
+ if (keep <= 0)
191
+ boundary = candidate.length;
192
+ else if (userIdx.length < keep)
193
+ boundary = 0;
194
+ else
195
+ boundary = userIdx[userIdx.length - keep];
196
+ boundary = keepToolPairs(atPair, userIdx, boundary);
197
+ if (boundary < candidate.length && tail[boundary] > budget) {
198
+ // size-aware tail: drop earlier kept turns until the rest fits the budget
199
+ for (const start of userIdx) {
200
+ if (start <= boundary)
191
201
  continue;
192
- chosen = j;
193
- if (tail[j] <= budget)
202
+ boundary = keepToolPairs(atPair, userIdx, start);
203
+ if (tail[boundary] <= budget)
194
204
  break;
195
205
  }
196
- boundary = chosen;
206
+ // the latest user turn alone is over the budget: cut inside it (spec §4.2, revision
207
+ // 2026-11-15)
208
+ if (tail[boundary] > budget) {
209
+ boundary = cutInsideTurn(candidate, atPair, tail, boundary, budget);
210
+ }
197
211
  }
198
212
  }
199
213
  const covered = candidate.slice(0, boundary);
@@ -264,6 +278,24 @@ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Numb
264
278
  .filter((e) => e.type === "user_message" && e.seq > floor && e.seq <= upTo && e.seq <= coversUpToSeq)
265
279
  .map((e) => e.seq);
266
280
  }
281
+ /**
282
+ * The opening messages a manual compaction's summary re-renders (context compaction spec §4.7,
283
+ * maintainer decision 2026-11-28): a compact run is started by no message, so its own run has none;
284
+ * the turn it cuts into is the one the latest run a message started (trigger `message` or
285
+ * `schedule`) opened, and {@link openingSeqs} of that run decides which of its opening messages the
286
+ * summary covers. None when no such run is in the log.
287
+ */
288
+ export function manualOpeningSeqs(events, coversUpToSeq, absorbedUpToSeq) {
289
+ const start = events
290
+ .filter((e) => e.type === "run_started" &&
291
+ (e.payload.trigger === undefined ||
292
+ e.payload.trigger === "message" ||
293
+ e.payload.trigger === "schedule"))
294
+ .reduce((a, e) => (a === null || e.seq > a.seq ? e : a), null);
295
+ if (start?.runId == null)
296
+ return [];
297
+ return openingSeqs(events, start.runId, coversUpToSeq, absorbedUpToSeq);
298
+ }
267
299
  /**
268
300
  * Estimated input tokens of the kept tail from each index (`out[i]` for the events from `i` on,
269
301
  * `out[length]` = 0): the events rendered as the transcript renders them, then estimated with the
@@ -335,6 +367,29 @@ function keepToolPairs(atPair, userIdx, boundary) {
335
367
  }
336
368
  return 0;
337
369
  }
370
+ /**
371
+ * The cut inside the latest user turn (context compaction spec §4.2, revision 2026-11-15): from
372
+ * `boundary`, the first tool-pair boundary, oldest first, whose tail fits `budget`, never past the
373
+ * latest tool pair (the latest assistant message with tool calls). A turn without a tool pair after
374
+ * `boundary` keeps `boundary`.
375
+ */
376
+ function cutInsideTurn(candidate, atPair, tail, boundary, budget) {
377
+ let limit = -1;
378
+ for (let i = candidate.length - 1; i > boundary && limit < 0; i--) {
379
+ const e = candidate[i];
380
+ if (e.type === "assistant_message" && e.payload.content.some((b) => b.type === "tool_call"))
381
+ limit = i;
382
+ }
383
+ let chosen = boundary;
384
+ for (let j = boundary + 1; j <= limit; j++) {
385
+ if (!atPair[j])
386
+ continue;
387
+ chosen = j;
388
+ if (tail[j] <= budget)
389
+ break;
390
+ }
391
+ return chosen;
392
+ }
338
393
  function transcriptLine(e, notes) {
339
394
  switch (e.type) {
340
395
  case "user_message": {
@@ -372,10 +372,12 @@ interface CompactOptions {
372
372
  /** Whether `ref` is the fallback rung (its saved params are `fallbackParams`). */
373
373
  fallback?: boolean;
374
374
  /**
375
- * A manual compact run (spec §4.7, with `force`): an outcome the automatic paths keep silent is
376
- * recorded, so the person sees what their action did (maintainer decision 2026-11-28): nothing to
377
- * summarize writes `compaction_skipped`, a model or storage that cannot be reached right now
378
- * writes `compaction_failed`.
375
+ * A manual compact run (spec §4.7, with `force`): it plans with the manual rule (every turn before
376
+ * the latest summarized, at most {@link manualTailBudget} of the latest turn kept; maintainer
377
+ * decision 2026-11-28), which the reactive path (`force` alone) does not. An outcome the automatic
378
+ * paths keep silent is recorded, so the person sees what their action did: nothing to summarize
379
+ * writes `compaction_skipped`, a model or storage that cannot be reached right now writes
380
+ * `compaction_failed`.
379
381
  */
380
382
  manual?: boolean;
381
383
  }
@@ -5,7 +5,7 @@ import { ApiError } from "../errors.js";
5
5
  import { ExtensionUnloadedError } from "../extensions/inflight.js";
6
6
  import { hasInvocation, skillLoadOffered } from "../skills/catalog.js";
7
7
  import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./context/build.js";
8
- import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, turnsSinceSummary, } from "./context/compaction.js";
8
+ import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, manualOpeningSeqs, manualTailBudget, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, turnsSinceSummary, } from "./context/compaction.js";
9
9
  import { applyFit, estimateAfterFit, planFit, planningBounds, planReactiveTrim, planSqueezedFit, sentOutputCap, } from "./context/fit.js";
10
10
  import { guardToolPairs } from "./context/pairing.js";
11
11
  import { hasProjectSkills, overlongProjectSkills } from "./context/project-root.js";
@@ -814,20 +814,27 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
814
814
  // the input room left for the kept tail: the planning target `W - O_p - R_p`, minus the system
815
815
  // prompt and tool definitions every request carries
816
816
  const tailBudget = bounds.target - estimateTokens([], built.system, built.tools);
817
- const plan = compactionPlan(events, compaction, tailBudget);
817
+ // a manual compaction ignores keepRecentTurns and keeps at most about a fifth of the window of
818
+ // the latest turn (spec §4.7, maintainer decision 2026-11-28); the reactive path (`force`
819
+ // without `manual`) plans like the proactive one
820
+ const manual = opts.manual === true;
821
+ const plan = manual
822
+ ? compactionPlan(events, compaction, manualTailBudget(info.contextWindow, tailBudget), {
823
+ manual: true,
824
+ })
825
+ : compactionPlan(events, compaction, tailBudget);
818
826
  if (!plan) {
819
- if (opts.manual !== true)
827
+ if (!manual)
820
828
  return skipped(events);
821
829
  // a manual compaction that finds nothing to summarize says so (display only, never
822
- // model-visible): every user turn since the last summary is in the kept tail
830
+ // model-visible): nothing precedes the kept tail
823
831
  const written = await appendCounted(deps, input, [
824
832
  {
825
833
  type: "compaction_skipped",
826
834
  runId: input.runId,
827
835
  idemKey: idem.compactionSkipped(input.runId),
828
836
  payload: {
829
- reason: "too_few_turns",
830
- keepRecentTurns: compaction.keepRecentTurns,
837
+ reason: "nothing_to_summarize",
831
838
  turns: turnsSinceSummary(events),
832
839
  step: input.step,
833
840
  },
@@ -840,7 +847,10 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
840
847
  };
841
848
  }
842
849
  // decided now and recorded in the summary (spec §4.2): the request never depends on later events
843
- const opening = openingSeqs(events, input.runId, plan.coversUpToSeq, input.absorbedUpToSeq);
850
+ // a manual compact run is started by no message: the turn it cuts into is the latest message run's
851
+ const opening = manual
852
+ ? manualOpeningSeqs(events, plan.coversUpToSeq, input.absorbedUpToSeq)
853
+ : openingSeqs(events, input.runId, plan.coversUpToSeq, input.absorbedUpToSeq);
844
854
  const { runId, step, signal, conversationId } = input;
845
855
  const ref = modelRef;
846
856
  // §4.6 progress: from here the compaction is certain, so the conversation may show a row. It is
@@ -6,13 +6,22 @@ import { TransactionHost } from "../../infra/database/transaction-host.js";
6
6
  import type { KernelLogger } from "../../log.js";
7
7
  import { SandboxService } from "../../sandbox/sandbox.service.js";
8
8
  /**
9
- * The longest a run start waits for its project's knowledge (every device call of the read under
10
- * one bound): past it the run goes on without a new snapshot, as when the device is unreachable.
9
+ * The time limits of a run start's project read. The device's start (a resume, or a recreate when
10
+ * its instance is gone) and the read itself are bounded apart, so a slow start never eats the
11
+ * read's time: past either the run goes on without a new snapshot, as when the device is
12
+ * unreachable.
11
13
  */
12
- export declare const PROJECT_KNOWLEDGE_TIMEOUT_MS = 30000;
14
+ export interface ProjectKnowledgeTimeouts {
15
+ /** Entering the device: from the read's start until the device runs. */
16
+ startMs: number;
17
+ /** Every device call of the read once the device runs, under one bound. */
18
+ readMs: number;
19
+ }
20
+ /** The default {@link ProjectKnowledgeTimeouts}. */
21
+ export declare const PROJECT_KNOWLEDGE_TIMEOUTS: ProjectKnowledgeTimeouts;
13
22
  /**
14
- * Test seam (`KernelSeams`): the read's time limit in ms, asked at every read; default
15
- * {@link PROJECT_KNOWLEDGE_TIMEOUT_MS}.
23
+ * Test seam (`KernelSeams`): the read's time limits, asked at every read; default
24
+ * {@link PROJECT_KNOWLEDGE_TIMEOUTS}.
16
25
  */
17
26
  export declare const PROJECT_KNOWLEDGE_TIMEOUT: unique symbol;
18
27
  /** What a run start tells {@link ProjectKnowledgeService.record}. */
@@ -62,8 +71,8 @@ export declare class ProjectKnowledgeService {
62
71
  private readonly projects;
63
72
  private readonly sandbox;
64
73
  private readonly log;
65
- private readonly timeoutMs;
66
- constructor(db: KernelDb, eventLog: Pick<EventLog, "appendIn" | "notify">, txHost: TransactionHost, devices: Pick<ConversationDevices, "forTool">, projects: Pick<DeviceProjectsService, "scopeFor" | "keeps">, sandbox: Pick<SandboxService, "withKernelRead">, log: KernelLogger, timeoutMs?: () => number);
74
+ private readonly timeouts;
75
+ constructor(db: KernelDb, eventLog: Pick<EventLog, "appendIn" | "notify">, txHost: TransactionHost, devices: Pick<ConversationDevices, "forTool">, projects: Pick<DeviceProjectsService, "scopeFor" | "keeps">, sandbox: Pick<SandboxService, "withKernelRead">, log: KernelLogger, timeouts?: () => ProjectKnowledgeTimeouts);
67
76
  /**
68
77
  * Reads and records (see the class); notifies after the commit. False: the run had ended under
69
78
  * the locks (a stop landed while the device was read), so nothing was appended and the run must
@@ -27,16 +27,18 @@ import { providerConnectionFailure } from "../../sandbox/unreachable.js";
27
27
  import { currentExecutionClaim } from "../run-execution.js";
28
28
  import { runEndedIn } from "../run-status.js";
29
29
  import { projectRootIdemKey, projectUnavailable, readProjectKnowledge, sameProjectRoot, unavailableProject, } from "./knowledge.js";
30
+ /** The default {@link ProjectKnowledgeTimeouts}. */
31
+ export const PROJECT_KNOWLEDGE_TIMEOUTS = {
32
+ startMs: 60_000,
33
+ readMs: 30_000,
34
+ };
30
35
  /**
31
- * The longest a run start waits for its project's knowledge (every device call of the read under
32
- * one bound): past it the run goes on without a new snapshot, as when the device is unreachable.
33
- */
34
- export const PROJECT_KNOWLEDGE_TIMEOUT_MS = 30_000;
35
- /**
36
- * Test seam (`KernelSeams`): the read's time limit in ms, asked at every read; default
37
- * {@link PROJECT_KNOWLEDGE_TIMEOUT_MS}.
36
+ * Test seam (`KernelSeams`): the read's time limits, asked at every read; default
37
+ * {@link PROJECT_KNOWLEDGE_TIMEOUTS}.
38
38
  */
39
39
  export const PROJECT_KNOWLEDGE_TIMEOUT = Symbol("PROJECT_KNOWLEDGE_TIMEOUT");
40
+ /** The abort reason of a passed time limit (as `AbortSignal.timeout` gives). */
41
+ const timeoutReason = (what) => new DOMException(`The project read's ${what} time limit passed`, "TimeoutError");
40
42
  /** The run start has no current execution claim of its own run: nothing is admitted. */
41
43
  class KnowledgeClaimMissing extends Error {
42
44
  constructor() {
@@ -91,8 +93,8 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
91
93
  projects;
92
94
  sandbox;
93
95
  log;
94
- timeoutMs;
95
- constructor(db, eventLog, txHost, devices, projects, sandbox, log, timeoutMs = () => PROJECT_KNOWLEDGE_TIMEOUT_MS) {
96
+ timeouts;
97
+ constructor(db, eventLog, txHost, devices, projects, sandbox, log, timeouts = () => PROJECT_KNOWLEDGE_TIMEOUTS) {
96
98
  this.db = db;
97
99
  this.eventLog = eventLog;
98
100
  this.txHost = txHost;
@@ -100,7 +102,7 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
100
102
  this.projects = projects;
101
103
  this.sandbox = sandbox;
102
104
  this.log = log;
103
- this.timeoutMs = timeoutMs;
105
+ this.timeouts = timeouts;
104
106
  }
105
107
  /**
106
108
  * Reads and records (see the class); notifies after the commit. False: the run had ended under
@@ -169,7 +171,12 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
169
171
  runId: input.runId,
170
172
  project: bound.project,
171
173
  };
172
- const signal = AbortSignal.any([input.signal, AbortSignal.timeout(this.timeoutMs())]);
174
+ const limits = this.timeouts();
175
+ // the start's limit runs until the device runs; the read then has its own
176
+ const start = new AbortController();
177
+ const startTimer = setTimeout(() => start.abort(timeoutReason("start")), limits.startMs);
178
+ const signal = AbortSignal.any([input.signal, start.signal]);
179
+ let readSignal;
173
180
  try {
174
181
  // the device a tool call of this conversation would enter, checked for its owner now
175
182
  const deviceId = await this.devices.forTool(input.orgId, input.conversationId);
@@ -202,7 +209,10 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
202
209
  conversationId: input.conversationId,
203
210
  runId: input.runId,
204
211
  },
205
- }, async (h, p, info, sig) => {
212
+ }, async (h, p, info, held) => {
213
+ clearTimeout(startTimer);
214
+ const sig = AbortSignal.any([held, AbortSignal.timeout(limits.readMs)]);
215
+ readSignal = sig;
206
216
  const target = { project: bound.project, root: bound.root, mode: scope.mode };
207
217
  // the kernel's own check first: a root above the owner's home is refused as the working
208
218
  // root's rule refuses it (`workingRootOf`, the same home: the reported one, else the
@@ -253,13 +263,21 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
253
263
  }, signal);
254
264
  }
255
265
  catch (err) {
266
+ const stopped = input.signal.aborted;
267
+ const readTimedOut = !stopped && readSignal?.aborted === true;
268
+ const startTimedOut = !stopped && start.signal.aborted;
256
269
  this.log.warn("project knowledge not read: the device could not be asked; the run goes on", {
257
270
  ...where,
258
- timedOut: signal.aborted && !input.signal.aborted,
271
+ timedOut: readTimedOut || startTimedOut,
272
+ ...(startTimedOut && { timedOutIn: "start" }),
273
+ ...(readTimedOut && { timedOutIn: "read" }),
259
274
  err,
260
275
  });
261
276
  return null;
262
277
  }
278
+ finally {
279
+ clearTimeout(startTimer);
280
+ }
263
281
  }
264
282
  /**
265
283
  * How the read enters the device: `withKernelRead` under the run's current execution claim (the
@@ -1,6 +1,5 @@
1
1
  import { type AuthHint, type ConnectorOperation, type GitSource, type ToolAnnotations } from "@capybara-hq/plugin-sdk";
2
2
  import { type ConnectionGuideState, type GuideAck, PluginGuides } from "../extensions/plugin-guides.js";
3
- import { ExtensionRegistry } from "../extensions/registry.js";
4
3
  import type { WriteActor } from "../identity/write-actor.js";
5
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
5
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -259,11 +258,6 @@ export interface OAuthSetup {
259
258
  export declare class ConnectorsService {
260
259
  private readonly kdb;
261
260
  private readonly registry;
262
- /**
263
- * Extension manifests: a derived default slug avoids an extension's name (an explicit slug may
264
- * take one; connector and extension tool keys live in separate namespaces).
265
- */
266
- private readonly extensions;
267
261
  private readonly credentials;
268
262
  private readonly config;
269
263
  private readonly drift;
@@ -276,12 +270,7 @@ export declare class ConnectorsService {
276
270
  readonly txHost: TransactionHost;
277
271
  /** Setup guides of connector templates (spec 2026-11-09-setup-guides-v2-design.md §11). */
278
272
  private readonly guides;
279
- constructor(kdb: KernelDb, registry: ToolRegistry,
280
- /**
281
- * Extension manifests: a derived default slug avoids an extension's name (an explicit slug may
282
- * take one; connector and extension tool keys live in separate namespaces).
283
- */
284
- extensions: Pick<ExtensionRegistry, "manifests">, credentials: Credentials, config: Pick<KernelConfigService, "get">, drift: ToolDrift,
273
+ constructor(kdb: KernelDb, registry: ToolRegistry, credentials: Credentials, config: Pick<KernelConfigService, "get">, drift: ToolDrift,
285
274
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
286
275
  orgLock: Pick<OrgLock, "lock" | "tryLock" | "lockAndAuthorize">,
287
276
  /** Owed work: the tool listings that follow a deferred create or a setup (§5.2.1). */
@@ -300,7 +289,9 @@ export declare class ConnectorsService {
300
289
  private slugTaken;
301
290
  /**
302
291
  * The first free default name and slug ({@link CreateConnectorInput.slugDefault}), read in the
303
- * caller's transaction under the org lock.
292
+ * caller's transaction under the org lock. Only live connectors hold a slug: an extension's name
293
+ * does not, as for an explicit slug, since connector tools are `mcp__<slug>__<tool>` and extension
294
+ * tools `plugin__<plugin>__<tool>` (a template's default slug is often its plugin's name: slack).
304
295
  */
305
296
  private freeName;
306
297
  private resolveSlug;
@@ -17,7 +17,6 @@ import { assertItemInstallable } from "../catalog/request-rules.js";
17
17
  import { productName } from "../config/product-name.js";
18
18
  import { ApiError } from "../errors.js";
19
19
  import { PluginGuides, } from "../extensions/plugin-guides.js";
20
- import { ExtensionRegistry } from "../extensions/registry.js";
21
20
  import { audit } from "../identity/audit.js";
22
21
  import { assertCustomAllowed } from "../identity/settings.js";
23
22
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -116,7 +115,6 @@ const unannotated = (a) => a?.readOnlyHint === undefined && a?.destructiveHint =
116
115
  let ConnectorsService = class ConnectorsService {
117
116
  kdb;
118
117
  registry;
119
- extensions;
120
118
  credentials;
121
119
  config;
122
120
  drift;
@@ -125,12 +123,7 @@ let ConnectorsService = class ConnectorsService {
125
123
  locks;
126
124
  txHost;
127
125
  guides;
128
- constructor(kdb, registry,
129
- /**
130
- * Extension manifests: a derived default slug avoids an extension's name (an explicit slug may
131
- * take one; connector and extension tool keys live in separate namespaces).
132
- */
133
- extensions, credentials, config, drift,
126
+ constructor(kdb, registry, credentials, config, drift,
134
127
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
135
128
  orgLock,
136
129
  /** Owed work: the tool listings that follow a deferred create or a setup (§5.2.1). */
@@ -141,7 +134,6 @@ let ConnectorsService = class ConnectorsService {
141
134
  guides) {
142
135
  this.kdb = kdb;
143
136
  this.registry = registry;
144
- this.extensions = extensions;
145
137
  this.credentials = credentials;
146
138
  this.config = config;
147
139
  this.drift = drift;
@@ -189,7 +181,9 @@ let ConnectorsService = class ConnectorsService {
189
181
  }
190
182
  /**
191
183
  * The first free default name and slug ({@link CreateConnectorInput.slugDefault}), read in the
192
- * caller's transaction under the org lock.
184
+ * caller's transaction under the org lock. Only live connectors hold a slug: an extension's name
185
+ * does not, as for an explicit slug, since connector tools are `mcp__<slug>__<tool>` and extension
186
+ * tools `plugin__<plugin>__<tool>` (a template's default slug is often its plugin's name: slack).
193
187
  */
194
188
  async freeName(t, orgId, d) {
195
189
  const base = deriveSlug(d.name ?? d.display) ?? deriveSlug(d.display);
@@ -202,8 +196,6 @@ let ConnectorsService = class ConnectorsService {
202
196
  .where("org_id", "=", orgId)
203
197
  .where("deleted_at", "is", null)
204
198
  .execute()).map((r) => r.slug));
205
- for (const m of this.extensions.manifests())
206
- taken.add(m.name);
207
199
  for (let n = 1;; n++) {
208
200
  const suffix = n === 1 ? "" : `_${n}`;
209
201
  const slug = `${base.slice(0, 24 - suffix.length).replace(/_+$/, "")}${suffix}`;
@@ -1987,14 +1979,13 @@ ConnectorsService = __decorate([
1987
1979
  Injectable(),
1988
1980
  __param(0, Inject(KernelDb)),
1989
1981
  __param(1, Inject(ToolRegistry)),
1990
- __param(2, Inject(ExtensionRegistry)),
1991
- __param(3, Inject(Credentials)),
1992
- __param(4, Inject(KernelConfigService)),
1993
- __param(5, Inject(ToolDrift)),
1994
- __param(6, Inject(OrgLock)),
1995
- __param(7, Inject(OutboxService)),
1996
- __param(8, Inject(LockService)),
1997
- __param(9, Inject(TransactionHost)),
1998
- __param(10, Inject(PluginGuides))
1982
+ __param(2, Inject(Credentials)),
1983
+ __param(3, Inject(KernelConfigService)),
1984
+ __param(4, Inject(ToolDrift)),
1985
+ __param(5, Inject(OrgLock)),
1986
+ __param(6, Inject(OutboxService)),
1987
+ __param(7, Inject(LockService)),
1988
+ __param(8, Inject(TransactionHost)),
1989
+ __param(9, Inject(PluginGuides))
1999
1990
  ], ConnectorsService);
2000
1991
  export { ConnectorsService };
@@ -1,5 +1,6 @@
1
1
  import type { Logger } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
+ import { type HandoffRecord } from "../../handoff/handoff-paths.js";
3
4
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
4
5
  import { KernelDb } from "../../infra/database/kernel-db.js";
5
6
  import { TransactionHost } from "../../infra/database/transaction-host.js";
@@ -36,8 +37,21 @@ export declare class OAuthFlow {
36
37
  /** 某成员首次成功连接、而连接器还没有工具快照时(A16:用该成员的 token 刷新工具清单)。 */
37
38
  private onFirstConnect;
38
39
  private app;
39
- /** 生成授权 URL。`binding` 为本浏览器的绑定值(由 controller 写入 Cookie)。 */
40
- start(orgId: string, connectorId: string, accountId: string, returnTo: string | undefined, binding: string): Promise<{
40
+ /**
41
+ * Every check {@link start} makes before it writes the state: `http.publicUrl` is set, the
42
+ * connector exists, is an active `oauth_code` connector and has a client with an authorization
43
+ * endpoint (a dcr connector created without a client registers it now, once across replicas,
44
+ * R16). A browser handoff start runs it so a connector that cannot be connected fails in the app,
45
+ * not after the person signed in in the browser.
46
+ */
47
+ check(orgId: string, connectorId: string, accountId: string): Promise<void>;
48
+ private prepare;
49
+ /**
50
+ * Builds the authorization URL. `binding` is this browser's binding value (the controller writes
51
+ * the cookie). With `handoff` (a browser handoff redeemed in this browser), the state's return
52
+ * page is the handoff done page built from the ticket's record, and `returnTo` is ignored.
53
+ */
54
+ start(orgId: string, connectorId: string, accountId: string, returnTo: string | undefined, binding: string, handoff?: HandoffRecord): Promise<{
41
55
  authorizationUrl: string;
42
56
  }>;
43
57
  /** 回跳地址:`http.publicUrl` + 站内路径 + 结果参数(未配置 publicUrl 时为相对地址)。 */
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { createHash, randomBytes } from "node:crypto";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { ApiError } from "../../errors.js";
13
+ import { handoffDonePath } from "../../handoff/handoff-paths.js";
13
14
  import { audit } from "../../identity/audit.js";
14
15
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
15
16
  import { KernelDb } from "../../infra/database/kernel-db.js";
@@ -77,8 +78,17 @@ let OAuthFlow = class OAuthFlow {
77
78
  .where("deleted_at", "is", null)
78
79
  .executeTakeFirst();
79
80
  }
80
- /** 生成授权 URL。`binding` 为本浏览器的绑定值(由 controller 写入 Cookie)。 */
81
- async start(orgId, connectorId, accountId, returnTo, binding) {
81
+ /**
82
+ * Every check {@link start} makes before it writes the state: `http.publicUrl` is set, the
83
+ * connector exists, is an active `oauth_code` connector and has a client with an authorization
84
+ * endpoint (a dcr connector created without a client registers it now, once across replicas,
85
+ * R16). A browser handoff start runs it so a connector that cannot be connected fails in the app,
86
+ * not after the person signed in in the browser.
87
+ */
88
+ async check(orgId, connectorId, accountId) {
89
+ await this.prepare(orgId, connectorId, accountId);
90
+ }
91
+ async prepare(orgId, connectorId, accountId) {
82
92
  const publicUrl = this.config.get().http.publicUrl;
83
93
  if (!publicUrl)
84
94
  throw publicUrlRequired();
@@ -103,6 +113,15 @@ let OAuthFlow = class OAuthFlow {
103
113
  if (!client?.authorizationEndpoint) {
104
114
  throw new ApiError("connector.connect_failed", "This connector needs to be configured by an organization admin before members can connect it.");
105
115
  }
116
+ return { publicUrl, app, client, authorizationEndpoint: client.authorizationEndpoint };
117
+ }
118
+ /**
119
+ * Builds the authorization URL. `binding` is this browser's binding value (the controller writes
120
+ * the cookie). With `handoff` (a browser handoff redeemed in this browser), the state's return
121
+ * page is the handoff done page built from the ticket's record, and `returnTo` is ignored.
122
+ */
123
+ async start(orgId, connectorId, accountId, returnTo, binding, handoff) {
124
+ const { publicUrl, app, client, authorizationEndpoint } = await this.prepare(orgId, connectorId, accountId);
106
125
  const state = b64url();
107
126
  const verifier = b64url();
108
127
  const redirectUri = callbackUrl(publicUrl);
@@ -112,12 +131,12 @@ let OAuthFlow = class OAuthFlow {
112
131
  accountId,
113
132
  verifier,
114
133
  redirectUri,
115
- returnTo: returnTo ?? DEFAULT_RETURN_PATH,
134
+ returnTo: handoff !== undefined ? handoffDonePath(handoff) : (returnTo ?? DEFAULT_RETURN_PATH),
116
135
  binding: sha256(binding),
117
136
  ...(client.issuer !== undefined && { issuer: client.issuer }),
118
137
  };
119
138
  await this.redis.set(stateKey(state), JSON.stringify(rec), "EX", OAUTH_STATE_TTL_SECONDS);
120
- const url = new URL(client.authorizationEndpoint);
139
+ const url = new URL(authorizationEndpoint);
121
140
  url.searchParams.set("response_type", "code");
122
141
  url.searchParams.set("client_id", client.clientId);
123
142
  url.searchParams.set("redirect_uri", redirectUri);
@@ -1,21 +1,33 @@
1
1
  import type { FastifyReply, FastifyRequest } from "fastify";
2
2
  import type { z } from "zod";
3
+ import { HandoffTickets } from "../../handoff/handoff-tickets.js";
3
4
  import { type Principal } from "../../identity/principal.js";
4
5
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
5
6
  import { type OrgContext } from "../../orgs/org.guard.js";
6
7
  import { OAuthFlow } from "./flow.js";
7
- import { OAuthConnectBodySchema } from "./oauth.schemas.js";
8
+ import { OAuthConnectBodySchema, type OAuthConnectResponse } from "./oauth.schemas.js";
8
9
  /**
9
- * 发起 OAuth 连接(`POST /orgs/:orgId/connectors/:connectorId/connect`,`connectors.use`,仅用户主体):返回授权 URL,并写浏览器绑定
10
- * Cookie `cap_oauth`(HttpOnly、SameSite=Lax——授权服务器回跳是跨站顶级 GET 导航、Lax 会带上;Path 只到回调)。
10
+ * Writes the OAuth browser binding cookie `cap_oauth` (HttpOnly, SameSite=Lax: the authorization
11
+ * server's redirect back is a cross-site top-level GET, which Lax sends; Path only the callback).
12
+ */
13
+ export declare function setOAuthBindingCookie(reply: FastifyReply, binding: string, config: {
14
+ auth: {
15
+ cookieSecure: boolean;
16
+ };
17
+ }): void;
18
+ /**
19
+ * Starts an OAuth connection (`POST /orgs/:orgId/connectors/:connectorId/connect`,
20
+ * `connectors.use`, user principals only): returns the authorization URL and writes the browser
21
+ * binding cookie ({@link setOAuthBindingCookie}). With `handoff` (a native shell, shell external
22
+ * authorization spec §1): the same checks, then a handoff ticket and its web page instead, with
23
+ * no cookie and no OAuth state; the flow starts when the person redeems it in the system browser.
11
24
  */
12
25
  export declare class OAuthConnectController {
13
26
  private readonly flow;
14
27
  private readonly config;
15
- constructor(flow: OAuthFlow, config: KernelConfigService);
16
- connect(principal: Principal, org: OrgContext, connectorId: string, body: z.infer<typeof OAuthConnectBodySchema>, req: FastifyRequest, reply: FastifyReply): Promise<{
17
- authorizationUrl: string;
18
- }>;
28
+ private readonly tickets;
29
+ constructor(flow: OAuthFlow, config: KernelConfigService, tickets: HandoffTickets);
30
+ connect(principal: Principal, org: OrgContext, connectorId: string, body: z.infer<typeof OAuthConnectBodySchema>, req: FastifyRequest, reply: FastifyReply): Promise<OAuthConnectResponse>;
19
31
  }
20
32
  /**
21
33
  * 授权服务器的回跳(`GET /api/v1/oauth/callback`,公开路由:浏览器从授权服务器跳回来,会话 Cookie 可能已过期;