@soft-boy/agentschema 0.2.1 → 0.3.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.
@@ -0,0 +1,171 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { stringify } from "yaml";
4
+ import { check } from "./check.js";
5
+ import { serviceName } from "./cred-menu.js";
6
+ import { DeployError } from "./deploy.js";
7
+ import { builtInFile } from "./init.js";
8
+ import { AGENT_FILE, ENV_FILE } from "./instance.js";
9
+ import { updateFrontmatter } from "./markdown.js";
10
+ import { listMcpTools } from "./mcp.js";
11
+ import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR } from "./tools.js";
12
+
13
+ const PREBUILT = "Pre-built tools (bash, files, web search)";
14
+ const CUSTOM = "Custom tool (JavaScript that runs on your machine)";
15
+ const MCP = "MCP server";
16
+ const INPUT_TYPES = ["string", "number", "integer", "boolean", "object", "string[]", "number[]", "integer[]", "boolean[]", "object[]"];
17
+
18
+ // `tools create`: asks what kind of tool to add, then writes its file in tools/.
19
+ // Returns the path of the file written.
20
+ export async function toolsCreate(dir = ".", { io, fetch = globalThis.fetch, log = () => {} }) {
21
+ const { errors, instance } = check(dir);
22
+ if (!instance) throw new DeployError(`${dir} isn't an agent folder:\n ${errors.join("\n ")}`);
23
+
24
+ const kind = await io.select("What kind of tool?", [PREBUILT, CUSTOM, MCP], PREBUILT);
25
+ const write = kind === PREBUILT ? prebuilt : kind === CUSTOM ? custom : mcp;
26
+ const { path, text, addServer } = await write(dir, instance, io, { fetch, log });
27
+
28
+ const file = join(dir, path);
29
+ mkdirSync(dirname(file), { recursive: true });
30
+ writeFileSync(file, text);
31
+ log(`Wrote ${file}`);
32
+ if (addServer) {
33
+ updateFrontmatter(join(dir, AGENT_FILE), (doc) => {
34
+ if (doc.hasIn(["mcp_servers"])) doc.addIn(["mcp_servers"], doc.createNode(addServer));
35
+ else doc.setIn(["mcp_servers"], doc.createNode([addServer]));
36
+ });
37
+ log(`Added ${addServer.name} to mcp_servers in ${join(dir, AGENT_FILE)}`);
38
+ }
39
+
40
+ const after = check(dir);
41
+ const related = (m) => m.startsWith(path) || (kind === MCP && (m.startsWith(AGENT_FILE) || m.startsWith(ENV_FILE)));
42
+ for (const w of after.warnings.filter(related)) log(`warning: ${w}`);
43
+ for (const e of after.errors.filter(related)) log(`error: ${e}`);
44
+ if (kind === CUSTOM) log(`\nWrite the tool's code in its ## Code block, then deploy with:\n agentschema deploy ${dir}`);
45
+ else if (kind === MCP) log(`\nIf the server needs you to sign in, add a credential for it:\n agentschema cred create ${dir}\nThen deploy with:\n agentschema deploy ${dir}`);
46
+ else log(`\nDeploy with:\n agentschema deploy ${dir}`);
47
+ return file;
48
+ }
49
+
50
+ // The pre-built toolset: one file, with a row for each tool.
51
+ async function prebuilt(dir, { tools }, io) {
52
+ const existing = tools.find((t) => t.data.type === TOOLSET);
53
+ if (existing) throw new DeployError(`the agent already has its pre-built tools in ${existing.file}; edit that file's table to turn tools on or off`);
54
+
55
+ let enabled = PREBUILT_TOOLS;
56
+ if (!(await io.confirm(`Turn on all eight (${PREBUILT_TOOLS.join(", ")})?`, true))) {
57
+ enabled = [];
58
+ for (const name of PREBUILT_TOOLS) if (await io.confirm(` ${name}?`, true)) enabled.push(name);
59
+ }
60
+ return { path: `${TOOLS_DIR}/${TOOLSET_FILE}`, text: builtInFile(PREBUILT_TOOLS, enabled) };
61
+ }
62
+
63
+ // A custom tool: its name, description and inputs, with a code block to fill in.
64
+ async function custom(dir, { tools }, io) {
65
+ const taken = new Set(tools.filter((t) => t.data.type === "custom").map((t) => t.name));
66
+ const name = await io.text("Tool name? (letters, digits, _ and -)", "", {
67
+ validate: (n) => {
68
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(n)) return "Use letters, digits, _ and -, up to 64 characters";
69
+ if (PREBUILT_TOOLS.includes(n)) return `${n} is a pre-built tool's name`;
70
+ if (/^(mcp__|ant__)/.test(n)) return "A custom tool's name can't start with mcp__ or ant__";
71
+ if (taken.has(n) || existsSync(join(dir, TOOLS_DIR, `${n}.md`))) return `There's already a tool called ${n}`;
72
+ return null;
73
+ },
74
+ });
75
+ const description = await io.text("What does it do? (Claude reads this to decide when to call it)", "", {
76
+ validate: (d) => (d ? null : "The description is required"),
77
+ });
78
+
79
+ const inputs = [];
80
+ while (true) {
81
+ const input = await io.text(inputs.length === 0 ? "First input's name? (Enter for none)" : "Next input's name? (Enter when done)", "", {
82
+ validate: (n) => {
83
+ if (n && !/^[a-zA-Z_$][\w$]*$/.test(n)) return "Use a name like city or max_results";
84
+ if (inputs.some((i) => i.name === n)) return `${n} is already an input`;
85
+ return null;
86
+ },
87
+ });
88
+ if (!input) break;
89
+ const type = await io.select(` ${input}'s type?`, INPUT_TYPES, "string");
90
+ const about = await io.text(` ${input}'s description?`, "");
91
+ const required = await io.confirm(` Is ${input} required?`, true);
92
+ inputs.push({ name: input, type, about, required });
93
+ }
94
+
95
+ const cell = (s) => s.replace(/\|/g, "\\|");
96
+ const table = inputs.length === 0 ? "" : [
97
+ "## Input Schema", "",
98
+ "| Name | Type | Description | Required |",
99
+ "|---|---|---|---|",
100
+ ...inputs.map((i) => `| \`${i.name}\` | \`${i.type}\` | ${cell(i.about)} | \`${i.required}\` |`),
101
+ "", "",
102
+ ].join("\n");
103
+ const args = inputs.length === 0 ? "()" : `({ ${inputs.map((i) => i.name).join(", ")} })`;
104
+ const code = [
105
+ "## Code", "",
106
+ "```javascript",
107
+ `module.exports = async ${args} => {`,
108
+ ` throw new Error("${name} isn't implemented yet");`,
109
+ "};",
110
+ "```", "",
111
+ ].join("\n");
112
+
113
+ const front = stringify({ type: "custom", name, description });
114
+ return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${front}---\n\n${table}${code}` };
115
+ }
116
+
117
+ // An MCP server: its URL and name, how its tools are approved, and a table of those tools.
118
+ // The server itself is declared in agent.md; a server already declared there only needs its file.
119
+ async function mcp(dir, instance, io, { fetch, log }) {
120
+ const { tools, agent } = instance;
121
+ const declared = Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers : [];
122
+ const toolsets = new Set(tools.filter((t) => t.data.type === MCP_TOOLSET).map((t) => t.data.mcp_server_name));
123
+ const url = await io.text("MCP server URL?", "", {
124
+ validate: (u) => {
125
+ if (!/^https?:\/\/\S+$/.test(u)) return "Enter an http(s) URL";
126
+ const same = declared.find((s) => s?.url === u);
127
+ return same && toolsets.has(same.name) ? `${AGENT_FILE} already declares that server, as ${same.name}` : null;
128
+ },
129
+ });
130
+ const existing = declared.find((s) => s?.url === url);
131
+ const name = existing?.name ?? await io.text("Name for it?", serviceName(url).toLowerCase(), {
132
+ validate: (n) => {
133
+ if (!n || /[/\\]/.test(n) || n.startsWith(".")) return "Use a name without / that doesn't start with .";
134
+ if (declared.some((s) => s?.name === n)) return `${AGENT_FILE} already declares a server called ${n}`;
135
+ if (existsSync(join(dir, TOOLS_DIR, `${n}.md`))) return `There's already a tool file called ${n}.md`;
136
+ return null;
137
+ },
138
+ });
139
+ const addServer = existing ? null : { type: "url", name, url };
140
+
141
+ const policies = ["always_ask", ...POLICIES.filter((p) => p !== "always_ask")];
142
+ const policy = await io.select("Ask you before each call? (permission for its tools)", policies.map(describePolicy), describePolicy("always_ask"));
143
+ const permission = policies.find((p) => describePolicy(p) === policy);
144
+
145
+ // A table of the server's tools, all on, to edit. A tool the server adds later isn't in the
146
+ // table, so it gets the API's defaults: on, and asking before each call.
147
+ log(`Asking ${url} for its tools…`);
148
+ const names = await listMcpTools(url, { fetch });
149
+ const front = { type: MCP_TOOLSET, mcp_server_name: name };
150
+ if (names) {
151
+ log(`It has ${names.length} tool${names.length === 1 ? "" : "s"}.`);
152
+ const rows = names.map((t) => `| \`${t}\` | \`true\` | \`${permission}\` |`);
153
+ const body = ["Set Enabled to false to turn a tool off.", "", "## Tools", "", "| Name | Enabled | Permission |", "|---|---|---|", ...rows, ""].join("\n");
154
+ return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${stringify(front)}---\n\n${body}`, addServer };
155
+ }
156
+
157
+ // It won't list them without signing in: every tool is on, with the permission chosen.
158
+ log("It won't list its tools without signing in, so the file has no table; every tool is on.");
159
+ if (permission !== "always_ask") front.default_config = { permission_policy: { type: permission } };
160
+ const body = "Every tool the server offers is on. To turn one off, or give it its own permission, add a table:\n\n" +
161
+ " ## Tools\n\n | Name | Enabled | Permission |\n |---|---|---|\n | `delete_event` | `false` | |\n";
162
+ return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${stringify(front)}---\n\n${body}`, addServer };
163
+ }
164
+
165
+ function describePolicy(policy) {
166
+ return {
167
+ always_ask: "always_ask: ask before every call (the API's default for MCP tools)",
168
+ always_allow: "always_allow: never ask",
169
+ auto: "auto: Anthropic decides per call, and asks when it can't",
170
+ }[policy];
171
+ }
package/src/tools.js CHANGED
@@ -7,6 +7,7 @@ import { FileError, parseMarkdown } from "./markdown.js";
7
7
  export const TOOLS_DIR = "tools";
8
8
  export const TOOLSET = "agent_toolset_20260401";
9
9
  export const TOOLSET_FILE = `${TOOLSET}.md`;
10
+ export const MCP_TOOLSET = "mcp_toolset";
10
11
  export const PREBUILT_TOOLS = ["bash", "edit", "glob", "grep", "read", "web_fetch", "web_search", "write"];
11
12
  export const POLICIES = ["always_allow", "always_ask", "auto"];
12
13
  const TYPES = ["string", "number", "integer", "boolean", "object", "array"];
@@ -38,8 +39,10 @@ export function readTools(dir) {
38
39
  }
39
40
 
40
41
  // Custom tool names must be unique across folders, since the folders are dropped.
41
- for (const [name, same] of groupBy(tools.filter((t) => t.data.type === "custom"), (t) => t.name)) {
42
- if (same.length > 1) errors.push(`${TOOLS_DIR}: more than one tool is named \`${name}\` (${same.map((t) => t.file).join(", ")})`);
42
+ for (const [type, what] of [["custom", "tool"], [MCP_TOOLSET, "MCP server"]]) {
43
+ for (const [name, same] of groupBy(tools.filter((t) => t.data.type === type), (t) => t.name)) {
44
+ if (same.length > 1) errors.push(`${TOOLS_DIR}: more than one ${what} is named \`${name}\` (${same.map((t) => t.file).join(", ")})`);
45
+ }
43
46
  }
44
47
  const toolsets = tools.filter((t) => t.data.type === TOOLSET);
45
48
  if (toolsets.length > 1) {
@@ -137,13 +140,41 @@ export function checkTools(tools, errors) {
137
140
  if (type === TOOLSET) {
138
141
  checkToolset(tool, err);
139
142
  extra(["type"]);
143
+ } else if (type === MCP_TOOLSET) {
144
+ checkMcpToolset(tool, err);
145
+ extra(["type", "mcp_server_name", "default_config", "url"]);
140
146
  } else if (type === "custom") {
141
147
  checkCustom(tool, err);
142
148
  extra(["type", "name", "description"]);
143
149
  } else {
144
- err(`\`type\` must be \`${TOOLSET}\` (a pre-built tool) or \`custom\``);
150
+ err(`\`type\` must be \`${TOOLSET}\` (the pre-built tools), \`${MCP_TOOLSET}\` (an MCP server) or \`custom\``);
151
+ }
152
+ }
153
+ }
154
+
155
+ // The tools of an MCP server that agent.md declares: `mcp_server_name` is the server's name, and the
156
+ // optional `## Tools` table configures tools by the names the server reports.
157
+ function checkMcpToolset(tool, err) {
158
+ const { mcp_server_name: server, default_config: defaults } = tool.data;
159
+ if ("url" in tool.data) err("`url` belongs in agent.md's `mcp_servers`; refer to the server here with `mcp_server_name`");
160
+ if (typeof server !== "string" || server === "") err("`mcp_server_name` is required");
161
+ else if (server !== tool.name) err(`\`mcp_server_name\` must match the file name (${tool.name})`);
162
+ if (tool.name.length > 255) err("an MCP server's name (its file name) must be at most 255 characters");
163
+
164
+ if (defaults !== undefined && defaults !== null) {
165
+ if (typeof defaults !== "object" || Array.isArray(defaults)) err("`default_config` must be a mapping");
166
+ else {
167
+ if (defaults.enabled !== undefined && typeof defaults.enabled !== "boolean") err("`default_config.enabled` must be true or false");
168
+ const policy = defaults.permission_policy;
169
+ if (policy !== undefined && !POLICIES.includes(policy?.type)) {
170
+ err(`\`default_config.permission_policy.type\` must be ${POLICIES.join(", ")}`);
171
+ }
172
+ for (const key of Object.keys(defaults)) {
173
+ if (!["enabled", "permission_policy"].includes(key)) err(`unknown field \`default_config.${key}\``);
174
+ }
145
175
  }
146
176
  }
177
+ checkRows(tool.rows ?? [], err, { known: null });
147
178
  }
148
179
 
149
180
  function checkToolset(tool, err) {
@@ -152,9 +183,15 @@ function checkToolset(tool, err) {
152
183
  const hint = PREBUILT_TOOLS.includes(tool.name) ? `; since 0.2.1 all pre-built tools go in one file, ${TOOLS_DIR}/${TOOLSET_FILE}` : "";
153
184
  return err(`a \`## Tools\` table listing the pre-built tools to enable is required${hint}`);
154
185
  }
186
+ checkRows(tool.rows, err, { known: PREBUILT_TOOLS });
187
+ }
188
+
189
+ // The rows of a `## Tools` table. `known` is the list of valid tool names, when there is one.
190
+ function checkRows(rows, err, { known }) {
155
191
  const seen = new Set();
156
- for (const row of tool.rows) {
157
- if (!PREBUILT_TOOLS.includes(row.name)) err(`\`${row.name}\` is not a pre-built tool; use ${PREBUILT_TOOLS.join(", ")}`);
192
+ for (const row of rows) {
193
+ if (!row.name) err("a `## Tools` row has no name");
194
+ else if (known && !known.includes(row.name)) err(`\`${row.name}\` is not a pre-built tool; use ${known.join(", ")}`);
158
195
  else if (seen.has(row.name)) err(`\`${row.name}\` is listed twice`);
159
196
  seen.add(row.name);
160
197
  if (!["true", "false"].includes(row.enabled.toLowerCase())) err(`\`${row.name}\`: Enabled must be true or false`);
@@ -194,21 +231,18 @@ function checkCustom(tool, err) {
194
231
  }
195
232
  }
196
233
 
197
- // The tools list sent to the API: one toolset entry with a config for each row of its table
198
- // (tools it doesn't list keep the API's defaults), then the custom tools, sorted by name.
234
+ // The tools list sent to the API, each kind sorted by name: the pre-built toolset with a config
235
+ // for each row of its table (tools it doesn't list keep the API's defaults), then a toolset for
236
+ // each MCP server, then the custom tools.
199
237
  export function compileTools(tools) {
200
238
  const compiled = [];
201
239
  const toolset = tools.find((t) => t.data.type === TOOLSET);
202
- if (toolset) {
203
- const rows = [...(toolset.rows ?? [])].sort((a, b) => (a.name < b.name ? -1 : 1));
204
- compiled.push({
205
- type: TOOLSET,
206
- configs: rows.map(({ name, enabled, permission }) => {
207
- const config = { name, enabled: enabled.toLowerCase() === "true" };
208
- if (permission) config.permission_policy = { type: permission };
209
- return config;
210
- }),
211
- });
240
+ if (toolset) compiled.push({ type: TOOLSET, configs: configs(toolset.rows) });
241
+ for (const tool of byName(tools.filter((t) => t.data.type === MCP_TOOLSET))) {
242
+ const entry = { type: MCP_TOOLSET, mcp_server_name: tool.name };
243
+ if (tool.data.default_config) entry.default_config = tool.data.default_config;
244
+ if (tool.rows?.length) entry.configs = configs(tool.rows);
245
+ compiled.push(entry);
212
246
  }
213
247
  for (const tool of tools.filter((t) => t.data.type === "custom").sort((a, b) => (a.name < b.name ? -1 : 1))) {
214
248
  compiled.push({ type: "custom", name: tool.name, description: tool.data.description, input_schema: inputSchema(tool.params ?? []) });
@@ -216,6 +250,16 @@ export function compileTools(tools) {
216
250
  return compiled;
217
251
  }
218
252
 
253
+ const byName = (tools) => [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
254
+
255
+ function configs(rows = []) {
256
+ return [...rows].sort((a, b) => (a.name < b.name ? -1 : 1)).map(({ name, enabled, permission }) => {
257
+ const config = { name, enabled: enabled.toLowerCase() === "true" };
258
+ if (permission) config.permission_policy = { type: permission };
259
+ return config;
260
+ });
261
+ }
262
+
219
263
  function inputSchema(params) {
220
264
  const properties = {};
221
265
  for (const p of params) {
package/src/vaults.js ADDED
@@ -0,0 +1,148 @@
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { FileError, parseMarkdown } from "./markdown.js";
4
+
5
+ export const VAULTS_DIR = "vaults";
6
+ export const VAULT_FILE = "vault.md";
7
+ export const MCP_OAUTH = "mcp_oauth";
8
+ export const ENV_VAR = "environment_variable";
9
+ export const CREDENTIAL_TYPES = [MCP_OAUTH, ENV_VAR];
10
+ export const TOKEN_ENDPOINT_AUTH = ["none", "client_secret_basic", "client_secret_post"];
11
+
12
+ // Fields that hold secrets or short-lived values. They never go in a file: `cred deploy`
13
+ // asks for them and sends them straight to the vault.
14
+ export const SECRET_FIELDS = {
15
+ [MCP_OAUTH]: [
16
+ ["access_token"],
17
+ ["expires_at"],
18
+ ["refresh", "refresh_token"],
19
+ ["refresh", "token_endpoint_auth", "client_secret"],
20
+ ],
21
+ [ENV_VAR]: [["secret_value"]],
22
+ };
23
+
24
+ // Fields the API won't change on an existing credential. Changing one in a file is an error;
25
+ // delete the credential and create it again.
26
+ export const IMMUTABLE_FIELDS = {
27
+ [MCP_OAUTH]: [
28
+ ["type"],
29
+ ["mcp_server_url"],
30
+ ["refresh"], // adding or removing the refresh block
31
+ ["refresh", "token_endpoint"],
32
+ ["refresh", "client_id"],
33
+ ["refresh", "resource"],
34
+ ["refresh", "token_endpoint_auth", "type"],
35
+ ],
36
+ [ENV_VAR]: [["type"], ["secret_name"]],
37
+ };
38
+
39
+ // Reads vaults/: each folder is a vault named after the folder, holding an optional vault.md
40
+ // and one .md file per credential, named after the file. Vaults are sorted by name, which is
41
+ // the order `run` attaches them in. A missing vaults/ folder means no vaults.
42
+ // Returns { vaults, errors }; a file that can't be parsed has an entry in errors.
43
+ export function readVaults(dir) {
44
+ const folder = join(dir, VAULTS_DIR);
45
+ try {
46
+ if (!statSync(folder).isDirectory()) return { vaults: [], errors: [`${VAULTS_DIR}: not a directory`] };
47
+ } catch {
48
+ return { vaults: [], errors: [] };
49
+ }
50
+
51
+ const vaults = [];
52
+ const errors = [];
53
+ const parse = (file) => {
54
+ try {
55
+ return parseMarkdown(readFileSync(join(dir, file), "utf8"), file);
56
+ } catch (err) {
57
+ if (!(err instanceof FileError)) throw err;
58
+ errors.push(err.message);
59
+ return null;
60
+ }
61
+ };
62
+
63
+ for (const entry of sorted(readdirSync(folder, { withFileTypes: true }))) {
64
+ if (entry.name.startsWith(".")) continue;
65
+ const path = `${VAULTS_DIR}/${entry.name}`;
66
+ if (!entry.isDirectory()) {
67
+ if (entry.name.endsWith(".md")) errors.push(`${path}: each vault is a folder; put credential files inside one`);
68
+ continue;
69
+ }
70
+
71
+ const vault = { name: entry.name, path, file: null, credentials: [] };
72
+ for (const item of sorted(readdirSync(join(folder, entry.name), { withFileTypes: true }))) {
73
+ if (item.name.startsWith(".")) continue;
74
+ const file = `${path}/${item.name}`;
75
+ if (item.isDirectory()) {
76
+ errors.push(`${file}: a vault holds credential files, not folders`);
77
+ } else if (item.name === VAULT_FILE) {
78
+ vault.file = parse(file);
79
+ } else if (item.name.endsWith(".md")) {
80
+ const parsed = parse(file);
81
+ if (parsed) vault.credentials.push({ file, name: basename(item.name, ".md"), vault: entry.name, ...parsed });
82
+ }
83
+ }
84
+ vaults.push(vault);
85
+ }
86
+ return { vaults, errors };
87
+ }
88
+
89
+ const sorted = (entries) => entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
90
+
91
+ // The lock file keys for a vault and a credential.
92
+ export const vaultKey = (vault) => `./${vault.path}`;
93
+ export const credentialKey = (cred) => `./${cred.file}`;
94
+
95
+ // The body sent to POST /v1/vaults: the folder name and vault.md's metadata.
96
+ export function vaultBody(vault) {
97
+ const body = { display_name: vault.name };
98
+ if (vault.file?.data.metadata !== undefined) body.metadata = vault.file.data.metadata;
99
+ return body;
100
+ }
101
+
102
+ // A credential's settings from its file: everything but the secrets. This is what's hashed
103
+ // into the lock, and what deploy keeps in sync.
104
+ export function credentialSettings(cred) {
105
+ const body = { display_name: cred.name, auth: structuredClone(cred.data.auth) };
106
+ if (cred.data.metadata !== undefined) body.metadata = cred.data.metadata;
107
+ return body;
108
+ }
109
+
110
+ // The body sent to create a credential: its settings plus the secrets `cred deploy` asked for.
111
+ export function credentialCreateBody(cred, { accessToken, expiresAt, refreshToken, clientSecret, secretValue }) {
112
+ const body = credentialSettings(cred);
113
+ if (body.auth.type === ENV_VAR) {
114
+ body.auth.secret_value = secretValue;
115
+ return body;
116
+ }
117
+ body.auth.access_token = accessToken;
118
+ if (expiresAt) body.auth.expires_at = expiresAt;
119
+ if (body.auth.refresh) {
120
+ body.auth.refresh.refresh_token = refreshToken;
121
+ if (body.auth.refresh.token_endpoint_auth?.type !== "none") body.auth.refresh.token_endpoint_auth.client_secret = clientSecret;
122
+ }
123
+ return body;
124
+ }
125
+
126
+ // Which secrets a credential file needs when it's created.
127
+ export function secretsNeeded(cred) {
128
+ const refresh = cred.data.auth?.refresh;
129
+ return {
130
+ refreshToken: Boolean(refresh),
131
+ clientSecret: Boolean(refresh) && refresh.token_endpoint_auth?.type !== "none",
132
+ };
133
+ }
134
+
135
+ // The immutable fields whose value in the file differs from the deployed credential's.
136
+ export function changedImmutableFields(cred, remoteAuth) {
137
+ const local = cred.data.auth ?? {};
138
+ const changed = [];
139
+ for (const path of IMMUTABLE_FIELDS[local.type] ?? []) {
140
+ const a = get(local, path);
141
+ const b = get(remoteAuth ?? {}, path);
142
+ const differs = path.length === 1 && path[0] === "refresh" ? Boolean(a) !== Boolean(b) : (a ?? null) !== (b ?? null);
143
+ if (differs) changed.push(path.join("."));
144
+ }
145
+ return changed;
146
+ }
147
+
148
+ export const get = (obj, path) => path.reduce((o, k) => (o && typeof o === "object" ? o[k] : undefined), obj);