@capybara-hq/kernel 0.1.0-rc.61 → 0.1.0-rc.63
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.
- package/bootstrap.json +3 -3
- package/dist/app.d.ts +2 -0
- package/dist/catalog/catalog.service.d.ts +13 -0
- package/dist/catalog/catalog.service.js +17 -8
- package/dist/catalog/git-source.d.ts +8 -0
- package/dist/catalog/git-source.js +14 -6
- package/dist/catalog/marketplaces.controller.d.ts +3 -2
- package/dist/catalog/marketplaces.controller.js +5 -2
- package/dist/catalog/marketplaces.schemas.d.ts +7 -0
- package/dist/catalog/marketplaces.schemas.js +13 -0
- package/dist/catalog/marketplaces.service.d.ts +65 -11
- package/dist/catalog/marketplaces.service.js +208 -30
- package/dist/config/schema.d.ts +2 -0
- package/dist/config/schema.js +21 -1
- package/dist/conversations/attachments.controller.d.ts +11 -3
- package/dist/conversations/attachments.controller.js +18 -5
- package/dist/conversations/conversations.controller.d.ts +11 -2
- package/dist/conversations/conversations.controller.js +17 -4
- package/dist/conversations/conversations.schemas.d.ts +8 -0
- package/dist/conversations/conversations.schemas.js +6 -0
- package/dist/db/kernel-schema.d.ts +4 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +7 -0
- package/dist/extensions/bootstrap-defaults.d.ts +24 -0
- package/dist/extensions/bootstrap-defaults.js +78 -0
- package/dist/extensions/bootstrap-extra.d.ts +74 -0
- package/dist/extensions/bootstrap-extra.js +131 -0
- package/dist/extensions/bootstrap.d.ts +77 -13
- package/dist/extensions/bootstrap.js +282 -48
- package/dist/identity/settings.d.ts +10 -0
- package/dist/identity/settings.js +46 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/kernel.module.js +3 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +7 -1
- package/dist/lifecycle/kernel-lifecycle.js +69 -16
- package/dist/platform/ops/marketplaces.ops.js +27 -4
- package/package.json +4 -4
- package/src/migrations/0174_marketplace_managed_username.sql +4 -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 ->
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
*
|
|
564
|
-
* the
|
|
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
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
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
|
|
721
|
-
|
|
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,
|
|
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,
|
|
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,
|
|
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 && {
|
|
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 && {
|
|
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
|
-
/**
|
|
1222
|
-
|
|
1223
|
-
|
|
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
|
-
|
|
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);
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -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>;
|
package/dist/config/schema.js
CHANGED
|
@@ -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
|
|
@@ -8,14 +8,22 @@ declare const CreateBody: z.ZodObject<{
|
|
|
8
8
|
contentType: z.ZodString;
|
|
9
9
|
size: z.ZodNumber;
|
|
10
10
|
}, z.core.$strict>;
|
|
11
|
+
declare const DownloadQuery: z.ZodObject<{
|
|
12
|
+
as: z.ZodOptional<z.ZodEnum<{
|
|
13
|
+
url: "url";
|
|
14
|
+
}>>;
|
|
15
|
+
}, z.core.$strip>;
|
|
11
16
|
/**
|
|
12
17
|
* 对话附件(`/api/v1/orgs/:orgId/attachments`,`agents.use`,只接受人类用户):
|
|
13
18
|
* 1. `POST /` 登记并取预签名上传(`upload.method` 为 `POST` 时按 multipart 表单:先放 `fields`,最后放 `file`);
|
|
14
19
|
* 2. 浏览器直传对象存储;
|
|
15
20
|
* 3. `POST /:id/finalize` 核对大小与类型;
|
|
16
21
|
* 4. 发消息时在 `files` 里引用 id。
|
|
17
|
-
*
|
|
18
|
-
*
|
|
22
|
+
* Download: `GET /:id/download` redirects (302) to the presigned URL (`Cache-Control: private,
|
|
23
|
+
* max-age=60`); `?as=url` answers `{ url }` with that address instead. Limits: `GET /limits` (types,
|
|
24
|
+
* per-file size, files per message, the media budget per request, whether storage is available; for the
|
|
25
|
+
* web's pre-checks; needs no object store). Without an object store the other routes answer 503
|
|
26
|
+
* `storage.unavailable`.
|
|
19
27
|
*/
|
|
20
28
|
export declare class AttachmentsController {
|
|
21
29
|
private readonly attachments;
|
|
@@ -23,6 +31,6 @@ export declare class AttachmentsController {
|
|
|
23
31
|
limits(principal: Principal): AttachmentLimits;
|
|
24
32
|
create(principal: Principal, org: OrgContext, body: z.infer<typeof CreateBody>): Promise<CreatedAttachment>;
|
|
25
33
|
finalize(principal: Principal, org: OrgContext, id: string): Promise<AttachmentView>;
|
|
26
|
-
download(principal: Principal, org: OrgContext, id: string, reply: FastifyReply): Promise<void>;
|
|
34
|
+
download(principal: Principal, org: OrgContext, id: string, q: z.infer<typeof DownloadQuery>, reply: FastifyReply): Promise<void>;
|
|
27
35
|
}
|
|
28
36
|
export {};
|
|
@@ -12,9 +12,10 @@ import { Controller, Get, HttpCode, Inject, Param, Post, Res } from "@nestjs/com
|
|
|
12
12
|
import { z } from "zod";
|
|
13
13
|
import { CurrentPrincipal, requireUser } from "../identity/principal.js";
|
|
14
14
|
import { createZodDto } from "../infra/validation/create-zod-dto.js";
|
|
15
|
-
import { ZBody } from "../infra/validation/zod-params.js";
|
|
15
|
+
import { ZBody, ZQuery } from "../infra/validation/zod-params.js";
|
|
16
16
|
import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
|
|
17
17
|
import { ATTACHMENT_DOWNLOAD_CACHE_SECONDS, AttachmentsService, } from "./attachments.service.js";
|
|
18
|
+
import { DOWNLOAD_AS } from "./conversations.schemas.js";
|
|
18
19
|
const CreateBody = z
|
|
19
20
|
.object({
|
|
20
21
|
name: z
|
|
@@ -28,14 +29,21 @@ const CreateBody = z
|
|
|
28
29
|
.strict();
|
|
29
30
|
class AttachmentCreateBodyDto extends createZodDto(CreateBody, "AttachmentCreateBody") {
|
|
30
31
|
}
|
|
32
|
+
// Not strict: the web adds a cache-busting `retry=1` when it reloads a failed image.
|
|
33
|
+
const DownloadQuery = z.object({ as: DOWNLOAD_AS.optional() });
|
|
34
|
+
class AttachmentDownloadQueryDto extends createZodDto(DownloadQuery, "AttachmentDownloadQuery") {
|
|
35
|
+
}
|
|
31
36
|
/**
|
|
32
37
|
* 对话附件(`/api/v1/orgs/:orgId/attachments`,`agents.use`,只接受人类用户):
|
|
33
38
|
* 1. `POST /` 登记并取预签名上传(`upload.method` 为 `POST` 时按 multipart 表单:先放 `fields`,最后放 `file`);
|
|
34
39
|
* 2. 浏览器直传对象存储;
|
|
35
40
|
* 3. `POST /:id/finalize` 核对大小与类型;
|
|
36
41
|
* 4. 发消息时在 `files` 里引用 id。
|
|
37
|
-
*
|
|
38
|
-
*
|
|
42
|
+
* Download: `GET /:id/download` redirects (302) to the presigned URL (`Cache-Control: private,
|
|
43
|
+
* max-age=60`); `?as=url` answers `{ url }` with that address instead. Limits: `GET /limits` (types,
|
|
44
|
+
* per-file size, files per message, the media budget per request, whether storage is available; for the
|
|
45
|
+
* web's pre-checks; needs no object store). Without an object store the other routes answer 503
|
|
46
|
+
* `storage.unavailable`.
|
|
39
47
|
*/
|
|
40
48
|
let AttachmentsController = class AttachmentsController {
|
|
41
49
|
attachments;
|
|
@@ -54,9 +62,13 @@ let AttachmentsController = class AttachmentsController {
|
|
|
54
62
|
const p = requireUser(principal);
|
|
55
63
|
return this.attachments.finalize(org.orgId, p.account.id, id);
|
|
56
64
|
}
|
|
57
|
-
async download(principal, org, id, reply) {
|
|
65
|
+
async download(principal, org, id, q, reply) {
|
|
58
66
|
const p = requireUser(principal);
|
|
59
67
|
const location = await this.attachments.downloadUrl(org.orgId, p.account.id, id);
|
|
68
|
+
if (q.as === "url") {
|
|
69
|
+
await reply.header("cache-control", "private, no-store").send({ url: location });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
60
72
|
// 浏览器可在短时间内复用跳转(同一页面的缩略图);预签名有效期不短于这段时间
|
|
61
73
|
await reply
|
|
62
74
|
.header("cache-control", `private, max-age=${ATTACHMENT_DOWNLOAD_CACHE_SECONDS}`)
|
|
@@ -89,7 +101,8 @@ __decorate([
|
|
|
89
101
|
__param(0, CurrentPrincipal()),
|
|
90
102
|
__param(1, CurrentOrg()),
|
|
91
103
|
__param(2, Param("id")),
|
|
92
|
-
__param(3,
|
|
104
|
+
__param(3, ZQuery(AttachmentDownloadQueryDto)),
|
|
105
|
+
__param(4, Res())
|
|
93
106
|
], AttachmentsController.prototype, "download", null);
|
|
94
107
|
AttachmentsController = __decorate([
|
|
95
108
|
Controller("api/v1/orgs/:orgId/attachments"),
|
|
@@ -39,12 +39,19 @@ declare const OutputQuery: z.ZodObject<{
|
|
|
39
39
|
declare const FileContentQuery: z.ZodObject<{
|
|
40
40
|
limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
41
41
|
}, z.core.$strip>;
|
|
42
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* `inline=1`: open inline (bitmaps only, see ConversationArtifacts). `as=url`: answer `{ url }`
|
|
44
|
+
* (the presigned location the 302 would send) instead of redirecting, so a page can hand a
|
|
45
|
+
* cookie-free URL to the system browser (a native shell's `openExternal@1`).
|
|
46
|
+
*/
|
|
43
47
|
declare const DownloadQuery: z.ZodObject<{
|
|
44
48
|
inline: z.ZodOptional<z.ZodEnum<{
|
|
45
49
|
0: "0";
|
|
46
50
|
1: "1";
|
|
47
51
|
}>>;
|
|
52
|
+
as: z.ZodOptional<z.ZodEnum<{
|
|
53
|
+
url: "url";
|
|
54
|
+
}>>;
|
|
48
55
|
}, z.core.$strip>;
|
|
49
56
|
declare const MessageBody: z.ZodObject<{
|
|
50
57
|
text: z.ZodString;
|
|
@@ -215,7 +222,9 @@ export declare class ConversationsController {
|
|
|
215
222
|
output: OutputPage;
|
|
216
223
|
}>;
|
|
217
224
|
/**
|
|
218
|
-
*
|
|
225
|
+
* Download an artifact the agent delivered (`artifact_created`): a 302 to the presigned URL (always
|
|
226
|
+
* `attachment`, with the file name);
|
|
227
|
+
* `as=url` answers `{ url }` with that address instead (never cached).
|
|
219
228
|
* 会话可见性与会话流相同,不可见 → `conversation.not_found`;不是该会话的产物 → `conversation.artifact_not_found`。
|
|
220
229
|
*/
|
|
221
230
|
downloadArtifact(principal: Principal, org: OrgContext, id: string, artifactId: string, q: z.infer<typeof DownloadQuery>, reply: FastifyReply): Promise<void>;
|
|
@@ -18,7 +18,7 @@ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
|
|
|
18
18
|
import { MAX_ATTACHMENTS } from "../tools/connector-content.js";
|
|
19
19
|
import { ConversationToolInfo, TOOL_INFO_KEY_MAX, TOOL_INFO_MAX_KEYS, } from "../tools/info.js";
|
|
20
20
|
import { ARTIFACT_DOWNLOAD_CACHE_SECONDS, ConversationArtifacts, } from "./artifacts.js";
|
|
21
|
-
import { CompactBody, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, searchFields, } from "./conversations.schemas.js";
|
|
21
|
+
import { CompactBody, DOWNLOAD_AS, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, searchFields, } from "./conversations.schemas.js";
|
|
22
22
|
import { ConversationsService, } from "./conversations.service.js";
|
|
23
23
|
import { ConversationDeviceStatus } from "./device-status.js";
|
|
24
24
|
import { ConversationFiles, FILE_CONTENT_MAX_BYTES } from "./files.js";
|
|
@@ -46,8 +46,15 @@ const OutputQuery = z.object({
|
|
|
46
46
|
const FileContentQuery = z.object({
|
|
47
47
|
limit: z.coerce.number().int().min(1).max(FILE_CONTENT_MAX_BYTES).default(FILE_CONTENT_MAX_BYTES),
|
|
48
48
|
});
|
|
49
|
-
/**
|
|
50
|
-
|
|
49
|
+
/**
|
|
50
|
+
* `inline=1`: open inline (bitmaps only, see ConversationArtifacts). `as=url`: answer `{ url }`
|
|
51
|
+
* (the presigned location the 302 would send) instead of redirecting, so a page can hand a
|
|
52
|
+
* cookie-free URL to the system browser (a native shell's `openExternal@1`).
|
|
53
|
+
*/
|
|
54
|
+
const DownloadQuery = z.object({
|
|
55
|
+
inline: z.enum(["0", "1"]).optional(),
|
|
56
|
+
as: DOWNLOAD_AS.optional(),
|
|
57
|
+
});
|
|
51
58
|
const MessageFields = z.object({
|
|
52
59
|
/** 用户输入的文本;只有带 `files` 且不带 `attachments` 时可以为空(只发图片 / 文件)。 */
|
|
53
60
|
text: z.string().max(100_000),
|
|
@@ -333,7 +340,9 @@ let ConversationsController = class ConversationsController {
|
|
|
333
340
|
return { output: await this.outputs.read(org.orgId, id, p.account.id, outputId, q) };
|
|
334
341
|
}
|
|
335
342
|
/**
|
|
336
|
-
*
|
|
343
|
+
* Download an artifact the agent delivered (`artifact_created`): a 302 to the presigned URL (always
|
|
344
|
+
* `attachment`, with the file name);
|
|
345
|
+
* `as=url` answers `{ url }` with that address instead (never cached).
|
|
337
346
|
* 会话可见性与会话流相同,不可见 → `conversation.not_found`;不是该会话的产物 → `conversation.artifact_not_found`。
|
|
338
347
|
*/
|
|
339
348
|
async downloadArtifact(principal, org, id, artifactId, q, reply) {
|
|
@@ -341,6 +350,10 @@ let ConversationsController = class ConversationsController {
|
|
|
341
350
|
const { url } = await this.artifacts.downloadUrl(org.orgId, id, p.account.id, artifactId, {
|
|
342
351
|
inline: q.inline === "1",
|
|
343
352
|
});
|
|
353
|
+
if (q.as === "url") {
|
|
354
|
+
await reply.header("cache-control", "private, no-store").send({ url });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
344
357
|
await reply
|
|
345
358
|
.header("cache-control", `private, max-age=${ARTIFACT_DOWNLOAD_CACHE_SECONDS}`)
|
|
346
359
|
.redirect(url, 302);
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import type { RouteSchemas } from "../platform/route-schemas.js";
|
|
3
|
+
/**
|
|
4
|
+
* The download routes' answer form: `as=url` answers `{ url }` (the presigned location the 302
|
|
5
|
+
* would send, never cached) so a page can hand a cookie-free URL to the system browser (a native
|
|
6
|
+
* shell's `openExternal@1`). Shared by the attachment and the artifact download routes.
|
|
7
|
+
*/
|
|
8
|
+
export declare const DOWNLOAD_AS: z.ZodEnum<{
|
|
9
|
+
url: "url";
|
|
10
|
+
}>;
|
|
3
11
|
/** Shared by the list and groups queries: title search, run activity and the archived list. */
|
|
4
12
|
export declare const searchFields: {
|
|
5
13
|
q: z.ZodOptional<z.ZodString>;
|