@capybara-hq/kernel 0.1.0-rc.62 → 0.1.0-rc.64

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 (120) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/app.d.ts +2 -0
  3. package/dist/catalog/catalog.service.d.ts +13 -0
  4. package/dist/catalog/catalog.service.js +17 -8
  5. package/dist/catalog/git-source.d.ts +8 -0
  6. package/dist/catalog/git-source.js +14 -6
  7. package/dist/catalog/marketplaces.controller.d.ts +3 -2
  8. package/dist/catalog/marketplaces.controller.js +5 -2
  9. package/dist/catalog/marketplaces.schemas.d.ts +7 -0
  10. package/dist/catalog/marketplaces.schemas.js +13 -0
  11. package/dist/catalog/marketplaces.service.d.ts +65 -11
  12. package/dist/catalog/marketplaces.service.js +208 -30
  13. package/dist/catalog/org-catalog.schemas.d.ts +1 -1
  14. package/dist/catalog/org-catalog.schemas.js +1 -1
  15. package/dist/channels/actions.d.ts +2 -5
  16. package/dist/channels/actions.js +20 -8
  17. package/dist/channels/cards.d.ts +4 -3
  18. package/dist/channels/cards.js +6 -4
  19. package/dist/channels/outbound.js +3 -2
  20. package/dist/config/schema.d.ts +2 -0
  21. package/dist/config/schema.js +22 -2
  22. package/dist/conversations/approval-profile.d.ts +30 -0
  23. package/dist/conversations/approval-profile.js +62 -0
  24. package/dist/conversations/conversations.service.js +0 -2
  25. package/dist/conversations/events.d.ts +43 -0
  26. package/dist/conversations/events.js +52 -0
  27. package/dist/conversations/permission-profiles.controller.d.ts +3 -2
  28. package/dist/conversations/permission-profiles.service.d.ts +3 -2
  29. package/dist/conversations/permission-profiles.service.js +12 -8
  30. package/dist/db/kernel-schema.d.ts +8 -2
  31. package/dist/errors.d.ts +7 -0
  32. package/dist/errors.js +7 -0
  33. package/dist/extensions/bootstrap-defaults.d.ts +24 -0
  34. package/dist/extensions/bootstrap-defaults.js +78 -0
  35. package/dist/extensions/bootstrap-extra.d.ts +74 -0
  36. package/dist/extensions/bootstrap-extra.js +131 -0
  37. package/dist/extensions/bootstrap.d.ts +77 -13
  38. package/dist/extensions/bootstrap.js +282 -48
  39. package/dist/identity/initial-passwords.controller.d.ts +8 -6
  40. package/dist/identity/initial-passwords.controller.js +13 -7
  41. package/dist/identity/initial-passwords.d.ts +22 -13
  42. package/dist/identity/initial-passwords.js +25 -29
  43. package/dist/identity/settings.d.ts +10 -0
  44. package/dist/identity/settings.js +46 -0
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.js +3 -0
  47. package/dist/kernel.module.js +3 -0
  48. package/dist/lifecycle/kernel-lifecycle.d.ts +7 -1
  49. package/dist/lifecycle/kernel-lifecycle.js +69 -16
  50. package/dist/local-devices/relay.js +3 -1
  51. package/dist/models/images.js +5 -4
  52. package/dist/platform/connector-person-fields.js +2 -2
  53. package/dist/platform/exclusions.js +4 -4
  54. package/dist/platform/method.js +1 -1
  55. package/dist/platform/operation.d.ts +9 -7
  56. package/dist/platform/operation.js +1 -1
  57. package/dist/platform/ops/accounts.ops.d.ts +1 -1
  58. package/dist/platform/ops/accounts.ops.js +3 -3
  59. package/dist/platform/ops/channels.ops.d.ts +1 -1
  60. package/dist/platform/ops/channels.ops.js +2 -2
  61. package/dist/platform/ops/connectors.ops.d.ts +2 -2
  62. package/dist/platform/ops/connectors.ops.js +8 -8
  63. package/dist/platform/ops/extensions-admin.ops.d.ts +1 -1
  64. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  65. package/dist/platform/ops/extensions.ops.d.ts +1 -1
  66. package/dist/platform/ops/extensions.ops.js +4 -4
  67. package/dist/platform/ops/marketplaces.ops.js +27 -4
  68. package/dist/platform/ops/org-plugins.ops.js +2 -2
  69. package/dist/platform/ops/orgs.ops.d.ts +1 -1
  70. package/dist/platform/ops/orgs.ops.js +3 -3
  71. package/dist/platform/ops/plugins.ops.d.ts +1 -1
  72. package/dist/platform/ops/plugins.ops.js +2 -2
  73. package/dist/platform/person-fields.d.ts +4 -3
  74. package/dist/platform/person-fields.js +6 -5
  75. package/dist/platform/sealed-inputs.d.ts +2 -2
  76. package/dist/platform/sealed-inputs.js +2 -2
  77. package/dist/platform/sealed-reveals.controller.d.ts +5 -8
  78. package/dist/platform/sealed-reveals.controller.js +8 -8
  79. package/dist/platform/sealed-reveals.d.ts +19 -17
  80. package/dist/platform/sealed-reveals.js +30 -33
  81. package/dist/runtime/context/build.js +3 -0
  82. package/dist/runtime/context/compaction.js +2 -0
  83. package/dist/runtime/waits.js +3 -2
  84. package/dist/sandbox/operation-authority.js +16 -15
  85. package/dist/sandbox/operation-intents.js +2 -2
  86. package/dist/sandbox/permission-availability.d.ts +49 -3
  87. package/dist/sandbox/permission-availability.js +61 -6
  88. package/dist/sandbox/permission-call-types.d.ts +3 -0
  89. package/dist/sandbox/permission-facts.d.ts +29 -1
  90. package/dist/sandbox/permission-facts.js +29 -6
  91. package/dist/sandbox/review/classifier.d.ts +72 -2
  92. package/dist/sandbox/review/classifier.js +113 -38
  93. package/dist/sandbox/review/index.d.ts +2 -2
  94. package/dist/sandbox/review/index.js +1 -1
  95. package/dist/sandbox/review/review.service.d.ts +1 -4
  96. package/dist/sandbox/review/review.service.js +4 -33
  97. package/dist/setup/setup-guides.service.js +1 -1
  98. package/dist/tools/approvals.service.d.ts +71 -16
  99. package/dist/tools/approvals.service.js +139 -13
  100. package/dist/tools/builtins/builtin-tools.d.ts +1 -1
  101. package/dist/tools/builtins/builtin-tools.js +12 -6
  102. package/dist/tools/builtins/platform.d.ts +15 -11
  103. package/dist/tools/builtins/platform.js +49 -39
  104. package/dist/tools/builtins/sandbox/bash.d.ts +1 -1
  105. package/dist/tools/builtins/sandbox/bash.js +32 -14
  106. package/dist/tools/builtins/sandbox/common.d.ts +12 -3
  107. package/dist/tools/builtins/sandbox/common.js +29 -5
  108. package/dist/tools/connectors.schemas.d.ts +1 -1
  109. package/dist/tools/connectors.schemas.js +1 -1
  110. package/dist/tools/pipeline.d.ts +70 -10
  111. package/dist/tools/pipeline.js +356 -48
  112. package/dist/tools/policy.d.ts +4 -3
  113. package/dist/tools/policy.js +6 -6
  114. package/dist/tools/registry.d.ts +25 -9
  115. package/dist/tools/tool-review.d.ts +113 -0
  116. package/dist/tools/tool-review.js +303 -0
  117. package/dist/tools/tools.module.js +6 -0
  118. package/package.json +4 -4
  119. package/src/migrations/0174_marketplace_managed_username.sql +4 -0
  120. package/src/migrations/0175_secure_input_kind.sql +8 -0
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { CATALOG_ITEM_NAME_RE, marketplaceEntryDeprecation, marketplaceEntryVersion, PLUGIN_MANIFEST_FILE, parseMarketplaceManifest, parsePluginManifest, pluginDescription, SDK_VERSION, SEMVER_VERSION_RE, } from "@capybara-hq/plugin-sdk";
11
+ import { CATALOG_ITEM_NAME_RE, GIT_USERNAME_RE, marketplaceEntryDeprecation, marketplaceEntryVersion, PLUGIN_MANIFEST_FILE, parseMarketplaceManifest, parsePluginManifest, pluginDescription, SDK_VERSION, SEMVER_VERSION_RE, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import semver from "semver";
@@ -39,6 +39,8 @@ const OFFICIAL_MARKETPLACE_NAME = "Capybara official marketplace";
39
39
  /** 企业清单的可选令牌:secrets 的 namespace `kernel`、org `_deployment`、键 `catalog-token:<id>`(preflight #65)。 */
40
40
  const SECRETS_NAMESPACE = "kernel";
41
41
  const tokenKey = (id) => `catalog-token:${id}`;
42
+ /** The id prefix of a marketplace the deployment config owns (`config:<name>`). */
43
+ export const CONFIG_MARKETPLACE_PREFIX = "config:";
42
44
  /** 拉取一份清单的超时。 */
43
45
  export const MARKETPLACE_FETCH_TIMEOUT_MS = 30_000;
44
46
  /**
@@ -72,6 +74,7 @@ export function pluginNameFrom(segment) {
72
74
  return name === "" ? "plugin" : name;
73
75
  }
74
76
  const builtinErr = (what) => new ApiError("marketplace.builtin", `The official marketplace is configured in marketplaces.official.*; it cannot be ${what} here (only enabled or disabled)`);
77
+ const configManagedErr = (what) => new ApiError("marketplace.config_managed", `This marketplace is configured by the deployment (bootstrap.extraManifest); it cannot be ${what} here (only enabled or disabled)`);
75
78
  /** Entry versions newest first; `''` (no version) last. */
76
79
  const bySemverDescOrNone = (a, b) => a === b ? 0 : a === "" ? 1 : b === "" ? -1 : compareVersions(b, a);
77
80
  const gitDetailOf = (v) => {
@@ -461,6 +464,115 @@ let MarketplacesService = class MarketplacesService {
461
464
  }))
462
465
  .execute();
463
466
  }
467
+ /**
468
+ * Upserts the marketplaces of the extra bootstrap manifest (spec 2026-11-20 §5): one row
469
+ * `config:<name>` each with `managed = 'config'`; name, URL (its form per
470
+ * {@link marketplaceForm}), ref and username follow the file, the admin's enable switch is left
471
+ * alone, and a changed URL, form or ref drops the ETag and the last commit. The token stays in
472
+ * `marketplaces.tokens[name]`, never in the secrets table (a token an admin set while the row
473
+ * was demoted is deleted when it becomes managed again). A managed row whose name left the
474
+ * file is kept as an ordinary custom marketplace (`managed = NULL`, so no token). Called by
475
+ * every replica at start; idempotent. An invalid entry -> {@link ConfigError}, nothing written.
476
+ * `undefined` (this process has no extra manifest) writes nothing and demotes nothing: such a
477
+ * process may have read no managed row before another replica's sync committed (ruling R16), so
478
+ * only a configured extra manifest (an empty one included) removes a marketplace. Returns the
479
+ * names of the rows it demoted.
480
+ */
481
+ async syncExtraFromConfig(marketplaces) {
482
+ if (marketplaces === undefined)
483
+ return [];
484
+ const rows = marketplaces
485
+ .map((m) => this.extraMarketplaceRow(m))
486
+ // one lock order for every replica
487
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
488
+ const ids = rows.map((r) => r.id);
489
+ if (new Set(ids).size !== ids.length) {
490
+ throw new ConfigError("invalid configuration:\n - bootstrap.extraManifest: marketplace names must be unique");
491
+ }
492
+ const t = this.db;
493
+ const same = sql `marketplaces.url = excluded.url AND marketplaces.form = excluded.form AND marketplaces.ref IS NOT DISTINCT FROM excluded.ref`;
494
+ for (const r of rows) {
495
+ await t
496
+ .insertInto("marketplaces")
497
+ .values({ ...r, mirrors: "[]", builtin: false, enabled: true, managed: "config" })
498
+ .onConflict((oc) => oc.column("id").doUpdateSet({
499
+ name: r.name,
500
+ url: r.url,
501
+ form: r.form,
502
+ ref: r.ref,
503
+ username: r.username,
504
+ mirrors: "[]",
505
+ builtin: false,
506
+ managed: "config",
507
+ etag: sql `CASE WHEN ${same} THEN marketplaces.etag ELSE NULL END`,
508
+ last_commit: sql `CASE WHEN ${same} THEN marketplaces.last_commit ELSE NULL END`,
509
+ }))
510
+ .execute();
511
+ // A managed row's token lives only in the config: drop one an admin set while the row was
512
+ // demoted, so it never follows the file's URL to another origin
513
+ await this.secrets().delete(DEPLOYMENT_SECRETS_ORG, tokenKey(r.id));
514
+ }
515
+ let gone = t.updateTable("marketplaces").set({ managed: null }).where("managed", "=", "config");
516
+ if (ids.length > 0)
517
+ gone = gone.where("id", "not in", ids);
518
+ const demoted = await gone.returning("name").execute();
519
+ for (const r of rows)
520
+ await this.backfillBootstrapItems(r.id);
521
+ return demoted.map((d) => d.name).sort();
522
+ }
523
+ /**
524
+ * Names the managed marketplace on the platform items the bootstrap step imported from it before
525
+ * its row existed (`capybara bootstrap` runs before the first start, and `marketplace_id` is a
526
+ * foreign key): a live item without a marketplace whose latest version came from the bootstrap
527
+ * with a `source_ref` of `<id>:…` (a git entry of that marketplace). Then the catalog tracks its
528
+ * updates like an import from the marketplace. Idempotent.
529
+ */
530
+ async backfillBootstrapItems(id) {
531
+ const prefix = `${id.replace(/[\\%_]/g, (c) => `\\${c}`)}:%`;
532
+ await this.db
533
+ .updateTable("catalog_items as i")
534
+ .set({ marketplace_id: id })
535
+ .where("i.owner_org_id", "is", null)
536
+ .where("i.marketplace_id", "is", null)
537
+ .where("i.deleted_at", "is", null)
538
+ .where((eb) => eb.exists(eb
539
+ .selectFrom("catalog_item_versions as v")
540
+ .select("v.item_id")
541
+ .whereRef("v.item_id", "=", "i.id")
542
+ .whereRef("v.version", "=", "i.latest_version")
543
+ .where("v.source", "=", "bootstrap")
544
+ .where("v.source_ref", "like", prefix)))
545
+ .execute();
546
+ }
547
+ /** The row of one extra-manifest marketplace, checked as an admin add is (else ConfigError). */
548
+ extraMarketplaceRow(m) {
549
+ const bad = (what) => new ConfigError(`invalid configuration:\n - bootstrap.extraManifest marketplaces: ${what}`);
550
+ if (!CATALOG_ITEM_NAME_RE.test(m.name)) {
551
+ throw bad(`name ${JSON.stringify(m.name)} must match ^[a-z0-9][a-z0-9-]{0,63}$`);
552
+ }
553
+ if (m.username !== undefined && m.username !== "" && !GIT_USERNAME_RE.test(m.username)) {
554
+ throw bad(`${m.name}: username must match ^[A-Za-z0-9._-]{1,64}$`);
555
+ }
556
+ const { form, url } = marketplaceForm(m.url);
557
+ const ref = m.ref ?? null;
558
+ try {
559
+ this.checkUrls(url, []);
560
+ this.checkGitFields(form, ref, []);
561
+ }
562
+ catch (e) {
563
+ if (e instanceof ApiError)
564
+ throw bad(`${m.name}: ${e.message}`);
565
+ throw e;
566
+ }
567
+ return {
568
+ id: `${CONFIG_MARKETPLACE_PREFIX}${m.name}`,
569
+ name: m.name,
570
+ url,
571
+ form,
572
+ ref,
573
+ username: m.username === undefined || m.username === "" ? null : m.username,
574
+ };
575
+ }
464
576
  /** 全部来源(official 在前,其余按创建时间)。 */
465
577
  async list() {
466
578
  const rows = (await this.db
@@ -494,8 +606,9 @@ let MarketplacesService = class MarketplacesService {
494
606
  this.checkGitFields(form, input.ref ?? null, input.mirrors ?? []);
495
607
  if (input.token !== undefined)
496
608
  this.checkToken(input.token);
609
+ const username = this.checkUsername(input.username);
497
610
  const id = randomUUID();
498
- await this.writeAdd(actor, id, { ...input, name, form, url }, opts);
611
+ await this.writeAdd(actor, id, { ...input, name, form, url, username }, opts);
499
612
  return this.get(id);
500
613
  }
501
614
  /**
@@ -532,6 +645,7 @@ let MarketplacesService = class MarketplacesService {
532
645
  mirrors: JSON.stringify(input.mirrors ?? []),
533
646
  builtin: false,
534
647
  enabled: true,
648
+ username: input.username,
535
649
  created_by: actor,
536
650
  })
537
651
  .execute();
@@ -549,6 +663,7 @@ let MarketplacesService = class MarketplacesService {
549
663
  form,
550
664
  ...(input.ref !== undefined && { ref: input.ref }),
551
665
  mirrors: input.mirrors ?? [],
666
+ ...(input.username !== null && { username: input.username }),
552
667
  hasToken: input.token !== undefined,
553
668
  ...opts.auditDetail,
554
669
  },
@@ -556,12 +671,13 @@ let MarketplacesService = class MarketplacesService {
556
671
  }
557
672
  /**
558
673
  * Updates a custom marketplace (audit `marketplace.updated`, listing the changed fields, the
559
- * token's value never recorded; not written when unchanged). `token: null` clears the token.
560
- * Official only takes `enabled`, any other field -> `marketplace.builtin`. Changing the URL, form
561
- * or ref clears the ETag and the last commit (the next refresh reads everything again); a new URL
562
- * gets its form from {@link marketplaceForm} unless `form` is given. `ref: null` follows the
563
- * remote HEAD. Switching the form clears the other form's field (the ref when becoming http,
564
- * the mirrors when becoming git) unless the patch sets it.
674
+ * token's value never recorded; not written when unchanged). `token: null` clears the token,
675
+ * `username: null` or `""` the username. Official only takes `enabled`, any other field ->
676
+ * `marketplace.builtin`; a config-managed marketplace likewise -> `marketplace.config_managed`.
677
+ * Changing the URL, form or ref clears the ETag and the last commit (the next refresh reads
678
+ * everything again); a new URL gets its form from {@link marketplaceForm} unless `form` is
679
+ * given. `ref: null` follows the remote HEAD. Switching the form clears the other form's field
680
+ * (the ref when becoming http, the mirrors when becoming git) unless the patch sets it.
565
681
  */
566
682
  async update(actor, id, patch, opts = {}) {
567
683
  const name = patch.name !== undefined ? this.checkName(patch.name) : undefined;
@@ -579,15 +695,17 @@ let MarketplacesService = class MarketplacesService {
579
695
  .executeTakeFirst());
580
696
  if (!row)
581
697
  throw notFound();
582
- if (row.builtin &&
583
- (name !== undefined ||
584
- patch.url !== undefined ||
585
- patch.form !== undefined ||
586
- patch.ref !== undefined ||
587
- patch.mirrors !== undefined ||
588
- patch.token !== undefined)) {
698
+ const editsMore = name !== undefined ||
699
+ patch.url !== undefined ||
700
+ patch.form !== undefined ||
701
+ patch.ref !== undefined ||
702
+ patch.mirrors !== undefined ||
703
+ patch.token !== undefined ||
704
+ patch.username !== undefined;
705
+ if (row.builtin && editsMore)
589
706
  throw builtinErr("changed");
590
- }
707
+ if (row.managed === "config" && editsMore)
708
+ throw configManagedErr("changed");
591
709
  const target = patch.url !== undefined || patch.form !== undefined
592
710
  ? marketplaceForm(patch.url ?? row.url, patch.form)
593
711
  : { form: row.form, url: row.url };
@@ -600,6 +718,7 @@ let MarketplacesService = class MarketplacesService {
600
718
  this.checkGitFields(target.form, ref, mirrors);
601
719
  if (typeof patch.token === "string")
602
720
  this.checkToken(patch.token);
721
+ const username = patch.username === undefined ? row.username : this.checkUsername(patch.username ?? undefined);
603
722
  const changed = [];
604
723
  const set = {};
605
724
  if (name !== undefined && name !== row.name) {
@@ -626,6 +745,10 @@ let MarketplacesService = class MarketplacesService {
626
745
  set.mirrors = JSON.stringify(mirrors);
627
746
  changed.push("mirrors");
628
747
  }
748
+ if (username !== row.username) {
749
+ set.username = username;
750
+ changed.push("username");
751
+ }
629
752
  if (patch.enabled !== undefined && patch.enabled !== row.enabled) {
630
753
  set.enabled = patch.enabled;
631
754
  changed.push("enabled");
@@ -660,6 +783,7 @@ let MarketplacesService = class MarketplacesService {
660
783
  ...(set.url !== undefined && { url: set.url }),
661
784
  ...(set.form !== undefined && { form: set.form }),
662
785
  ...(set.ref !== undefined && { ref: set.ref }),
786
+ ...(set.username !== undefined && { username: set.username }),
663
787
  ...opts.auditDetail,
664
788
  },
665
789
  });
@@ -667,14 +791,15 @@ let MarketplacesService = class MarketplacesService {
667
791
  /**
668
792
  * Deletes a custom marketplace (audit `marketplace.removed`): its cached entries and token
669
793
  * are deleted; imported catalog items are kept (their marketplace becomes null). Official can
670
- * only be disabled -> `marketplace.builtin`.
794
+ * only be disabled -> `marketplace.builtin`; a config-managed one ->
795
+ * `marketplace.config_managed`.
671
796
  */
672
797
  async remove(actor, id, opts = {}) {
673
798
  const t = this.db;
674
799
  await this.adminLock.lockAndAuthorize(actor);
675
800
  const row = await t
676
801
  .selectFrom("marketplaces")
677
- .select(["builtin", "name", "url"])
802
+ .select(["builtin", "managed", "name", "url"])
678
803
  .where("id", "=", id)
679
804
  .forUpdate()
680
805
  .executeTakeFirst();
@@ -682,6 +807,8 @@ let MarketplacesService = class MarketplacesService {
682
807
  throw notFound();
683
808
  if (row.builtin)
684
809
  throw builtinErr("deleted");
810
+ if (row.managed === "config")
811
+ throw configManagedErr("deleted");
685
812
  await t.deleteFrom("marketplaces").where("id", "=", id).execute();
686
813
  await this.secrets().delete(DEPLOYMENT_SECRETS_ORG, tokenKey(id));
687
814
  await audit(t, {
@@ -717,9 +844,8 @@ let MarketplacesService = class MarketplacesService {
717
844
  ? "The official marketplace is disabled by marketplaces.official.enabled (offline mode)"
718
845
  : "This marketplace is disabled; enable it before refreshing");
719
846
  }
720
- const token = row.builtin
721
- ? undefined
722
- : ((await this.secrets().get(DEPLOYMENT_SECRETS_ORG, tokenKey(id))) ?? undefined);
847
+ const creds = await this.credentialsOf(row);
848
+ const token = creds.token;
723
849
  const tokenOrigin = new URL(row.url).origin;
724
850
  const errors = [];
725
851
  // the API code of each failed URL (undefined: an ordinary fetch failure)
@@ -730,7 +856,7 @@ let MarketplacesService = class MarketplacesService {
730
856
  let outcome;
731
857
  if (row.form === "git") {
732
858
  try {
733
- outcome = await this.fetchGit(row, token, signal);
859
+ outcome = await this.fetchGit(row, creds, signal);
734
860
  }
735
861
  catch (e) {
736
862
  if (!(e instanceof GitSourceError || e instanceof MarketplaceInvalidError))
@@ -781,7 +907,7 @@ let MarketplacesService = class MarketplacesService {
781
907
  // the branch heads of imported branch-following git entries (outside the transaction)
782
908
  const heads = outcome === undefined
783
909
  ? new Map()
784
- : await this.resolveHeads(id, outcome === "not_modified" ? undefined : outcome.manifest.plugins, { url: row.url, token }, signal);
910
+ : await this.resolveHeads(id, outcome === "not_modified" ? undefined : outcome.manifest.plugins, { url: row.url, ...creds }, signal);
785
911
  const lastError = status === "error" ? errors.join("\n").slice(0, MAX_ERROR_CHARS) : null;
786
912
  const from = await this.recordRefresh(row, { outcome, heads, status, lastError }, actor, opts);
787
913
  if (from === "stale") {
@@ -835,13 +961,17 @@ let MarketplacesService = class MarketplacesService {
835
961
  * with source path `.`, named by plugin.json or, for a skills-only repo, by the repo name
836
962
  * (Decision 3). Throws {@link GitSourceError} or {@link MarketplaceInvalidError}.
837
963
  */
838
- async fetchGit(row, token, signal) {
964
+ async fetchGit(row, creds, signal) {
839
965
  const config = this.config.get();
840
966
  const options = {
841
967
  net: marketplaceNetPolicy(config),
842
968
  maxBytes: config.packages.maxBytes,
843
969
  signal,
844
- ...(token !== undefined && { token, tokenOrigin: new URL(row.url).origin }),
970
+ ...(creds.token !== undefined && {
971
+ token: creds.token,
972
+ tokenOrigin: new URL(row.url).origin,
973
+ ...(creds.username !== undefined && { username: creds.username }),
974
+ }),
845
975
  };
846
976
  const loc = { url: row.url, ...(row.ref !== null && { ref: row.ref }) };
847
977
  const commit = await resolveGitCommit(loc, options);
@@ -1000,7 +1130,11 @@ let MarketplacesService = class MarketplacesService {
1000
1130
  net: marketplaceNetPolicy(config),
1001
1131
  maxBytes: config.packages.maxBytes,
1002
1132
  signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
1003
- ...(m.token !== undefined && { token: m.token, tokenOrigin: new URL(m.url).origin }),
1133
+ ...(m.token !== undefined && {
1134
+ token: m.token,
1135
+ tokenOrigin: new URL(m.url).origin,
1136
+ ...(m.username !== undefined && { username: m.username }),
1137
+ }),
1004
1138
  };
1005
1139
  try {
1006
1140
  const commit = await resolveGitCommit({ url: git.url, ...(git.ref !== undefined && { ref: git.ref }) }, options);
@@ -1218,9 +1352,37 @@ let MarketplacesService = class MarketplacesService {
1218
1352
  }
1219
1353
  return { contentType: checked.contentType, data };
1220
1354
  }
1221
- /** The token of a custom marketplace (undefined without one; official never has one). */
1222
- async token(id) {
1223
- return (await this.secrets().get(DEPLOYMENT_SECRETS_ORG, tokenKey(id))) ?? undefined;
1355
+ /**
1356
+ * The git / http credential of a marketplace: none for official; a config-managed one's token
1357
+ * from `marketplaces.tokens[name]` (never the secrets table); a custom one's from secrets. The
1358
+ * username is the stored one (absent: the default `x-access-token`). Missing -> `{}`.
1359
+ */
1360
+ async credentials(id) {
1361
+ const row = await this.db
1362
+ .selectFrom("marketplaces")
1363
+ .select(["id", "builtin", "managed", "username"])
1364
+ .where("id", "=", id)
1365
+ .executeTakeFirst();
1366
+ return row === undefined ? {} : this.credentialsOf(row);
1367
+ }
1368
+ async credentialsOf(row) {
1369
+ if (row.builtin)
1370
+ return {};
1371
+ const token = row.managed === "config"
1372
+ ? this.configToken(row.id)
1373
+ : ((await this.secrets().get(DEPLOYMENT_SECRETS_ORG, tokenKey(row.id))) ?? undefined);
1374
+ return {
1375
+ ...(token !== undefined && { token }),
1376
+ ...(row.username !== null && { username: row.username }),
1377
+ };
1378
+ }
1379
+ /** The `marketplaces.tokens` entry of a config-managed marketplace (`config:<name>`). */
1380
+ configToken(id) {
1381
+ if (!id.startsWith(CONFIG_MARKETPLACE_PREFIX))
1382
+ return undefined;
1383
+ const tokens = this.config.get().marketplaces.tokens;
1384
+ const name = id.slice(CONFIG_MARKETPLACE_PREFIX.length);
1385
+ return Object.hasOwn(tokens, name) ? tokens[name] : undefined;
1224
1386
  }
1225
1387
  /** Refreshes every effective marketplace (maintenance job `catalogs-refresh`), one failing not stopping the rest. */
1226
1388
  async refreshAll(signal) {
@@ -1519,7 +1681,11 @@ let MarketplacesService = class MarketplacesService {
1519
1681
  builtin: r.builtin,
1520
1682
  enabled: sourceEffective(r, config),
1521
1683
  disabledByConfig: r.builtin && !config.marketplaces.official.enabled,
1522
- hasToken: hasToken.has(tokenKey(r.id)),
1684
+ managed: r.managed,
1685
+ username: r.username,
1686
+ hasToken: r.managed === "config"
1687
+ ? this.configToken(r.id) !== undefined
1688
+ : hasToken.has(tokenKey(r.id)),
1523
1689
  etag: r.etag,
1524
1690
  lastRefreshedAt: r.last_refreshed_at?.toISOString() ?? null,
1525
1691
  lastStatus: r.last_status,
@@ -1563,12 +1729,24 @@ let MarketplacesService = class MarketplacesService {
1563
1729
  throw new ApiError("validation_failed", "ref must be 1–256 characters without spaces");
1564
1730
  }
1565
1731
  }
1732
+ /** A username outside `GIT_USERNAME_RE` -> `validation_failed`; empty or absent -> null. */
1733
+ checkUsername(username) {
1734
+ if (username === undefined || username === "")
1735
+ return null;
1736
+ if (!GIT_USERNAME_RE.test(username)) {
1737
+ throw new ApiError("validation_failed", "username must match ^[A-Za-z0-9._-]{1,64}$");
1738
+ }
1739
+ return username;
1740
+ }
1566
1741
  checkToken(token) {
1567
1742
  if (token.length < 1 || token.length > MAX_TOKEN_CHARS || /[\r\n]/.test(token)) {
1568
1743
  throw new ApiError("validation_failed", `token must be 1–${MAX_TOKEN_CHARS} characters without line breaks`);
1569
1744
  }
1570
1745
  }
1571
1746
  };
1747
+ __decorate([
1748
+ Transactional()
1749
+ ], MarketplacesService.prototype, "syncExtraFromConfig", null);
1572
1750
  __decorate([
1573
1751
  Transactional()
1574
1752
  ], MarketplacesService.prototype, "writeAdd", null);
@@ -30,7 +30,7 @@ export declare const CatalogMarketplaceRequestBody: z.ZodObject<{
30
30
  /**
31
31
  * One connector template's input at install (C30): name, slug, endpoint, credential or OAuth
32
32
  * client. The credential and the client secret are secrets (`secret()` meta, ruling R2): a Platform
33
- * operation never takes them as params; the person enters them on the confirmation card.
33
+ * operation never takes them as params; the person enters them in a secure input request.
34
34
  */
35
35
  export declare const CatalogConnectorInput: z.ZodObject<{
36
36
  name: z.ZodOptional<z.ZodString>;
@@ -52,7 +52,7 @@ export const CatalogMarketplaceRequestBody = z
52
52
  /**
53
53
  * One connector template's input at install (C30): name, slug, endpoint, credential or OAuth
54
54
  * client. The credential and the client secret are secrets (`secret()` meta, ruling R2): a Platform
55
- * operation never takes them as params; the person enters them on the confirmation card.
55
+ * operation never takes them as params; the person enters them in a secure input request.
56
56
  */
57
57
  export const CatalogConnectorInput = z
58
58
  .object({
@@ -35,10 +35,7 @@ export declare class ChannelCardActions {
35
35
  private readonly deps;
36
36
  constructor(deps: ChannelCardActionsDeps);
37
37
  handle(connectionId: string, e: CardActionEvent): Promise<void>;
38
- /**
39
- * Whether the approval `id` of the org is a network ask, a git push ask or a command review ask
40
- * (each the asked person's own, decided by them in person).
41
- */
42
- private isOwnerDecidedAsk;
38
+ /** The kind of the approval `id` of the org (undefined when there is none). */
39
+ private kindOf;
43
40
  }
44
41
  export {};
@@ -3,7 +3,15 @@ import { ApiError } from "../errors.js";
3
3
  import { idempotencyKey } from "./jobs.js";
4
4
  import { phrase } from "./phrases.js";
5
5
  import { findThread, threadKeyOf } from "./threads.js";
6
- /** 授权 / 状态类失败 → 回给点击者的一句话(不改卡片);其余错误照常抛出。 */
6
+ /**
7
+ * The approval kinds that are the asked person's own, decided by them in person: a network ask, a
8
+ * git push ask, a command review ask.
9
+ */
10
+ const OWNER_DECIDED = new Set(["network", "git", "command"]);
11
+ /**
12
+ * Authorization and state failures → one sentence back to the clicker (the card stays as it is);
13
+ * any other error is thrown as usual.
14
+ */
7
15
  const REPLY_FOR = {
8
16
  "approval.not_found": "cannotHandle",
9
17
  "question.not_found": "cannotHandle",
@@ -87,6 +95,7 @@ export class ChannelCardActions {
87
95
  }
88
96
  // 匿名访客共用一个账号:只能处理自己话题里的卡片,且不能留下「本会话 / 以后都允许」的授权
89
97
  const anonymous = who.threadAccount === null;
98
+ const kind = a.cardKind === "approval" ? await this.kindOf(row.orgId, a.cardId) : undefined;
90
99
  if (anonymous) {
91
100
  const own = await findThread(this.deps.db, {
92
101
  connectionId,
@@ -104,11 +113,17 @@ export class ChannelCardActions {
104
113
  // a network, git push or command review ask is the device owner's, decided by them in
105
114
  // person (network ask-to-allow spec §5.2, auto mode spec §5.4): the shared guest account
106
115
  // never decides one, whoever clicks
107
- if (a.cardKind === "approval" && (await this.isOwnerDecidedAsk(row.orgId, a.cardId))) {
116
+ if (kind !== undefined && OWNER_DECIDED.has(kind)) {
108
117
  await reply("cannotHandle");
109
118
  return;
110
119
  }
111
120
  }
121
+ // a secure input is entered and cancelled on the web only (IM gets a link, never its card), so
122
+ // no click decides one, whoever sends it
123
+ if (kind === "secure_input") {
124
+ await reply("cannotHandle");
125
+ return;
126
+ }
112
127
  try {
113
128
  if (a.cardKind === "approval" && (a.action === "approve" || a.action === "deny")) {
114
129
  const scope = anonymous ? "once" : a.scope;
@@ -133,17 +148,14 @@ export class ChannelCardActions {
133
148
  // row is the child's, which has no delivery of its own
134
149
  await this.deps.outbound.enqueue(card.conversation_id);
135
150
  }
136
- /**
137
- * Whether the approval `id` of the org is a network ask, a git push ask or a command review ask
138
- * (each the asked person's own, decided by them in person).
139
- */
140
- async isOwnerDecidedAsk(orgId, id) {
151
+ /** The kind of the approval `id` of the org (undefined when there is none). */
152
+ async kindOf(orgId, id) {
141
153
  const r = await this.deps.db
142
154
  .selectFrom("approvals")
143
155
  .select("kind")
144
156
  .where("id", "=", id)
145
157
  .where("org_id", "=", orgId)
146
158
  .executeTakeFirst();
147
- return r?.kind === "network" || r?.kind === "git" || r?.kind === "command";
159
+ return r?.kind;
148
160
  }
149
161
  }
@@ -91,9 +91,10 @@ export declare function commandCardText(detail: Pick<CommandAskDetail, "kind" |
91
91
  workingRoot?: string;
92
92
  }, scopes: readonly string[], locale: ChannelLocale, redact?: (s: string) => string): NetworkCardText;
93
93
  /**
94
- * The `bind` card of an approval whose Platform call needs the person to type secrets: the values
95
- * pass only through the web, never an IM vendor, so IM gets a link to the conversation instead of
96
- * an approval card. Undefined when the approval does not exist or has no person fields.
94
+ * The `bind` card of a secure input request (or an approval whose Platform call needs the person
95
+ * to type secrets): the values pass only through the web, never an IM vendor, so IM gets a link to
96
+ * the conversation instead of an approval card. Undefined when the approval does not exist or has
97
+ * no person fields.
97
98
  */
98
99
  export declare function personFieldsCard(d: CardDeps, approvalId: string, base: string, locale: ChannelLocale): Promise<Extract<ChannelCard, {
99
100
  kind: "bind";
@@ -296,9 +296,10 @@ export function commandCardText(detail, scopes, locale, redact = (s) => s) {
296
296
  };
297
297
  }
298
298
  /**
299
- * The `bind` card of an approval whose Platform call needs the person to type secrets: the values
300
- * pass only through the web, never an IM vendor, so IM gets a link to the conversation instead of
301
- * an approval card. Undefined when the approval does not exist or has no person fields.
299
+ * The `bind` card of a secure input request (or an approval whose Platform call needs the person
300
+ * to type secrets): the values pass only through the web, never an IM vendor, so IM gets a link to
301
+ * the conversation instead of an approval card. Undefined when the approval does not exist or has
302
+ * no person fields.
302
303
  */
303
304
  export async function personFieldsCard(d, approvalId, base, locale) {
304
305
  const v = await d.approvals.describe(approvalId);
@@ -321,7 +322,8 @@ export async function personFieldsCard(d, approvalId, base, locale) {
321
322
  */
322
323
  export async function approvalCard(d, approvalId, base, locale, redact) {
323
324
  const v = await d.approvals.describe(approvalId);
324
- if (!v)
325
+ // a secure input is web-only: never an approval card, only the bind link (personFieldsCard)
326
+ if (!v || v.kind === "secure_input")
325
327
  return undefined;
326
328
  const decidedBy = await displayName(d.db, v.decidedBy);
327
329
  // a network, git or command ask names what it asks about instead of a tool call (same shape)
@@ -1026,8 +1026,9 @@ class Delivery {
1026
1026
  await this.send({ text: phrase("handleOnWeb", this.locale) }, this.key(seq));
1027
1027
  return this.advance(seq);
1028
1028
  }
1029
- // secrets are typed on the web only: IM gets a link, never an approval card (no card is
1030
- // recorded, so `approval_decided` has nothing to update)
1029
+ // secrets are typed on the web only (a secure input request, or a tool ask with person
1030
+ // fields): IM gets a link, never an approval card (no card is recorded, so `approval_decided`
1031
+ // has nothing to update)
1031
1032
  const bind = await personFieldsCard(this.d, approvalId, this.base, this.locale);
1032
1033
  if (bind) {
1033
1034
  await this.send(cardMessage(bind.text, bind), this.key(seq));
@@ -93,11 +93,13 @@ export declare const KernelConfigSchema: z.ZodObject<{
93
93
  }, z.core.$strict>>;
94
94
  bootstrap: z.ZodPrefault<z.ZodObject<{
95
95
  dir: z.ZodDefault<z.ZodString>;
96
+ extraManifest: z.ZodOptional<z.ZodString>;
96
97
  }, z.core.$strict>>;
97
98
  catalog: z.ZodPrefault<z.ZodObject<{
98
99
  staleInstallMinutes: z.ZodDefault<z.ZodNumber>;
99
100
  }, z.core.$strict>>;
100
101
  marketplaces: z.ZodPrefault<z.ZodObject<{
102
+ tokens: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
101
103
  official: z.ZodPrefault<z.ZodObject<{
102
104
  enabled: z.ZodDefault<z.ZodBoolean>;
103
105
  url: z.ZodDefault<z.ZodURL>;
@@ -1,5 +1,5 @@
1
1
  import { isIP } from "node:net";
2
- import { DOCUMENT_MEDIA_TYPES, IMAGE_MEDIA_TYPES, validateAllowHost, } from "@capybara-hq/plugin-sdk";
2
+ import { CATALOG_ITEM_NAME_RE, DOCUMENT_MEDIA_TYPES, IMAGE_MEDIA_TYPES, validateAllowHost, } from "@capybara-hq/plugin-sdk";
3
3
  import { z } from "zod";
4
4
  import { LOG_FORMATS, LOG_LEVELS } from "../log.js";
5
5
  import { noProxyEntryProblem, proxyUrlProblem } from "../net/proxy.js";
@@ -452,6 +452,13 @@ export const KernelConfigSchema = z.strictObject({
452
452
  .meta(meta({
453
453
  description: "Offline directory for the bootstrap plugins, resolved against the working directory (/app/bootstrap in the image): a .tgz file here whose sha512 matches a pinned plugin is installed instead of downloading it from packages.npmRegistry",
454
454
  })),
455
+ extraManifest: z
456
+ .string()
457
+ .min(1)
458
+ .optional()
459
+ .meta(meta({
460
+ description: "Path of a bootstrap-extra.v1 manifest, resolved against the working directory like bootstrap.dir, that is merged with the built-in bootstrap manifest (extra plugins and marketplaces for a distribution). Absent by default",
461
+ })),
455
462
  })
456
463
  .prefault({}),
457
464
  catalog: z
@@ -468,6 +475,19 @@ export const KernelConfigSchema = z.strictObject({
468
475
  .prefault({}),
469
476
  marketplaces: z
470
477
  .strictObject({
478
+ tokens: z
479
+ .record(z.string().regex(CATALOG_ITEM_NAME_RE, {
480
+ message: "marketplace name must match ^[a-z0-9][a-z0-9-]{0,63}$",
481
+ }), z
482
+ .string()
483
+ .min(1)
484
+ .max(4096)
485
+ .refine((t) => !/[\r\n]/.test(t), { message: "a token must not contain a newline" }))
486
+ .default({})
487
+ .meta(meta({
488
+ description: "Access tokens by marketplace name for the marketplaces the extra bootstrap manifest declares (bootstrap.extraManifest); never put a token in the manifest file",
489
+ secret: true,
490
+ })),
471
491
  official: z
472
492
  .strictObject({
473
493
  enabled: z
@@ -1637,7 +1657,7 @@ export const KernelConfigSchema = z.strictObject({
1637
1657
  .optional()
1638
1658
  .meta(meta({
1639
1659
  hot: true,
1640
- description: "Whether a device may be granted running a call outside its sandbox (default allowed): a person, the review model or Full access then approves such an escalation per call, within the organization's and the device owner's settings; off refuses every escalation, and devices only run in their sandbox. An organization may turn it off and follow the platform. Set here, it is read-only in the admin console. Replaces devices.fullAccess (CAPYBARA_DEVICES__FULL_ACCESS) and devices.autoMode, which are refused: rename them (the same values; off also needs devices.network.ceiling: allowlist to keep devices on the allowlist), or convert a config file with capybara config migrate-permissions",
1660
+ description: "Whether a device may be granted running a call outside its sandbox (default allowed): a person, the review model or Auto then approves such an escalation per call, within the organization's and the device owner's settings; off refuses every escalation, and devices only run in their sandbox. An organization may turn it off and follow the platform. Set here, it is read-only in the admin console. Replaces devices.fullAccess (CAPYBARA_DEVICES__FULL_ACCESS) and devices.autoMode, which are refused: rename them (the same values; off also needs devices.network.ceiling: allowlist to keep devices on the allowlist), or convert a config file with capybara config migrate-permissions",
1641
1661
  })),
1642
1662
  /**
1643
1663
  * The platform's device sandbox network (approval-only profiles design, "Settings model"):