agent-trellis 0.20.0 → 0.22.0

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 (54) hide show
  1. package/dist/adapters/claude-code.js +2 -2
  2. package/dist/adapters/codex.js +3 -3
  3. package/dist/adapters/jsonMcp.d.ts +1 -1
  4. package/dist/adapters/jsonMcp.js +2 -2
  5. package/dist/adapters/kimi-code.js +2 -2
  6. package/dist/adapters/kiro.js +11 -9
  7. package/dist/adapters/mcpPlan.d.ts +3 -1
  8. package/dist/adapters/mcpPlan.js +65 -15
  9. package/dist/adapters/pi.js +5 -5
  10. package/dist/adapters/zcode.d.ts +1 -1
  11. package/dist/adapters/zcode.js +6 -6
  12. package/dist/cli.js +9 -6
  13. package/dist/commands/doctor.d.ts +1 -1
  14. package/dist/commands/doctor.js +5 -5
  15. package/dist/commands/mcp.js +1 -1
  16. package/dist/commands/mcpAuth.js +1 -1
  17. package/dist/commands/mcpGateway.d.ts +2 -2
  18. package/dist/commands/mcpGateway.js +4 -4
  19. package/dist/commands/mcpImport.js +2 -1
  20. package/dist/commands/migrate.js +11 -1
  21. package/dist/commands/remoteSkill.js +18 -1
  22. package/dist/commands/secretsAudit.d.ts +1 -1
  23. package/dist/commands/secretsAudit.js +49 -13
  24. package/dist/commands/skill.d.ts +11 -6
  25. package/dist/commands/skill.js +85 -32
  26. package/dist/commands/sync.d.ts +1 -0
  27. package/dist/commands/sync.js +3 -1
  28. package/dist/core/canonical.d.ts +1 -2
  29. package/dist/core/canonical.js +16 -9
  30. package/dist/core/types.d.ts +8 -7
  31. package/dist/lib/envVarNames.d.ts +5 -1
  32. package/dist/lib/envVarNames.js +22 -2
  33. package/dist/lib/mcpConnect.d.ts +1 -1
  34. package/dist/lib/mcpConnect.js +35 -10
  35. package/dist/lib/mcpMigrateRead.js +14 -2
  36. package/dist/lib/secretEnv.d.ts +57 -8
  37. package/dist/lib/secretEnv.js +108 -16
  38. package/dist/lib/skillScope.d.ts +14 -0
  39. package/dist/lib/skillScope.js +40 -0
  40. package/dist/lib/tomlSection.js +3 -2
  41. package/dist/lib/workspace.js +7 -2
  42. package/dist/lib/workspaceDoctor.d.ts +1 -1
  43. package/dist/lib/workspaceDoctor.js +8 -4
  44. package/dist/lib/workspaceMcp.d.ts +1 -1
  45. package/dist/lib/workspaceMcp.js +5 -5
  46. package/dist/pi-bridge/bundle.js +42424 -2793
  47. package/dist/pi-bridge/index.js +2 -2
  48. package/docs/architecture.md +27 -7
  49. package/docs/getting-started.md +29 -9
  50. package/docs/research.md +17 -1
  51. package/package.json +2 -1
  52. package/schema/scope.example.yaml +15 -3
  53. package/schema/secrets.policy.example.yaml +5 -0
  54. package/schema/servers.example.yaml +11 -1
@@ -14,8 +14,8 @@
14
14
  */
15
15
  import { Client, StreamableHTTPClientTransport, SSEClientTransport } from "@modelcontextprotocol/client";
16
16
  import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/client/stdio";
17
- import { resolveSecretEnv } from "./secretEnv.js";
18
- import { extractTemplateVarNames } from "./envVarNames.js";
17
+ import { deliveredName, isValidSecretVarName, parseEnvEntry, resolveSecretEntries, resolveSecretEnv } from "./secretEnv.js";
18
+ import { extractTemplateVarNames, invalidHeaderTemplate, replaceTemplateVars } from "./envVarNames.js";
19
19
  export const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
20
20
  const FAILED_TRANSPORT_CLEANUP_TIMEOUT_MS = 1_000;
21
21
  /**
@@ -73,9 +73,20 @@ export async function connectStdio(def, secretsPolicy, timeoutMs, clientInfo) {
73
73
  // `${sourceName}` placeholder text a consumer with no `${VAR}` runtime
74
74
  // of its own (like this bridge) would otherwise crash on parsing
75
75
  // (trellis-migrate-env-var-alias, the real notion-on-pi bug).
76
- const resolved = resolveSecretEnv([...(def.env ?? []), ...Object.values(envAliases)], secretsPolicy);
77
- const namedEnv = Object.fromEntries((def.env ?? []).map((name) => [name, resolved[name] ?? ""]));
78
- const aliasEnv = Object.fromEntries(Object.entries(envAliases).map(([targetKey, sourceName]) => [targetKey, resolved[sourceName] ?? ""]));
76
+ //
77
+ // Entries may be `mxenv://` references: the resolved map is keyed by
78
+ // DELIVERED name (the `KEY` segment for a reference, the entry itself
79
+ // for a bare name), and the spawned server receives values under
80
+ // delivered names — never the raw reference text as a variable name
81
+ // (mx-env-secret-source spec).
82
+ const resolved = await resolveSecretEnv([...(def.env ?? []), ...Object.values(envAliases)], secretsPolicy);
83
+ const namedEnv = Object.fromEntries((def.env ?? []).map((entry) => {
84
+ const delivered = deliveredName(entry);
85
+ return [delivered, resolved[delivered] ?? ""];
86
+ }));
87
+ const aliasEnv = Object.fromEntries(Object.entries(envAliases).map(([targetKey, sourceName]) => {
88
+ return [targetKey, resolved[deliveredName(sourceName)] ?? ""];
89
+ }));
79
90
  const transport = new StdioClientTransport({
80
91
  command: def.command,
81
92
  args: def.args,
@@ -91,20 +102,34 @@ export async function connectStdio(def, secretsPolicy, timeoutMs, clientInfo) {
91
102
  });
92
103
  return connectWithCleanup(client, transport, timeoutMs, `connect timed out after ${timeoutMs}ms`);
93
104
  }
94
- export function resolveHeaders(def, secretsPolicy) {
105
+ export async function resolveHeaders(def, secretsPolicy) {
95
106
  if (!def.headers || Object.keys(def.headers).length === 0)
96
107
  return undefined;
108
+ const invalidHeader = invalidHeaderTemplate(def.headers);
109
+ if (invalidHeader !== undefined)
110
+ throw new Error(`[trellis] invalid reference template in header ${invalidHeader} — use \${VAR} or \${mxenv://<profile>/<KEY>}`);
97
111
  const names = Object.keys(def.headers).flatMap((key) => extractTemplateVarNames(def.headers[key]));
98
- const resolved = resolveSecretEnv(names, secretsPolicy);
112
+ for (const name of names) {
113
+ const entry = parseEnvEntry(name);
114
+ if (entry.kind === "invalid" || (entry.kind === "name" && !isValidSecretVarName(name))) {
115
+ throw new Error(`[trellis] invalid header reference: ${name} — expected a variable name or mxenv://<profile>/<KEY>`);
116
+ }
117
+ }
118
+ const resolved = await resolveSecretEntries(names, secretsPolicy);
99
119
  const result = {};
100
120
  for (const [key, template] of Object.entries(def.headers)) {
101
- result[key] = template.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => resolved[name] ?? "");
121
+ result[key] = replaceTemplateVars(template, (name) => {
122
+ if (parseEnvEntry(name).kind === "ref" && !resolved[name]) {
123
+ throw new Error(`[trellis] unresolved header reference: ${name}`);
124
+ }
125
+ return resolved[name] ?? "";
126
+ });
102
127
  }
103
128
  return result;
104
129
  }
105
130
  export async function connectHttp(def, secretsPolicy, timeoutMs, clientInfo, authProvider) {
106
131
  const client = new Client(clientInfo, { capabilities: {}, versionNegotiation: { mode: "auto", probe: { timeoutMs } } });
107
- const headers = resolveHeaders(def, secretsPolicy);
132
+ const headers = await resolveHeaders(def, secretsPolicy);
108
133
  // authProvider is the SDK's per-request credential seam: `token()` runs
109
134
  // as each request's headers are assembled and its result overrides
110
135
  // `requestInit`'s Authorization — the alternative to burning a Bearer
@@ -118,7 +143,7 @@ export async function connectHttp(def, secretsPolicy, timeoutMs, clientInfo, aut
118
143
  export async function connectSse(def, secretsPolicy, timeoutMs, clientInfo, authProvider) {
119
144
  // HTTP+SSE is a legacy transport; it cannot carry modern discovery.
120
145
  const client = new Client(clientInfo, { capabilities: {} });
121
- const headers = resolveHeaders(def, secretsPolicy);
146
+ const headers = await resolveHeaders(def, secretsPolicy);
122
147
  const opts = {
123
148
  ...(headers ? { requestInit: { headers } } : {}),
124
149
  ...(authProvider ? { authProvider } : {}),
@@ -13,6 +13,7 @@
13
13
  import { execFileSync } from "node:child_process";
14
14
  import { readFileSync } from "node:fs";
15
15
  import { join } from "node:path";
16
+ import { parseEnvEntry } from "./secretEnv.js";
16
17
  import { readJsonFile } from "./probeCommon.js";
17
18
  import { readServerEnvTable } from "./tomlSection.js";
18
19
  import { resolveZcodeProfile } from "../probes/zcode.js";
@@ -42,8 +43,19 @@ const VAR_REF_RE = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
42
43
  * independent derivations of it.
43
44
  */
44
45
  export function resolvedEnvTextMap(def) {
45
- const nameRefs = Object.fromEntries((def.env ?? []).map((name) => [name, `\${${name}}`]));
46
- const aliasRefs = Object.fromEntries(Object.entries(def.envAliases ?? {}).map(([targetKey, sourceName]) => [targetKey, `\${${sourceName}}`]));
46
+ // `mxenv://` reference entries render as `${KEY}` under their DELIVERED
47
+ // name (the KEY segment) — the raw reference text never appears as a
48
+ // variable name in a native-client config (mx-env-secret-source spec).
49
+ const nameRefs = Object.fromEntries((def.env ?? []).map((entry) => {
50
+ const parsed = parseEnvEntry(entry);
51
+ const delivered = parsed.kind === "invalid" ? entry : parsed.delivered;
52
+ return [delivered, `\${${delivered}}`];
53
+ }));
54
+ const aliasRefs = Object.fromEntries(Object.entries(def.envAliases ?? {}).map(([targetKey, source]) => {
55
+ const parsed = parseEnvEntry(source);
56
+ const delivered = parsed.kind === "invalid" ? source : parsed.delivered;
57
+ return [targetKey, `\${${delivered}}`];
58
+ }));
47
59
  return { ...nameRefs, ...aliasRefs, ...(def.staticEnv ?? {}) };
48
60
  }
49
61
  function splitJsonEnvMap(env) {
@@ -4,9 +4,15 @@
4
4
  * `process.env[name]` lookup — so they can never disagree about where a
5
5
  * declared name's value comes from (design.md D1).
6
6
  *
7
- * Dependency-free by design, same as src/lib/envVarNames.ts: a full
8
- * dotenv library's quoting/escaping/interpolation rules are more than
9
- * this narrow need requires (design.md D4).
7
+ * Entries are either bare environment variable names (byte-identical
8
+ * legacy semantics: `env_file` sole-source when set, otherwise ambient
9
+ * `process.env`) or `mxenv://<profile>/<KEY>` references resolved
10
+ * through the `@morphixai/mxenv-core` SDK and delivered under the `KEY`
11
+ * segment (mx-env-secret-source spec). The dotenv half stays
12
+ * dependency-free — a full dotenv library's quoting/escaping/
13
+ * interpolation rules are more than this narrow need requires — while
14
+ * the reference grammar is owned by the SDK and never re-implemented
15
+ * here.
10
16
  */
11
17
  import type { SecretsPolicy } from "../core/types.js";
12
18
  import type { BackupSession } from "./backup.js";
@@ -17,12 +23,55 @@ import type { BackupSession } from "./backup.js";
17
23
  export declare function isValidSecretVarName(name: string): boolean;
18
24
  export declare function parseDotenv(content: string): Record<string, string>;
19
25
  /**
20
- * `policy.envFile` set: it is the SOLE source — a name absent from it
21
- * resolves to `undefined`, `process.env` is never consulted (a silent
22
- * fallback would defeat the isolation this exists to offer). Unset:
23
- * reads `process.env` directly, identical to every pre-existing caller.
26
+ * One declared `env` entry / `envAliases` source value, classified.
27
+ * Strict whole-string matching: an entry is a reference only when the
28
+ * entire entry is exactly one `mxenv://<profile>/<KEY>` (reconstructed
29
+ * from the SDK parser's match). Anything containing reference-shaped
30
+ * text that does not fully match — including the rejected legacy
31
+ * `mx-env://` scheme, which the SDK parser throws on — is `invalid`,
32
+ * never a silently-resolved bare name (mx-env-secret-source D6).
24
33
  */
25
- export declare function resolveSecretEnv(names: string[], policy: SecretsPolicy): Record<string, string | undefined>;
34
+ export type SecretEnvEntry = {
35
+ kind: "ref";
36
+ profile: string;
37
+ key: string;
38
+ delivered: string;
39
+ } | {
40
+ kind: "name";
41
+ delivered: string;
42
+ } | {
43
+ kind: "invalid";
44
+ entry: string;
45
+ };
46
+ /** Delivered name for an entry (KEY segment for a reference, the entry
47
+ * itself otherwise; an invalid entry passes through unchanged so error
48
+ * paths can still name it). The single derivation every renderer and
49
+ * consumer uses — never re-derive from the raw text. */
50
+ export declare function deliveredName(entry: string): string;
51
+ export declare function parseEnvEntry(entry: string): SecretEnvEntry;
52
+ /**
53
+ * `policy.envFile` set: it is the SOLE source for bare names — a name
54
+ * absent from it resolves to `undefined`, `process.env` is never
55
+ * consulted (a silent fallback would defeat the isolation this exists
56
+ * to offer). Unset: bare names read `process.env` directly, identical
57
+ * to every pre-existing caller. References NEVER consult `env_file` or
58
+ * ambient env: they resolve from the composed mxenv profile only, so a
59
+ * same-named ambient variable cannot shadow the composed value.
60
+ *
61
+ * Invalid entries reject the batch with a descriptive error; audit and
62
+ * the plan pre-check pre-classify to turn them into findings/conflicts
63
+ * before this point (the bridge only ever sees pre-checked defs).
64
+ * Compositions are cached per batch (one `ReferenceResolver` per call,
65
+ * not per name).
66
+ * Raw-entry keys preserve provenance when headers mix two profiles with
67
+ * the same KEY, or a reference and a bare name. Values stay in memory. */
68
+ export declare function resolveSecretEntries(entries: string[], policy: SecretsPolicy): Promise<Record<string, string | undefined>>;
69
+ export declare class SecretReferenceError extends Error {
70
+ readonly entry: string;
71
+ constructor(entry: string);
72
+ }
73
+ /** Compatibility view keyed by delivered name (KEY for a reference). */
74
+ export declare function resolveSecretEnv(entries: string[], policy: SecretsPolicy): Promise<Record<string, string | undefined>>;
26
75
  export type WriteLocalSecretOutcome = "created" | "already-present" | "conflict";
27
76
  /**
28
77
  * `trellis migrate`'s static-env secret extraction
@@ -4,12 +4,20 @@
4
4
  * `process.env[name]` lookup — so they can never disagree about where a
5
5
  * declared name's value comes from (design.md D1).
6
6
  *
7
- * Dependency-free by design, same as src/lib/envVarNames.ts: a full
8
- * dotenv library's quoting/escaping/interpolation rules are more than
9
- * this narrow need requires (design.md D4).
7
+ * Entries are either bare environment variable names (byte-identical
8
+ * legacy semantics: `env_file` sole-source when set, otherwise ambient
9
+ * `process.env`) or `mxenv://<profile>/<KEY>` references resolved
10
+ * through the `@morphixai/mxenv-core` SDK and delivered under the `KEY`
11
+ * segment (mx-env-secret-source spec). The dotenv half stays
12
+ * dependency-free — a full dotenv library's quoting/escaping/
13
+ * interpolation rules are more than this narrow need requires — while
14
+ * the reference grammar is owned by the SDK and never re-implemented
15
+ * here.
10
16
  */
11
17
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
12
19
  import { dirname } from "node:path";
20
+ import { findMxEnvReferences, loadConfigLayers, ReferenceResolver } from "@morphixai/mxenv-core";
13
21
  const LINE_RE = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
14
22
  const VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
15
23
  /** The name half of LINE_RE, standing alone: what counts as a variable
@@ -34,22 +42,106 @@ export function parseDotenv(content) {
34
42
  function loadEnvFile(path) {
35
43
  return existsSync(path) ? parseDotenv(readFileSync(path, "utf-8")) : {};
36
44
  }
45
+ /** Delivered name for an entry (KEY segment for a reference, the entry
46
+ * itself otherwise; an invalid entry passes through unchanged so error
47
+ * paths can still name it). The single derivation every renderer and
48
+ * consumer uses — never re-derive from the raw text. */
49
+ export function deliveredName(entry) {
50
+ const parsed = parseEnvEntry(entry);
51
+ return parsed.kind === "invalid" ? entry : parsed.delivered;
52
+ }
53
+ export function parseEnvEntry(entry) {
54
+ if (entry.includes("://")) {
55
+ try {
56
+ const refs = findMxEnvReferences(entry);
57
+ if (refs.length === 1 && `mxenv://${refs[0].profile}/${refs[0].key}` === entry) {
58
+ return { kind: "ref", profile: refs[0].profile, key: refs[0].key, delivered: refs[0].key };
59
+ }
60
+ }
61
+ catch {
62
+ // legacy scheme rejection from the SDK parser — falls through to invalid
63
+ }
64
+ return { kind: "invalid", entry };
65
+ }
66
+ return { kind: "name", delivered: entry };
67
+ }
37
68
  /**
38
- * `policy.envFile` set: it is the SOLE source — a name absent from it
39
- * resolves to `undefined`, `process.env` is never consulted (a silent
40
- * fallback would defeat the isolation this exists to offer). Unset:
41
- * reads `process.env` directly, identical to every pre-existing caller.
42
- */
43
- export function resolveSecretEnv(names, policy) {
69
+ * `policy.envFile` set: it is the SOLE source for bare names — a name
70
+ * absent from it resolves to `undefined`, `process.env` is never
71
+ * consulted (a silent fallback would defeat the isolation this exists
72
+ * to offer). Unset: bare names read `process.env` directly, identical
73
+ * to every pre-existing caller. References NEVER consult `env_file` or
74
+ * ambient env: they resolve from the composed mxenv profile only, so a
75
+ * same-named ambient variable cannot shadow the composed value.
76
+ *
77
+ * Invalid entries reject the batch with a descriptive error; audit and
78
+ * the plan pre-check pre-classify to turn them into findings/conflicts
79
+ * before this point (the bridge only ever sees pre-checked defs).
80
+ * Compositions are cached per batch (one `ReferenceResolver` per call,
81
+ * not per name).
82
+ * Raw-entry keys preserve provenance when headers mix two profiles with
83
+ * the same KEY, or a reference and a bare name. Values stay in memory. */
84
+ export async function resolveSecretEntries(entries, policy) {
85
+ const parsed = entries.map(parseEnvEntry);
86
+ const invalid = parsed.find((p) => p.kind === "invalid");
87
+ if (invalid) {
88
+ throw new Error(`[trellis] invalid mxenv:// reference entry: ${invalid.entry} — expected mxenv://<profile>/<KEY>`);
89
+ }
44
90
  const result = {};
45
- if (policy.envFile) {
46
- const map = loadEnvFile(policy.envFile);
47
- for (const name of names)
48
- result[name] = map[name];
91
+ // Cache compositions once per batch; raw keys keep profiles distinct.
92
+ const refs = parsed.filter((p) => p.kind === "ref");
93
+ if (refs.length > 0) {
94
+ let resolver;
95
+ try {
96
+ resolver = new ReferenceResolver(loadConfigLayers({ cwd: homedir(), homeDir: homedir() }), {});
97
+ }
98
+ catch {
99
+ throw new SecretReferenceError(entries[parsed.indexOf(refs[0])]);
100
+ }
101
+ for (const ref of refs) {
102
+ const entry = `mxenv://${ref.profile}/${ref.key}`;
103
+ if (Object.hasOwn(result, entry))
104
+ continue;
105
+ try {
106
+ const { value } = await resolver.valueOf(ref.profile, ref.key);
107
+ result[entry] = value;
108
+ }
109
+ catch {
110
+ // Provider errors may contain credential material. Report only the
111
+ // reference, never propagate provider output to logs or audit.
112
+ throw new SecretReferenceError(entry);
113
+ }
114
+ }
49
115
  }
50
- else {
51
- for (const name of names)
52
- result[name] = process.env[name];
116
+ const names = parsed.filter((p) => p.kind === "name");
117
+ if (names.length > 0) {
118
+ const fileMap = policy.envFile ? loadEnvFile(policy.envFile) : undefined;
119
+ for (const name of names) {
120
+ if (result[name.delivered] !== undefined)
121
+ continue;
122
+ result[name.delivered] = fileMap ? fileMap[name.delivered] : process.env[name.delivered];
123
+ }
124
+ }
125
+ return result;
126
+ }
127
+ export class SecretReferenceError extends Error {
128
+ entry;
129
+ constructor(entry) {
130
+ super(`[trellis] could not resolve mxenv reference ${entry} — check the profile, KEY and provider configuration`);
131
+ this.entry = entry;
132
+ }
133
+ }
134
+ /** Compatibility view keyed by delivered name (KEY for a reference). */
135
+ export async function resolveSecretEnv(entries, policy) {
136
+ const values = await resolveSecretEntries(entries, policy);
137
+ const result = {};
138
+ // Preserve the existing delivered-name collision rules for env/envAliases.
139
+ const ordered = [...entries.filter((entry) => parseEnvEntry(entry).kind === "ref"),
140
+ ...entries.filter((entry) => parseEnvEntry(entry).kind !== "ref")];
141
+ for (const entry of ordered) {
142
+ const name = deliveredName(entry);
143
+ if (result[name] === undefined)
144
+ result[name] = values[entry];
53
145
  }
54
146
  return result;
55
147
  }
@@ -0,0 +1,14 @@
1
+ import { type AgentId } from "../core/types.js";
2
+ import { type ScopeSelectorRaw } from "./scopeSelection.js";
3
+ export declare function registeredSkillScope(value: unknown): AgentId[];
4
+ export declare function readSkillScopes(path: string): Record<string, unknown>;
5
+ export declare function selectSkillScope(raw: ScopeSelectorRaw, managed: readonly AgentId[]): {
6
+ scope: AgentId[];
7
+ } | {
8
+ error: string;
9
+ };
10
+ export declare function requestSkillScope(raw: ScopeSelectorRaw, managed: readonly AgentId[], interactive: boolean): Promise<{
11
+ scope: AgentId[];
12
+ } | {
13
+ error: string;
14
+ }>;
@@ -0,0 +1,40 @@
1
+ /** Skill scope is a registry, not an exceptions list. Unregistered or
2
+ * invalid entries stay paused until applicable agents are selected. */
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { parse as parseYaml } from "yaml";
5
+ import { ALL_AGENTS } from "../core/types.js";
6
+ import { resolveScopeSelection } from "./scopeSelection.js";
7
+ import { canUseInteractivePicker, runMultiSelectPicker } from "./terminalPicker.js";
8
+ export function registeredSkillScope(value) {
9
+ return Array.isArray(value) && value.every((id) => ALL_AGENTS.includes(id)) ? [...new Set(value)] : [];
10
+ }
11
+ export function readSkillScopes(path) {
12
+ if (!existsSync(path))
13
+ return {};
14
+ const doc = parseYaml(readFileSync(path, "utf8"));
15
+ if (doc?.skills === undefined)
16
+ return {};
17
+ if (typeof doc.skills !== "object" || doc.skills === null || Array.isArray(doc.skills)) {
18
+ throw new Error(`${path}: skills must be a map of skill names to agent lists`);
19
+ }
20
+ return doc.skills;
21
+ }
22
+ export function selectSkillScope(raw, managed) {
23
+ const selected = resolveScopeSelection(raw, managed);
24
+ if (!selected.ok)
25
+ return { error: selected.detail };
26
+ // Even "all" records today's set. Managing another agent later must
27
+ // never expand the compatibility decision made for an existing skill.
28
+ return { scope: selected.scope ?? [...managed] };
29
+ }
30
+ export async function requestSkillScope(raw, managed, interactive) {
31
+ if (raw.agents !== undefined || raw.all || raw.none)
32
+ return selectSkillScope(raw, managed);
33
+ if (!interactive || !canUseInteractivePicker()) {
34
+ return { error: "choose applicable agents with --agents <ids>, --all or --none; no scope is selected automatically" };
35
+ }
36
+ if (managed.length === 0)
37
+ return { error: "no managed agents — run trellis onboard, or use --none to import a paused skill" };
38
+ const indices = await runMultiSelectPicker([...managed], managed.map(() => false), undefined, "选择这个 skill 适用的 agent(不选则暂停分发)");
39
+ return indices === null ? { error: "skill import cancelled" } : { scope: indices.map((index) => managed[index]) };
40
+ }
@@ -8,6 +8,7 @@
8
8
  * ever needs to recognize table headers and render a bounded, known
9
9
  * shape (`McpServerDef`), never general TOML.
10
10
  */
11
+ import { deliveredName } from "./secretEnv.js";
11
12
  /**
12
13
  * Matches a TOML table header line, and *only* a table header line — the
13
14
  * entire trimmed line must be exactly `[key.path]` or `[[key.path]]`,
@@ -146,7 +147,7 @@ export function renderServerSection(name, def) {
146
147
  if (def.args && def.args.length > 0)
147
148
  lines.push(`args = ${tomlStringArray(def.args)}`);
148
149
  if (def.env && def.env.length > 0)
149
- lines.push(`env_vars = ${tomlStringArray(def.env)}`);
150
+ lines.push(`env_vars = ${tomlStringArray(def.env.map(deliveredName))}`);
150
151
  }
151
152
  else {
152
153
  if (def.url)
@@ -160,7 +161,7 @@ export function renderServerSection(name, def) {
160
161
  // expands it from its own ambient environment, the same mechanism
161
162
  // `env_vars` already relies on for a same-named reference
162
163
  // (trellis-migrate-env-var-alias D3).
163
- const aliasEntries = Object.entries(def.envAliases ?? {}).map(([targetKey, sourceName]) => [targetKey, `\${${sourceName}}`]);
164
+ const aliasEntries = Object.entries(def.envAliases ?? {}).map(([targetKey, sourceName]) => [targetKey, `\${${deliveredName(sourceName)}}`]);
164
165
  const staticEnvEntries = [...aliasEntries, ...Object.entries(def.staticEnv ?? {})];
165
166
  if (staticEnvEntries.length > 0) {
166
167
  lines.push(`[${envHeader(name)}]`);
@@ -12,6 +12,7 @@ import { homedir } from "node:os";
12
12
  import { dirname, join, resolve } from "node:path";
13
13
  import { oauthClientMetadata } from "../core/types.js";
14
14
  import { fromServerDefYaml } from "../core/mcpServerDef.js";
15
+ import { readSkillScopes, registeredSkillScope } from "./skillScope.js";
15
16
  export const WORKSPACE_DIR_NAME = ".agents";
16
17
  /** The only `config.json` schema version this implementation understands. */
17
18
  export const WORKSPACE_CONFIG_VERSION = 1;
@@ -103,6 +104,7 @@ export function loadWorkspaceLayer(workspaceDir, policy) {
103
104
  layer.instructionsFile = instructionsPath;
104
105
  }
105
106
  const skillsRoot = join(layerRoot, "skills");
107
+ const scopes = readSkillScopes(join(layerRoot, "scope.yaml"));
106
108
  let skillEntries = [];
107
109
  try {
108
110
  skillEntries = readdirSync(skillsRoot);
@@ -113,8 +115,11 @@ export function loadWorkspaceLayer(workspaceDir, policy) {
113
115
  for (const name of skillEntries) {
114
116
  const dir = join(skillsRoot, name);
115
117
  try {
116
- if (statSync(dir).isDirectory())
117
- layer.skills.push({ name, dir });
118
+ if (statSync(dir).isDirectory()) {
119
+ layer.skills.push({ name, dir, scope: registeredSkillScope(scopes[name]) });
120
+ if (!Object.hasOwn(scopes, name))
121
+ diagnostics.push(`.agents/scope.yaml: skill "${name}" has no registered agents — Trellis distribution paused`);
122
+ }
118
123
  }
119
124
  catch {
120
125
  // unreadable/broken entry — skip, not a load failure
@@ -56,4 +56,4 @@ export interface WorkspaceDoctorSection {
56
56
  /** zcode's user-level-first deviation notices (empty otherwise). */
57
57
  precedenceWarnings: string[];
58
58
  }
59
- export declare function collectWorkspaceDoctorSection(canonical: CanonicalSource): WorkspaceDoctorSection | undefined;
59
+ export declare function collectWorkspaceDoctorSection(canonical: CanonicalSource): Promise<WorkspaceDoctorSection | undefined>;
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { existsSync, readFileSync } from "node:fs";
13
13
  import { parse as parseToml } from "smol-toml";
14
- import { resolveSecretEnv } from "./secretEnv.js";
14
+ import { deliveredName, parseEnvEntry, resolveSecretEnv } from "./secretEnv.js";
15
15
  import { loadWorkspaceRendered, workspaceMcpConfigPath, workspacePrecedenceWarnings } from "./workspaceMcp.js";
16
16
  const VAR_REF_RE = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
17
17
  function collectVarRefs(canonical) {
@@ -86,7 +86,7 @@ function unmarkedEntries(agentId, configPath, recorded) {
86
86
  }
87
87
  return { kind: "ok", names: names.filter((name) => recorded[name] === undefined) };
88
88
  }
89
- export function collectWorkspaceDoctorSection(canonical) {
89
+ export async function collectWorkspaceDoctorSection(canonical) {
90
90
  const workspace = canonical.workspace;
91
91
  if (!workspace)
92
92
  return undefined;
@@ -101,8 +101,12 @@ export function collectWorkspaceDoctorSection(canonical) {
101
101
  // overridden.
102
102
  const tombstoned = workspace.shadowed.filter((entry) => entry.startsWith("mcp:") && canonical.mcp.servers[entry.slice(4)] === undefined);
103
103
  const refs = collectVarRefs(canonical);
104
- const resolved = resolveSecretEnv([...new Set(refs.map((r) => r.name))], canonical.secretsPolicy);
105
- const unresolvedVars = refs.filter((r) => resolved[r.name] === undefined);
104
+ // Malformed `mxenv://` entries are unresolved as-is (they name themselves);
105
+ // they must never reach resolveSecretEnv, which rejects the batch.
106
+ const invalid = refs.filter((r) => parseEnvEntry(r.name).kind === "invalid");
107
+ const resolvableRefs = refs.filter((r) => parseEnvEntry(r.name).kind !== "invalid");
108
+ const resolved = await resolveSecretEnv([...new Set(resolvableRefs.map((r) => r.name))], canonical.secretsPolicy);
109
+ const unresolvedVars = [...invalid, ...resolvableRefs.filter((r) => resolved[deliveredName(r.name)] === undefined)];
106
110
  const manifest = loadWorkspaceRendered(workspace.root);
107
111
  const unmigrated = [];
108
112
  const tomlFindings = [];
@@ -53,5 +53,5 @@ export declare function renderWorkspaceManifestEntry(agentId: AgentId, name: str
53
53
  * `applyWorkspaceMcp`; this exists only for adoption, where no delivery
54
54
  * write to that agent's file has happened yet. */
55
55
  export declare function recordWorkspaceRendered(workspaceRoot: string, agentId: AgentId, name: string, rendered: unknown, backup: BackupSession): void;
56
- export declare function planWorkspaceMcp(agentId: AgentId, canonical: CanonicalSource): AdapterPlanItem[];
56
+ export declare function planWorkspaceMcp(agentId: AgentId, canonical: CanonicalSource): Promise<AdapterPlanItem[]>;
57
57
  export declare function applyWorkspaceMcp(agentId: AgentId, canonical: CanonicalSource, items: AdapterPlanItem[], backup: BackupSession): void;
@@ -140,7 +140,7 @@ export function recordWorkspaceRendered(workspaceRoot, agentId, name, rendered,
140
140
  mkdirSync(dirname(path), { recursive: true });
141
141
  backup.writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
142
142
  }
143
- export function planWorkspaceMcp(agentId, canonical) {
143
+ export async function planWorkspaceMcp(agentId, canonical) {
144
144
  const workspace = canonical.workspace;
145
145
  if (!workspace)
146
146
  return [];
@@ -151,7 +151,7 @@ export function planWorkspaceMcp(agentId, canonical) {
151
151
  const layer = (item) => ({ ...item, layer: "workspace" });
152
152
  if (agentId === "codex") {
153
153
  const content = existsSync(configPath) ? readFileSync(configPath, "utf-8") : "";
154
- const { desired, conflicts } = resolveMcpPlan(agentId, mcp, canonical.managedAgents, canonical.secretsPolicy);
154
+ const { desired, conflicts } = await resolveMcpPlan(agentId, mcp, canonical.managedAgents, canonical.secretsPolicy);
155
155
  const items = [];
156
156
  for (const { name, def } of desired) {
157
157
  const current = currentServerSectionText(content, name);
@@ -183,13 +183,13 @@ export function planWorkspaceMcp(agentId, canonical) {
183
183
  }
184
184
  if (agentId === "zcode") {
185
185
  const parsed = existsSync(configPath) ? JSON.parse(readFileSync(configPath, "utf-8")) : undefined;
186
- const items = planZcodeMcp({ configPath, parsed, mcp, managedAgents: canonical.managedAgents, policy: canonical.secretsPolicy, ownership }).map(layer);
186
+ const items = (await planZcodeMcp({ configPath, parsed, mcp, managedAgents: canonical.managedAgents, policy: canonical.secretsPolicy, ownership })).map(layer);
187
187
  const servers = (parsed?.mcp?.servers ?? {});
188
188
  return guardUnmarkedOverwrite(items, (item) => servers[item.mcpWrite.name] !== undefined && ownership[item.mcpWrite.name] === undefined);
189
189
  }
190
190
  const parsed = existsSync(configPath) ? JSON.parse(readFileSync(configPath, "utf-8")) : undefined;
191
191
  const render = agentId === "pi" ? piRenderer : undefined;
192
- const planned = planJsonMcp({
192
+ const planned = (await planJsonMcp({
193
193
  configPath,
194
194
  parsed,
195
195
  mcp,
@@ -198,7 +198,7 @@ export function planWorkspaceMcp(agentId, canonical) {
198
198
  policy: canonical.secretsPolicy,
199
199
  ownership,
200
200
  ...(render ? { render } : {}),
201
- }).map(layer);
201
+ })).map(layer);
202
202
  const existing = (parsed?.mcpServers ?? {});
203
203
  const guarded = guardUnmarkedOverwrite(planned, (item) => existing[item.mcpWrite.name] !== undefined && ownership[item.mcpWrite.name] === undefined);
204
204
  if (agentId !== "pi")