@capybara-hq/kernel 0.1.0-rc.103 → 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 (55) 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 +12 -0
  5. package/dist/conversations/events.js +23 -0
  6. package/dist/errors.d.ts +13 -0
  7. package/dist/errors.js +13 -0
  8. package/dist/evals/reconstruct.d.ts +9 -1
  9. package/dist/evals/reconstruct.js +7 -0
  10. package/dist/handoff/app-schemes.d.ts +28 -0
  11. package/dist/handoff/app-schemes.js +41 -0
  12. package/dist/handoff/handoff-paths.d.ts +26 -0
  13. package/dist/handoff/handoff-paths.js +25 -0
  14. package/dist/handoff/handoff-tickets.d.ts +28 -0
  15. package/dist/handoff/handoff-tickets.js +111 -0
  16. package/dist/handoff/handoff.controller.d.ts +24 -0
  17. package/dist/handoff/handoff.controller.js +74 -0
  18. package/dist/handoff/handoff.module.d.ts +7 -0
  19. package/dist/handoff/handoff.module.js +26 -0
  20. package/dist/handoff/handoff.schemas.d.ts +13 -0
  21. package/dist/handoff/handoff.schemas.js +3 -0
  22. package/dist/handoff/handoff.service.d.ts +49 -0
  23. package/dist/handoff/handoff.service.js +96 -0
  24. package/dist/http/api.module.js +8 -0
  25. package/dist/http/meta.controller.d.ts +1 -0
  26. package/dist/http/meta.controller.js +7 -0
  27. package/dist/identity/sso.controller.d.ts +30 -6
  28. package/dist/identity/sso.controller.js +51 -17
  29. package/dist/identity/sso.d.ts +10 -2
  30. package/dist/identity/sso.js +15 -3
  31. package/dist/overrides.d.ts +4 -4
  32. package/dist/overrides.js +1 -1
  33. package/dist/platform/exclusions.js +5 -0
  34. package/dist/platform/ops/connectors.ops.js +4 -2
  35. package/dist/runtime/compaction.service.d.ts +6 -3
  36. package/dist/runtime/compaction.service.js +7 -6
  37. package/dist/runtime/context/build.d.ts +13 -3
  38. package/dist/runtime/context/build.js +26 -6
  39. package/dist/runtime/context/compaction.d.ts +29 -1
  40. package/dist/runtime/context/compaction.js +108 -39
  41. package/dist/runtime/context/run-outcome.d.ts +10 -0
  42. package/dist/runtime/context/run-outcome.js +92 -0
  43. package/dist/runtime/model-call.d.ts +9 -0
  44. package/dist/runtime/model-call.js +63 -7
  45. package/dist/runtime/project/knowledge.service.d.ts +16 -7
  46. package/dist/runtime/project/knowledge.service.js +31 -13
  47. package/dist/tools/connectors.service.d.ts +4 -13
  48. package/dist/tools/connectors.service.js +12 -21
  49. package/dist/tools/oauth/flow.d.ts +16 -2
  50. package/dist/tools/oauth/flow.js +23 -4
  51. package/dist/tools/oauth/oauth.controller.d.ts +19 -7
  52. package/dist/tools/oauth/oauth.controller.js +42 -12
  53. package/dist/tools/oauth/oauth.schemas.d.ts +14 -1
  54. package/dist/tools/oauth/oauth.schemas.js +4 -1
  55. package/package.json +3 -3
@@ -0,0 +1,49 @@
1
+ import { AccountsService } from "../identity/accounts.js";
2
+ import type { UserPrincipal } from "../identity/principal.js";
3
+ import { SsoFlow } from "../identity/sso.js";
4
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
+ import { KernelDb } from "../infra/database/kernel-db.js";
6
+ import { OAuthFlow } from "../tools/oauth/flow.js";
7
+ import { HandoffTickets } from "./handoff-tickets.js";
8
+ /** The binding cookie values this browser already holds (either may be missing or invalid). */
9
+ export interface HandoffBrowserBindings {
10
+ oauth?: string | undefined;
11
+ sso?: string | undefined;
12
+ }
13
+ /**
14
+ * What a redeem answers, and which binding cookie the controller writes on this browser with
15
+ * which value: `oauth` (`cap_oauth`, the connector flow) or `sso` (`cap_sso`, the link flow).
16
+ */
17
+ export interface HandoffRedeemResult {
18
+ location: string;
19
+ binding: {
20
+ flow: "oauth" | "sso";
21
+ value: string;
22
+ };
23
+ }
24
+ /**
25
+ * Redeems a browser handoff ticket (shell external authorization spec §2) in the person's own
26
+ * signed-in browser: the ticket is taken first (GETDEL, one redeem wins across replicas), so a
27
+ * mismatch or a refusal spends it too. The flow then starts as a normal start would, in this
28
+ * browser, with the binding value the controller writes as this browser's cookie and the handoff
29
+ * done page as the return page.
30
+ */
31
+ export declare class HandoffService {
32
+ private readonly tickets;
33
+ private readonly accounts;
34
+ private readonly db;
35
+ private readonly config;
36
+ private readonly oauthFlow;
37
+ private readonly ssoFlow;
38
+ constructor(tickets: HandoffTickets, accounts: AccountsService, db: KernelDb, config: KernelConfigService, oauthFlow: OAuthFlow, ssoFlow: SsoFlow);
39
+ /**
40
+ * Unknown, used, expired or malformed ticket → `handoff.invalid`. The session's account is not
41
+ * the ticket's → `handoff.account_mismatch` naming the ticket's account (details
42
+ * `[{ login, displayName, email }]`, `login` its local login or null), and no flow starts. The
43
+ * ticket's return scheme is checked again (`handoff.scheme_not_allowed` once a super admin
44
+ * removed it). A connector ticket re-checks the org role as the start's org guard does, under
45
+ * the ticket's org scope (non-member or deleted org → `org.not_found`, role too low →
46
+ * `forbidden`), then starts the OAuth flow; a link ticket starts the SSO link intent.
47
+ */
48
+ redeem(ticket: string, principal: UserPrincipal, bindings: HandoffBrowserBindings): Promise<HandoffRedeemResult>;
49
+ }
@@ -0,0 +1,96 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { ApiError } from "../errors.js";
12
+ import { AccountsService } from "../identity/accounts.js";
13
+ import { SsoFlow, ssoBrowserBinding } from "../identity/sso.js";
14
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { withOrgScope } from "../infra/database/org-scope.js";
17
+ import { authorizeOrgAction } from "../orgs/org.guard.js";
18
+ import { browserBinding, OAuthFlow } from "../tools/oauth/flow.js";
19
+ import { assertReturnSchemeAllowed } from "./app-schemes.js";
20
+ import { HandoffTickets } from "./handoff-tickets.js";
21
+ /**
22
+ * Redeems a browser handoff ticket (shell external authorization spec §2) in the person's own
23
+ * signed-in browser: the ticket is taken first (GETDEL, one redeem wins across replicas), so a
24
+ * mismatch or a refusal spends it too. The flow then starts as a normal start would, in this
25
+ * browser, with the binding value the controller writes as this browser's cookie and the handoff
26
+ * done page as the return page.
27
+ */
28
+ let HandoffService = class HandoffService {
29
+ tickets;
30
+ accounts;
31
+ db;
32
+ config;
33
+ oauthFlow;
34
+ ssoFlow;
35
+ constructor(tickets, accounts, db, config, oauthFlow, ssoFlow) {
36
+ this.tickets = tickets;
37
+ this.accounts = accounts;
38
+ this.db = db;
39
+ this.config = config;
40
+ this.oauthFlow = oauthFlow;
41
+ this.ssoFlow = ssoFlow;
42
+ }
43
+ /**
44
+ * Unknown, used, expired or malformed ticket → `handoff.invalid`. The session's account is not
45
+ * the ticket's → `handoff.account_mismatch` naming the ticket's account (details
46
+ * `[{ login, displayName, email }]`, `login` its local login or null), and no flow starts. The
47
+ * ticket's return scheme is checked again (`handoff.scheme_not_allowed` once a super admin
48
+ * removed it). A connector ticket re-checks the org role as the start's org guard does, under
49
+ * the ticket's org scope (non-member or deleted org → `org.not_found`, role too low →
50
+ * `forbidden`), then starts the OAuth flow; a link ticket starts the SSO link intent.
51
+ */
52
+ async redeem(ticket, principal, bindings) {
53
+ const accountId = principal.account.id;
54
+ const rec = await this.tickets.take(ticket);
55
+ if (rec === null) {
56
+ throw new ApiError("handoff.invalid", "This authorization link has expired or was already used; start again in the app");
57
+ }
58
+ if (rec.accountId !== accountId) {
59
+ const [owner, logins] = await Promise.all([
60
+ this.accounts.get(rec.accountId),
61
+ this.accounts.localLogins([rec.accountId]),
62
+ ]);
63
+ throw new ApiError("handoff.account_mismatch", "This authorization link belongs to another account; sign in as that account or start again in the app", [
64
+ {
65
+ login: logins.get(rec.accountId) ?? null,
66
+ displayName: owner?.displayName ?? null,
67
+ email: owner?.email ?? null,
68
+ },
69
+ ]);
70
+ }
71
+ assertReturnSchemeAllowed(this.config.get(), rec.returnScheme);
72
+ if (rec.kind === "connector") {
73
+ const value = browserBinding(bindings.oauth);
74
+ // the entry point of this request's org work: the scope comes from the ticket
75
+ const { authorizationUrl } = await withOrgScope(rec.orgId, async () => {
76
+ await authorizeOrgAction(this.db.db, principal, rec.orgId, "connectors.use");
77
+ return this.oauthFlow.start(rec.orgId, rec.connectorId, accountId, rec.returnTo, value, rec);
78
+ });
79
+ return { location: authorizationUrl, binding: { flow: "oauth", value } };
80
+ }
81
+ const value = ssoBrowserBinding(bindings.sso);
82
+ // a link that cannot start answers the done page with `?error=<code>`: the same location
83
+ const location = await this.ssoFlow.start(rec.plugin, rec.returnTo, value, accountId, "link", rec);
84
+ return { location, binding: { flow: "sso", value } };
85
+ }
86
+ };
87
+ HandoffService = __decorate([
88
+ Injectable(),
89
+ __param(0, Inject(HandoffTickets)),
90
+ __param(1, Inject(AccountsService)),
91
+ __param(2, Inject(KernelDb)),
92
+ __param(3, Inject(KernelConfigService)),
93
+ __param(4, Inject(OAuthFlow)),
94
+ __param(5, Inject(SsoFlow))
95
+ ], HandoffService);
96
+ export { HandoffService };
@@ -56,6 +56,9 @@ import { ExtensionPointDefaultsController } from "../extensions/point-defaults.c
56
56
  import { FilesModule } from "../files/files.module.js";
57
57
  import { FilePreviewersController } from "../files/previewers.controller.js";
58
58
  import { GitModule } from "../git/git.module.js";
59
+ import { HandoffController } from "../handoff/handoff.controller.js";
60
+ import { HandoffModule } from "../handoff/handoff.module.js";
61
+ import { HandoffTicketsModule } from "../handoff/handoff-tickets.js";
59
62
  import { HtmlModule } from "../html/html.module.js";
60
63
  import { HtmlDocumentController } from "../html/html-document.controller.js";
61
64
  import { AccountAvatarController } from "../identity/account-avatar.controller.js";
@@ -176,6 +179,8 @@ const CONTROLLERS = [
176
179
  OAuthConnectController,
177
180
  OAuthCallbackController,
178
181
  SsoController,
182
+ // a shell's browser handoff redeemed in the person's signed-in browser
183
+ HandoffController,
179
184
  BindController,
180
185
  MeIdentitiesController,
181
186
  ChannelConnectionsController,
@@ -261,6 +266,9 @@ ApiModule = __decorate([
261
266
  SharesModule,
262
267
  // HTML files rendered as sandboxed documents (the document token and route)
263
268
  HtmlModule,
269
+ // the connect and link starts' handoff tickets (OAuthConnectController, SsoController)
270
+ HandoffTicketsModule,
271
+ HandoffModule,
264
272
  ],
265
273
  controllers: CONTROLLERS,
266
274
  providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
@@ -26,6 +26,7 @@ export declare const MetaResponseSchema: z.ZodObject<{
26
26
  }, z.core.$strip>>;
27
27
  }, z.core.$strip>;
28
28
  appRedirectUris: z.ZodArray<z.ZodString>;
29
+ appSchemes: z.ZodArray<z.ZodString>;
29
30
  }, z.core.$strip>;
30
31
  export type MetaResponse = z.infer<typeof MetaResponseSchema>;
31
32
  /**
@@ -11,6 +11,7 @@ import { DEVICE_DIAL_IN_PROTOCOL, DEVICE_PROTOCOL_VERSION, } from "@capybara-hq/
11
11
  import { Controller, Get, Header, Inject } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { DialInHandlers } from "../dial-in/handlers.js";
14
+ import { appSchemes } from "../handoff/app-schemes.js";
14
15
  import { Public } from "../identity/principal.js";
15
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
17
  import { PushProviderHost } from "../push/provider-host.js";
@@ -38,6 +39,11 @@ export const MetaResponseSchema = z.object({
38
39
  }),
39
40
  /** The redirect URIs app sign-in accepts (`auth.appRedirectUris`); [] while appSignIn is off. */
40
41
  appRedirectUris: z.array(z.string()),
42
+ /**
43
+ * The shell schemes a browser handoff's done page may link back to: those whose
44
+ * `<scheme>://auth/callback` is in `auth.appRedirectUris`; [] while appSignIn is off.
45
+ */
46
+ appSchemes: z.array(z.string()),
41
47
  });
42
48
  /** The protocol name `capybara-device` speaks (`capybara-device` of `capybara-device/<major>`). */
43
49
  const DEVICE_PROTOCOL_NAME = DEVICE_DIAL_IN_PROTOCOL.slice(0, DEVICE_DIAL_IN_PROTOCOL.indexOf("/"));
@@ -92,6 +98,7 @@ let MetaController = class MetaController {
92
98
  },
93
99
  // Not secret: an app that finds its own URI missing says so before opening the browser.
94
100
  appRedirectUris: appSignIn ? [...config.auth.appRedirectUris] : [],
101
+ appSchemes: appSchemes(config),
95
102
  };
96
103
  }
97
104
  /** A customised platform icon's versioned URL (the one the manifest uses); null for the default. */
@@ -1,5 +1,6 @@
1
1
  import type { FastifyReply, FastifyRequest } from "fastify";
2
2
  import { z } from "zod";
3
+ import { HandoffTickets } from "../handoff/handoff-tickets.js";
3
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
5
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
5
6
  import { type Account, AccountsService } from "./accounts.js";
@@ -15,10 +16,32 @@ declare const LinkBodySchema: z.ZodObject<{
15
16
  login: z.ZodString;
16
17
  password: z.ZodString;
17
18
  }, z.core.$strip>;
19
+ /**
20
+ * `POST /auth/sso/:plugin/start`: a link intent and the page to come back to. `handoff` (a native
21
+ * shell): finish the link in the system browser through a handoff ticket instead.
22
+ */
18
23
  declare const StartLinkBodySchema: z.ZodObject<{
19
24
  intent: z.ZodLiteral<"link">;
20
25
  returnTo: z.ZodOptional<z.ZodString>;
26
+ handoff: z.ZodOptional<z.ZodObject<{
27
+ returnScheme: z.ZodOptional<z.ZodString>;
28
+ }, z.core.$strict>>;
21
29
  }, z.core.$strip>;
30
+ /**
31
+ * The link start's answer: where the browser goes next (the source's authorize URL, or the page
32
+ * with `?error=<code>`), or with `handoff` the web page that starts the link in the system browser.
33
+ */
34
+ export type SsoStartLinkResponse = {
35
+ location: string;
36
+ } | {
37
+ handoffUrl: string;
38
+ };
39
+ /**
40
+ * Writes the SSO browser binding cookie `cap_sso` (HttpOnly, SameSite=Lax: the source's redirect
41
+ * back is a cross-site top-level GET, which Lax sends; Path only `/api/v1/auth/sso`). `secure` is
42
+ * {@link SsoFlow.cookieSecure}.
43
+ */
44
+ export declare function setSsoBindingCookie(reply: FastifyReply, binding: string, secure: boolean, maxAge?: number): void;
22
45
  /** What the link page shows (`GET /api/v1/auth/sso/link`). */
23
46
  export interface SsoLinkView {
24
47
  plugin: string;
@@ -44,7 +67,8 @@ export declare class SsoController {
44
67
  private readonly linkTickets;
45
68
  private readonly external;
46
69
  private readonly throttler;
47
- constructor(flow: SsoFlow, sessions: SessionService, accounts: AccountsService, config: KernelConfigService, linkTickets: SsoLinkTickets, external: ExternalIdentities, throttler: CredentialThrottler);
70
+ private readonly tickets;
71
+ constructor(flow: SsoFlow, sessions: SessionService, accounts: AccountsService, config: KernelConfigService, linkTickets: SsoLinkTickets, external: ExternalIdentities, throttler: CredentialThrottler, tickets: HandoffTickets);
48
72
  sources(): Promise<{
49
73
  sources: {
50
74
  plugin: string;
@@ -68,12 +92,12 @@ export declare class SsoController {
68
92
  * method it needs the CSRF header (global guard), so no other site can start it. The state
69
93
  * records the session's account; the callback must carry the same session. Writes the binding
70
94
  * cookie as the GET start does and returns where the browser goes next: the source's authorize
71
- * URL, or, on failure, the page with `?error=<code>`.
95
+ * URL, or, on failure, the page with `?error=<code>`. With `handoff` (a native shell, shell
96
+ * external authorization spec §1): no cookie and no state; a source on offer gets a handoff
97
+ * ticket and its web page, where the link starts when the person redeems it in the system
98
+ * browser; a source not on offer answers the same `?error=sso.unavailable` location.
72
99
  */
73
- startLink(plugin: string, body: z.infer<typeof StartLinkBodySchema>, principal: Principal, req: FastifyRequest, reply: FastifyReply): Promise<{
74
- location: string;
75
- }>;
76
- private setBindingCookie;
100
+ startLink(plugin: string, body: z.infer<typeof StartLinkBodySchema>, principal: Principal, req: FastifyRequest, reply: FastifyReply): Promise<SsoStartLinkResponse>;
77
101
  /**
78
102
  * The identity source's redirect back: state and binding cookie checked → the plugin verifies
79
103
  * the external identity → spec §4's decision ({@link SsoFlow.callback}). A sign-in creates a
@@ -10,6 +10,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Controller, Delete, Get, HttpCode, Inject, Param, Post, Query, Req, Res, } from "@nestjs/common";
11
11
  import { z } from "zod";
12
12
  import { ApiError } from "../errors.js";
13
+ import { assertReturnSchemeAllowed, HandoffRequestSchema } from "../handoff/app-schemes.js";
14
+ import { HandoffTickets } from "../handoff/handoff-tickets.js";
13
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
16
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
15
17
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
@@ -22,7 +24,7 @@ import { ExternalIdentities } from "./external.js";
22
24
  import { LinkedAccountsService, } from "./linked-accounts.js";
23
25
  import { CurrentPrincipal, Public, requireUser, SessionOnly } from "./principal.js";
24
26
  import { SessionService } from "./sessions.js";
25
- import { SSO_BINDING_COOKIE, SSO_COOKIE_PATH, SSO_STATE_TTL_SECONDS, SsoFlow, ssoBrowserBinding, withError, } from "./sso.js";
27
+ import { SSO_BINDING_COOKIE, SSO_COOKIE_PATH, SSO_STATE_TTL_SECONDS, SsoFlow, safeReturnTo, ssoBrowserBinding, withError, } from "./sso.js";
26
28
  import { linkExpired, SSO_LINK_PAGE_PATH, SSO_LINK_TTL_SECONDS, SsoLinkTickets, } from "./sso-link.js";
27
29
  const LinkBodySchema = z.object({
28
30
  ticket: z.string().max(100),
@@ -31,12 +33,31 @@ const LinkBodySchema = z.object({
31
33
  });
32
34
  class LinkBody extends createZodDto(LinkBodySchema, "SsoLinkBody") {
33
35
  }
36
+ /**
37
+ * `POST /auth/sso/:plugin/start`: a link intent and the page to come back to. `handoff` (a native
38
+ * shell): finish the link in the system browser through a handoff ticket instead.
39
+ */
34
40
  const StartLinkBodySchema = z.object({
35
41
  intent: z.literal("link"),
36
42
  returnTo: z.string().max(2000).optional(),
43
+ handoff: HandoffRequestSchema.optional(),
37
44
  });
38
45
  class StartLinkBody extends createZodDto(StartLinkBodySchema, "SsoStartLinkBody") {
39
46
  }
47
+ /**
48
+ * Writes the SSO browser binding cookie `cap_sso` (HttpOnly, SameSite=Lax: the source's redirect
49
+ * back is a cross-site top-level GET, which Lax sends; Path only `/api/v1/auth/sso`). `secure` is
50
+ * {@link SsoFlow.cookieSecure}.
51
+ */
52
+ export function setSsoBindingCookie(reply, binding, secure, maxAge = SSO_STATE_TTL_SECONDS) {
53
+ reply.setCookie(SSO_BINDING_COOKIE, binding, {
54
+ path: SSO_COOKIE_PATH,
55
+ httpOnly: true,
56
+ sameSite: "lax",
57
+ secure,
58
+ maxAge,
59
+ });
60
+ }
40
61
  const MAX_QUERY_KEYS = 50;
41
62
  const MAX_QUERY_VALUE = 4096;
42
63
  /** 查询参数只取单值字符串(重复参数 / 数组 / 超长值丢弃)。 */
@@ -60,7 +81,8 @@ let SsoController = class SsoController {
60
81
  linkTickets;
61
82
  external;
62
83
  throttler;
63
- constructor(flow, sessions, accounts, config, linkTickets, external, throttler) {
84
+ tickets;
85
+ constructor(flow, sessions, accounts, config, linkTickets, external, throttler, tickets) {
64
86
  this.flow = flow;
65
87
  this.sessions = sessions;
66
88
  this.accounts = accounts;
@@ -68,6 +90,7 @@ let SsoController = class SsoController {
68
90
  this.linkTickets = linkTickets;
69
91
  this.external = external;
70
92
  this.throttler = throttler;
93
+ this.tickets = tickets;
71
94
  }
72
95
  async sources() {
73
96
  return { sources: await this.flow.sources() };
@@ -89,7 +112,7 @@ let SsoController = class SsoController {
89
112
  }
90
113
  const binding = ssoBrowserBinding(req.cookies[SSO_BINDING_COOKIE]);
91
114
  const location = await this.flow.start(plugin, typeof returnTo === "string" ? returnTo : undefined, binding);
92
- this.setBindingCookie(reply, binding, SSO_STATE_TTL_SECONDS);
115
+ setSsoBindingCookie(reply, binding, this.flow.cookieSecure());
93
116
  await reply.header("cache-control", "no-store").redirect(location, 302);
94
117
  }
95
118
  /**
@@ -97,25 +120,35 @@ let SsoController = class SsoController {
97
120
  * method it needs the CSRF header (global guard), so no other site can start it. The state
98
121
  * records the session's account; the callback must carry the same session. Writes the binding
99
122
  * cookie as the GET start does and returns where the browser goes next: the source's authorize
100
- * URL, or, on failure, the page with `?error=<code>`.
123
+ * URL, or, on failure, the page with `?error=<code>`. With `handoff` (a native shell, shell
124
+ * external authorization spec §1): no cookie and no state; a source on offer gets a handoff
125
+ * ticket and its web page, where the link starts when the person redeems it in the system
126
+ * browser; a source not on offer answers the same `?error=sso.unavailable` location.
101
127
  */
102
128
  async startLink(plugin, body, principal, req, reply) {
103
129
  const p = requireUser(principal);
130
+ reply.header("cache-control", "no-store");
131
+ if (body.handoff !== undefined) {
132
+ const returnScheme = body.handoff.returnScheme;
133
+ assertReturnSchemeAllowed(this.config.get(), returnScheme);
134
+ const returnTo = safeReturnTo(body.returnTo);
135
+ if (!(await this.flow.linkAvailable(plugin))) {
136
+ return { location: this.flow.webUrl(withError(returnTo, "sso.unavailable")) };
137
+ }
138
+ const ticket = await this.tickets.create({
139
+ kind: "identity-link",
140
+ accountId: p.account.id,
141
+ plugin,
142
+ returnTo,
143
+ ...(returnScheme !== undefined && { returnScheme }),
144
+ });
145
+ return { handoffUrl: this.tickets.url(ticket) };
146
+ }
104
147
  const binding = ssoBrowserBinding(req.cookies[SSO_BINDING_COOKIE]);
105
148
  const location = await this.flow.start(plugin, body.returnTo, binding, p.account.id, body.intent);
106
- this.setBindingCookie(reply, binding, SSO_STATE_TTL_SECONDS);
107
- reply.header("cache-control", "no-store");
149
+ setSsoBindingCookie(reply, binding, this.flow.cookieSecure());
108
150
  return { location };
109
151
  }
110
- setBindingCookie(reply, binding, maxAge) {
111
- reply.setCookie(SSO_BINDING_COOKIE, binding, {
112
- path: SSO_COOKIE_PATH,
113
- httpOnly: true,
114
- sameSite: "lax",
115
- secure: this.flow.cookieSecure(),
116
- maxAge,
117
- });
118
- }
119
152
  /**
120
153
  * The identity source's redirect back: state and binding cookie checked → the plugin verifies
121
154
  * the external identity → spec §4's decision ({@link SsoFlow.callback}). A sign-in creates a
@@ -137,7 +170,7 @@ let SsoController = class SsoController {
137
170
  }
138
171
  else if (r.kind === "link_page") {
139
172
  // the binding value is the one the state was checked against
140
- this.setBindingCookie(reply, binding, SSO_LINK_TTL_SECONDS);
173
+ setSsoBindingCookie(reply, binding, this.flow.cookieSecure(), SSO_LINK_TTL_SECONDS);
141
174
  const target = this.flow.webUrl(`${SSO_LINK_PAGE_PATH}?ticket=${encodeURIComponent(r.ticket)}`);
142
175
  await reply.header("cache-control", "no-store").redirect(target, 302);
143
176
  return;
@@ -302,7 +335,8 @@ SsoController = __decorate([
302
335
  __param(3, Inject(KernelConfigService)),
303
336
  __param(4, Inject(SsoLinkTickets)),
304
337
  __param(5, Inject(ExternalIdentities)),
305
- __param(6, Inject(CredentialThrottler))
338
+ __param(6, Inject(CredentialThrottler)),
339
+ __param(7, Inject(HandoffTickets))
306
340
  ], SsoController);
307
341
  export { SsoController };
308
342
  const identityTaken = () => new ApiError("identity.taken", "This external identity is already linked to another account");
@@ -1,6 +1,7 @@
1
1
  import { type IdentitySource, type Logger } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { ExtensionRegistry } from "../extensions/registry.js";
4
+ import { type HandoffRecord } from "../handoff/handoff-paths.js";
4
5
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
6
  import { ExternalIdentities } from "./external.js";
6
7
  import { LoginSourcesService } from "./login-sources.js";
@@ -94,6 +95,11 @@ export declare class SsoFlow {
94
95
  private entry;
95
96
  /** The identity source of `plugin` when its login source is on offer (see {@link sources}). */
96
97
  provider(plugin: string): Promise<IdentitySource | undefined>;
98
+ /**
99
+ * Whether a link intent of `plugin` can start now: its login source is on offer and
100
+ * `http.publicUrl` is set (otherwise {@link start} answers `sso.unavailable`).
101
+ */
102
+ linkAvailable(plugin: string): Promise<boolean>;
97
103
  private redirectUri;
98
104
  /** 绑定 Cookie 是否加 Secure:`auth.cookieSecure`,或 `http.publicUrl` 是 https(浏览器经 https 访问)。 */
99
105
  cookieSecure(): boolean;
@@ -107,9 +113,11 @@ export declare class SsoFlow {
107
113
  * the sign-in page; a link intent's back to its page with `?error=<code>`. A link intent needs
108
114
  * the web session's account and must come from a CSRF-protected request (the controller's
109
115
  * `POST …/start`; a cross-site top-level GET carries the Lax session cookie, so a GET start never
110
- * links). `binding` is this browser's binding value (the controller writes the cookie).
116
+ * links). `binding` is this browser's binding value (the controller writes the cookie). With
117
+ * `handoff` (a browser handoff redeemed in this browser), the return page is the handoff done
118
+ * page the kernel builds from the ticket's record, and `returnTo` is ignored.
111
119
  */
112
- start(plugin: string, returnTo: string | undefined, binding: string, sessionAccountId?: string, intent?: SsoIntent): Promise<string>;
120
+ start(plugin: string, returnTo: string | undefined, binding: string, sessionAccountId?: string, intent?: SsoIntent, handoff?: HandoffRecord): Promise<string>;
113
121
  /**
114
122
  * Handles the identity source's redirect back. The state is read and deleted in one step (it can
115
123
  * never be used again, whatever the outcome); a state that belongs to another plugin →
@@ -12,6 +12,7 @@ import { isIdentitySourceRefused } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { ExtensionRegistry } from "../extensions/registry.js";
15
+ import { handoffDonePath } from "../handoff/handoff-paths.js";
15
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
17
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
17
18
  import { isSafeReturnPath } from "../tools/oauth/flow-paths.js";
@@ -105,6 +106,15 @@ let SsoFlow = class SsoFlow {
105
106
  async provider(plugin) {
106
107
  return (await this.entry(plugin))?.source;
107
108
  }
109
+ /**
110
+ * Whether a link intent of `plugin` can start now: its login source is on offer and
111
+ * `http.publicUrl` is set (otherwise {@link start} answers `sso.unavailable`).
112
+ */
113
+ async linkAvailable(plugin) {
114
+ if (!this.config.get().http.publicUrl)
115
+ return false;
116
+ return (await this.provider(plugin)) !== undefined;
117
+ }
108
118
  redirectUri(plugin) {
109
119
  const base = (this.config.get().http.publicUrl ?? "").replace(/\/+$/, "");
110
120
  return `${base}${ssoCallbackPath(plugin)}`;
@@ -129,10 +139,12 @@ let SsoFlow = class SsoFlow {
129
139
  * the sign-in page; a link intent's back to its page with `?error=<code>`. A link intent needs
130
140
  * the web session's account and must come from a CSRF-protected request (the controller's
131
141
  * `POST …/start`; a cross-site top-level GET carries the Lax session cookie, so a GET start never
132
- * links). `binding` is this browser's binding value (the controller writes the cookie).
142
+ * links). `binding` is this browser's binding value (the controller writes the cookie). With
143
+ * `handoff` (a browser handoff redeemed in this browser), the return page is the handoff done
144
+ * page the kernel builds from the ticket's record, and `returnTo` is ignored.
133
145
  */
134
- async start(plugin, returnTo, binding, sessionAccountId, intent = "signin") {
135
- const back = safeReturnTo(returnTo);
146
+ async start(plugin, returnTo, binding, sessionAccountId, intent = "signin", handoff) {
147
+ const back = handoff !== undefined ? handoffDonePath(handoff) : safeReturnTo(returnTo);
136
148
  const fail = (code) => intent === "link" ? this.webUrl(withError(back, code)) : this.loginError(code);
137
149
  if (intent === "link" && sessionAccountId === undefined) {
138
150
  return this.loginError("sso.session_mismatch");
@@ -20,7 +20,7 @@ import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
20
20
  import { PRESENCE_INTERVAL_MS } from "./infra/presence/replica-presence.js";
21
21
  import type { KernelQueueName } from "./infra/queue/queue-names.js";
22
22
  import { PUSH_SEND_TIMEOUT_MS } from "./push/delivery.js";
23
- import { PROJECT_KNOWLEDGE_TIMEOUT } from "./runtime/project/knowledge.service.js";
23
+ import { PROJECT_KNOWLEDGE_TIMEOUT, type ProjectKnowledgeTimeouts } from "./runtime/project/knowledge.service.js";
24
24
  import { LIST_MODELS_TIMEOUT } from "./runtime/providers.js";
25
25
  import { RUN_CONTEXT_CLOCK } from "./runtime/run-context.service.js";
26
26
  import { ENSURE_RUN_FAILS } from "./runtime/run-queue.js";
@@ -58,8 +58,8 @@ import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
58
58
  * - `OUTBOX_FAST_PATH_SETTLED`: receives each detached outbox fast-path pass (a test awaits them);
59
59
  * - `ENSURE_RUN_FAILS`: returns true to make `RunQueue.ensureRun` throw (Redis unreachable, or the
60
60
  * direct call after a commit skipped by a crash);
61
- * - `PROJECT_KNOWLEDGE_TIMEOUT`: the run-start read of a bound project's time limit, read at every
62
- * read (a test shortens it for one run);
61
+ * - `PROJECT_KNOWLEDGE_TIMEOUT`: the run-start read of a bound project's time limits (the device's
62
+ * start, the read), read at every read (a test shortens them for one run);
63
63
  * - `PUSH_SEND_TIMEOUT_MS`: one push send's time limit, read at every send (a test shortens it
64
64
  * for a hanging provider);
65
65
  * - `BACKGROUND_STOP_ATTEMPT_MS`: one exact background task stop attempt's time limit, read at
@@ -99,7 +99,7 @@ interface KernelSeams {
99
99
  [OUTBOX_FAST_PATH_SETTLED]: (pass: Promise<void>) => void;
100
100
  [ENSURE_RUN_FAILS]: () => boolean;
101
101
  [SCOPE_ORG_CHUNK_SIZE]: number;
102
- [PROJECT_KNOWLEDGE_TIMEOUT]: () => number;
102
+ [PROJECT_KNOWLEDGE_TIMEOUT]: () => ProjectKnowledgeTimeouts;
103
103
  [PROMPT_SUGGESTION_TIMEOUT]: () => number;
104
104
  [PUSH_SEND_TIMEOUT_MS]: () => number;
105
105
  [BACKGROUND_STOP_ATTEMPT_MS]: () => number;
package/dist/overrides.js CHANGED
@@ -17,7 +17,7 @@ import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
17
17
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
18
18
  import { PRESENCE_INTERVAL_MS } from "./infra/presence/replica-presence.js";
19
19
  import { PUSH_SEND_TIMEOUT_MS } from "./push/delivery.js";
20
- import { PROJECT_KNOWLEDGE_TIMEOUT } from "./runtime/project/knowledge.service.js";
20
+ import { PROJECT_KNOWLEDGE_TIMEOUT, } from "./runtime/project/knowledge.service.js";
21
21
  import { LIST_MODELS_TIMEOUT } from "./runtime/providers.js";
22
22
  import { RUN_CONTEXT_CLOCK } from "./runtime/run-context.service.js";
23
23
  import { ENSURE_RUN_FAILS } from "./runtime/run-queue.js";
@@ -502,6 +502,11 @@ export const PLATFORM_EXCLUSIONS = [
502
502
  category: "human-only",
503
503
  reason: "A person's own sign-in with a password: completes a pending link and signs in",
504
504
  },
505
+ {
506
+ route: "POST /api/v1/auth/handoffs/redeem",
507
+ category: "human-only",
508
+ reason: "Redeems a shell's browser handoff in the person's own signed-in browser; it starts an OAuth or SSO flow there",
509
+ },
505
510
  {
506
511
  route: "GET /api/v1/bind/:token",
507
512
  category: "human-only",
@@ -687,8 +687,10 @@ let ConnectorsOperations = class ConnectorsOperations {
687
687
  example: { connectorId: EXAMPLE_ID },
688
688
  authz: { orgAction: "connectors.use" },
689
689
  mirrors: ["POST /api/v1/orgs/:orgId/connectors/:connectorId/connect"],
690
- // the web card starts the flow from the person's session and returns to the conversation
691
- omits: ["returnTo"],
690
+ // the web card starts the flow from the person's session and returns to the conversation;
691
+ // `handoff` is a shell's browser handoff; the Platform card starts the flow in the person's
692
+ // web session
693
+ omits: ["returnTo", "handoff"],
692
694
  confirm: "read",
693
695
  errors: [
694
696
  { code: "connector.not_found", next: "Check the connector id with connectors.list." },
@@ -35,10 +35,13 @@ export interface ForcedCompaction {
35
35
  * The manual compaction a compact run executes (context compaction spec §4.7). It prepares the same
36
36
  * environment a model step has (the events, the effective definition's tools, the org's compaction
37
37
  * settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
38
- * `enabled: false` and the failure backoff are bypassed, the compaction plan is still required.
38
+ * `enabled: false` and the failure backoff are bypassed, the compaction plan is still required, with
39
+ * the manual rule (`manual: true`: every turn before the latest summarized, about a fifth of the
40
+ * window of the latest turn kept; maintainer decision 2026-11-28).
39
41
  *
40
- * The run writes only `compaction_summary` / `compaction_failed` + the summary calls' `usage`, with
41
- * `step: 0`; no user message and no model step.
42
+ * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` + the
43
+ * summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize (maintainer
44
+ * decision 2026-11-28); no user message and no model step.
42
45
  */
43
46
  export declare class CompactionService {
44
47
  private readonly steps;
@@ -17,10 +17,13 @@ import { RunSteps } from "./run-steps.js";
17
17
  * The manual compaction a compact run executes (context compaction spec §4.7). It prepares the same
18
18
  * environment a model step has (the events, the effective definition's tools, the org's compaction
19
19
  * settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
20
- * `enabled: false` and the failure backoff are bypassed, the compaction plan is still required.
20
+ * `enabled: false` and the failure backoff are bypassed, the compaction plan is still required, with
21
+ * the manual rule (`manual: true`: every turn before the latest summarized, about a fifth of the
22
+ * window of the latest turn kept; maintainer decision 2026-11-28).
21
23
  *
22
- * The run writes only `compaction_summary` / `compaction_failed` + the summary calls' `usage`, with
23
- * `step: 0`; no user message and no model step.
24
+ * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` + the
25
+ * summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize (maintainer
26
+ * decision 2026-11-28); no user message and no model step.
24
27
  */
25
28
  let CompactionService = class CompactionService {
26
29
  steps;
@@ -59,9 +62,7 @@ let CompactionService = class CompactionService {
59
62
  // step's request would (spec §4.7)
60
63
  const tools = stepToolsOf(await resolveAgentTools(deps, stepInput, events), stepInput, deps);
61
64
  const compaction = await this.settings.resolve(input.orgId);
62
- const out = await runCompaction(deps, stepInput, events, this.config.get().runtime, compaction, tools, {
63
- force: true,
64
- });
65
+ const out = await runCompaction(deps, stepInput, events, this.config.get().runtime, compaction, tools, { force: true, manual: true });
65
66
  return { summarySeq: out.summarySeq, failed: out.failed };
66
67
  }
67
68
  };