@agentsky/sky 3.43.0 → 3.45.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,555 @@
1
+ import {
2
+ api
3
+ } from "./chunk-WLTOVOTW.js";
4
+ import {
5
+ SKILL_NAME
6
+ } from "./chunk-OBRH43HE.js";
7
+ import {
8
+ configPath
9
+ } from "./chunk-XHZJG3QT.js";
10
+
11
+ // src/local-agents.ts
12
+ import { existsSync } from "fs";
13
+ import { homedir } from "os";
14
+ import { join } from "path";
15
+ function localAgents(env = process.env, home = homedir()) {
16
+ const claude = env.CLAUDE_CONFIG_DIR || join(home, ".claude");
17
+ const codex = env.CODEX_HOME || join(home, ".codex");
18
+ const cursor = join(home, ".cursor");
19
+ const grok = env.GROK_HOME || join(home, ".grok");
20
+ return [
21
+ { id: "claude_code", name: "Claude Code", root: claude, skillsDir: join(claude, "skills") },
22
+ { id: "codex", name: "Codex", root: codex, skillsDir: join(codex, "skills") },
23
+ { id: "cursor", name: "Cursor", root: cursor, skillsDir: join(cursor, "skills") },
24
+ { id: "grok", name: "Grok", root: grok, skillsDir: join(grok, "skills") }
25
+ ];
26
+ }
27
+ function detectLocalAgents(env = process.env, home = homedir()) {
28
+ return localAgents(env, home).filter((agent) => existsSync(agent.root));
29
+ }
30
+ function selectLocalAgents(ids, env = process.env, home = homedir()) {
31
+ if (!ids?.length) return detectLocalAgents(env, home);
32
+ const known = localAgents(env, home);
33
+ return ids.map((id) => {
34
+ const agent = known.find((candidate) => candidate.id === id);
35
+ if (!agent) throw new Error(`unknown agent ${id} \u2014 expected ${known.map((candidate) => candidate.id).join(" | ")}`);
36
+ return agent;
37
+ });
38
+ }
39
+
40
+ // src/mcp-register.ts
41
+ import { existsSync as existsSync2, readFileSync, writeFileSync } from "fs";
42
+ import { spawnSync } from "child_process";
43
+ import { homedir as homedir2 } from "os";
44
+ import { join as join2 } from "path";
45
+ import { parse as parseToml } from "smol-toml";
46
+ import { isMap, parseDocument } from "yaml";
47
+
48
+ // ../../packages/spec/src/mcp-tool-list.ts
49
+ var MCP_TOOL_LIST_PARAM = "tools";
50
+ function mcpUrlWithToolList(mcpUrl, list) {
51
+ const url = new URL(mcpUrl);
52
+ if (list === "short") url.searchParams.set(MCP_TOOL_LIST_PARAM, "short");
53
+ else url.searchParams.delete(MCP_TOOL_LIST_PARAM);
54
+ return url.toString();
55
+ }
56
+ function mcpToolListOf(mcpUrl) {
57
+ const value = (typeof mcpUrl === "string" ? new URL(mcpUrl) : mcpUrl).searchParams.get(MCP_TOOL_LIST_PARAM);
58
+ if (value === null) return "every";
59
+ return value === "short" || value === "every" ? value : null;
60
+ }
61
+
62
+ // src/mcp-register.ts
63
+ var MCP_SERVER_NAME = SKILL_NAME;
64
+ function detectHermes(env = process.env, home = homedir2()) {
65
+ const root = env.HERMES_HOME || join2(home, ".hermes");
66
+ return existsSync2(root) ? { id: "hermes", name: "Hermes", root } : null;
67
+ }
68
+ function claudeAppRoot(env = process.env, home = homedir2(), platform = process.platform) {
69
+ if (platform === "darwin") return join2(home, "Library", "Application Support", "Claude");
70
+ if (platform === "win32") return join2(env.APPDATA || join2(home, "AppData", "Roaming"), "Claude");
71
+ return join2(env.XDG_CONFIG_HOME || join2(home, ".config"), "Claude");
72
+ }
73
+ function detectClaudeApp(env = process.env, home = homedir2(), platform = process.platform) {
74
+ const root = claudeAppRoot(env, home, platform);
75
+ return existsSync2(root) ? { id: "claude_app", name: "Claude app", root } : null;
76
+ }
77
+ function detectMcpClients(env = process.env, home = homedir2(), platform = process.platform) {
78
+ const hermes = detectHermes(env, home);
79
+ const claudeApp = detectClaudeApp(env, home, platform);
80
+ return [...detectLocalAgents(env, home), ...hermes ? [hermes] : [], ...claudeApp ? [claudeApp] : []];
81
+ }
82
+ function systemCommandRunner() {
83
+ return {
84
+ has: (command) => spawnSync(command, ["--version"], { stdio: "ignore" }).status === 0,
85
+ run: (command, args) => {
86
+ const result = spawnSync(command, args, { encoding: "utf8" });
87
+ return { status: result.status, stderr: result.stderr ?? "", stdout: result.stdout ?? "" };
88
+ }
89
+ };
90
+ }
91
+ function mcpUrlFor(apiBase, list = "every") {
92
+ return mcpUrlWithToolList(`${apiBase.replace(/\/$/, "")}/mcp`, list);
93
+ }
94
+ function mcpCommands(agent, opts) {
95
+ if (agent === "claude_code") {
96
+ return {
97
+ command: "claude",
98
+ remove: ["mcp", "remove", "--scope", "user", MCP_SERVER_NAME],
99
+ add: ["mcp", "add", "--scope", "user", "--transport", "http", MCP_SERVER_NAME, opts.mcpUrl, "--header", `Authorization: Bearer ${opts.token}`]
100
+ };
101
+ }
102
+ if (agent === "grok") {
103
+ return {
104
+ command: "grok",
105
+ remove: ["mcp", "remove", MCP_SERVER_NAME],
106
+ add: ["mcp", "add", "--scope", "user", "--transport", "http", "--header", `Authorization: Bearer ${opts.token}`, MCP_SERVER_NAME, opts.mcpUrl]
107
+ };
108
+ }
109
+ return null;
110
+ }
111
+ function redact(text2, token) {
112
+ return text2.split(token).join(`${token.slice(0, 10)}\u2026`);
113
+ }
114
+ function registerMcpServer(client, opts, runner = systemCommandRunner()) {
115
+ if (client.id === "codex") return registerCodex(client, opts);
116
+ if (client.id === "cursor") return registerCursor(client, opts);
117
+ if (client.id === "hermes") return registerHermes(client, opts);
118
+ if (client.id === "claude_app") return registerClaudeApp(client, opts);
119
+ const commands = mcpCommands(client.id, opts);
120
+ if (!commands) return { agent: client.id, outcome: "unsupported" };
121
+ if (!runner.has(commands.command)) return { agent: client.id, outcome: "no_command", detail: `${commands.command} is not on PATH` };
122
+ if (opts.dryRun) return { agent: client.id, outcome: "planned", detail: redact(`run ${[commands.command, ...commands.add].join(" ")}`, opts.token) };
123
+ runner.run(commands.command, commands.remove);
124
+ const added = runner.run(commands.command, commands.add);
125
+ if (added.status !== 0) return { agent: client.id, outcome: "failed", detail: redact(added.stderr.trim() || `exit ${added.status}`, opts.token) };
126
+ return { agent: client.id, outcome: "registered" };
127
+ }
128
+ function mcpConfigPath(client, env = process.env, home = homedir2()) {
129
+ switch (client.id) {
130
+ case "claude_code":
131
+ return join2(env.CLAUDE_CONFIG_DIR || home, ".claude.json");
132
+ case "codex":
133
+ case "grok":
134
+ return join2(client.root, "config.toml");
135
+ case "cursor":
136
+ return join2(client.root, "mcp.json");
137
+ case "hermes":
138
+ return join2(client.root, "config.yaml");
139
+ case "claude_app":
140
+ return join2(client.root, "claude_desktop_config.json");
141
+ }
142
+ }
143
+ function readText(path) {
144
+ try {
145
+ return readFileSync(path, "utf8");
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+ function registeredMcpUrl(client, env = process.env, home = homedir2()) {
151
+ const raw = readText(mcpConfigPath(client, env, home));
152
+ if (raw === null) return null;
153
+ try {
154
+ let entry;
155
+ if (client.id === "codex" || client.id === "grok") entry = parseToml(raw).mcp_servers?.[MCP_SERVER_NAME];
156
+ else if (client.id === "hermes") entry = parseDocument(raw).toJS()?.mcp_servers?.[MCP_SERVER_NAME];
157
+ else entry = JSON.parse(raw).mcpServers?.[MCP_SERVER_NAME];
158
+ const url = entry?.url;
159
+ return typeof url === "string" ? url : null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+ function registeredToolList(client, env = process.env, home = homedir2()) {
165
+ const url = registeredMcpUrl(client, env, home);
166
+ if (url === null) return "every";
167
+ try {
168
+ return mcpToolListOf(url) === "short" ? "short" : "every";
169
+ } catch {
170
+ return "every";
171
+ }
172
+ }
173
+ function hasMcpServer(client, env = process.env, home = homedir2()) {
174
+ const raw = readText(mcpConfigPath(client, env, home));
175
+ if (raw === null) return false;
176
+ try {
177
+ if (client.id === "codex" || client.id === "grok") return Boolean(parseToml(raw).mcp_servers?.[MCP_SERVER_NAME]);
178
+ if (client.id === "hermes") return parseDocument(raw).hasIn(["mcp_servers", MCP_SERVER_NAME]);
179
+ return Boolean(JSON.parse(raw).mcpServers?.[MCP_SERVER_NAME]);
180
+ } catch {
181
+ return false;
182
+ }
183
+ }
184
+ function planned(client, path, entry, opts) {
185
+ return { agent: client.id, outcome: "planned", detail: `write to ${path}: ${redact(entry, opts.token)}` };
186
+ }
187
+ function written(client, path, text2) {
188
+ try {
189
+ writeFileSync(path, text2, { encoding: "utf8", mode: 384 });
190
+ } catch (err) {
191
+ return { agent: client.id, outcome: "failed", detail: String(err) };
192
+ }
193
+ return { agent: client.id, outcome: "registered" };
194
+ }
195
+ function tomlTableKey(name) {
196
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
197
+ return `(?:${escaped}|"${escaped}"|'${escaped}')`;
198
+ }
199
+ function withoutTomlServer(text2, name) {
200
+ const ours = new RegExp(`^\\s*\\[\\s*mcp_servers\\s*\\.\\s*${tomlTableKey(name)}\\s*(?:\\.[^\\]]*)?\\]\\s*(?:#.*)?$`);
201
+ let skipping = false;
202
+ const kept = [];
203
+ for (const line of text2.split(/\r?\n/)) {
204
+ if (/^\s*\[/.test(line)) skipping = ours.test(line);
205
+ if (!skipping) kept.push(line);
206
+ }
207
+ return kept.join("\n").replace(/\n+$/, "");
208
+ }
209
+ function registerCodex(client, opts) {
210
+ const path = mcpConfigPath(client);
211
+ const block = [
212
+ `[mcp_servers.${MCP_SERVER_NAME}]`,
213
+ `url = ${JSON.stringify(opts.mcpUrl)}`,
214
+ `http_headers = { Authorization = ${JSON.stringify(`Bearer ${opts.token}`)} }`
215
+ ].join("\n");
216
+ if (opts.dryRun) return planned(client, path, block, opts);
217
+ const raw = readText(path) ?? "";
218
+ let before;
219
+ try {
220
+ before = parseToml(raw);
221
+ } catch (err) {
222
+ return { agent: client.id, outcome: "failed", detail: `${path} is not valid TOML, left as it was (${String(err).split("\n")[0]})` };
223
+ }
224
+ const rest = withoutTomlServer(raw, MCP_SERVER_NAME);
225
+ const text2 = `${rest ? `${rest}
226
+
227
+ ` : ""}${block}
228
+ `;
229
+ try {
230
+ const after = parseToml(text2);
231
+ const others = Object.keys(before.mcp_servers ?? {}).filter((name) => name !== MCP_SERVER_NAME);
232
+ if (after.mcp_servers?.[MCP_SERVER_NAME]?.url !== opts.mcpUrl || others.some((name) => !after.mcp_servers?.[name])) throw new Error("the edited file lost an entry");
233
+ } catch (err) {
234
+ return { agent: client.id, outcome: "failed", detail: `could not edit ${path} safely, left as it was (${String(err).split("\n")[0]})` };
235
+ }
236
+ return written(client, path, text2);
237
+ }
238
+ function registerCursor(client, opts) {
239
+ const path = mcpConfigPath(client);
240
+ const entry = { url: opts.mcpUrl, headers: { Authorization: `Bearer ${opts.token}` } };
241
+ if (opts.dryRun) return planned(client, path, JSON.stringify({ [MCP_SERVER_NAME]: entry }, null, 2), opts);
242
+ let existing = {};
243
+ try {
244
+ const parsed = JSON.parse(readText(path) ?? "");
245
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) existing = parsed;
246
+ } catch {
247
+ existing = {};
248
+ }
249
+ const updated = { ...existing, mcpServers: { ...existing.mcpServers ?? {}, [MCP_SERVER_NAME]: entry } };
250
+ return written(client, path, `${JSON.stringify(updated, null, 2)}
251
+ `);
252
+ }
253
+ function registerClaudeApp(client, opts) {
254
+ if (!opts.sky?.length) return { agent: client.id, outcome: "unsupported", detail: "no sky command to start" };
255
+ const path = mcpConfigPath(client);
256
+ const [command, ...args] = opts.sky;
257
+ const entry = { command, args: [...args, "mcp", "serve"] };
258
+ if (opts.dryRun) return planned(client, path, JSON.stringify({ [MCP_SERVER_NAME]: entry }, null, 2), opts);
259
+ let existing = {};
260
+ const raw = readText(path);
261
+ if (raw !== null && raw.trim()) {
262
+ try {
263
+ const parsed = JSON.parse(raw);
264
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
265
+ existing = parsed;
266
+ } catch (err) {
267
+ return { agent: client.id, outcome: "failed", detail: `${path} is not valid JSON, left as it was (${String(err).split("\n")[0]})` };
268
+ }
269
+ }
270
+ const current = existing.mcpServers?.[MCP_SERVER_NAME];
271
+ if (JSON.stringify(current) === JSON.stringify(entry)) return { agent: client.id, outcome: "registered", detail: "already registered" };
272
+ const updated = { ...existing, mcpServers: { ...existing.mcpServers ?? {}, [MCP_SERVER_NAME]: entry } };
273
+ return written(client, path, `${JSON.stringify(updated, null, 2)}
274
+ `);
275
+ }
276
+ function registerHermes(client, opts) {
277
+ const path = mcpConfigPath(client);
278
+ const entry = { url: opts.mcpUrl, headers: { Authorization: `Bearer ${opts.token}` } };
279
+ if (opts.dryRun) return planned(client, path, `mcp_servers.${MCP_SERVER_NAME}: ${JSON.stringify(entry)}`, opts);
280
+ const doc = parseDocument(readText(path) ?? "");
281
+ if (doc.errors.length) return { agent: client.id, outcome: "failed", detail: `${path} is not valid YAML, left as it was (${doc.errors[0].message.split("\n")[0]})` };
282
+ if (doc.contents !== null && !isMap(doc.contents)) {
283
+ return { agent: client.id, outcome: "failed", detail: `${path} is not a YAML mapping, left as it was` };
284
+ }
285
+ doc.setIn(["mcp_servers", MCP_SERVER_NAME], doc.createNode(entry));
286
+ return written(client, path, doc.toString());
287
+ }
288
+ function refreshMcpRegistrations(opts, clients = detectMcpClients(), runner = systemCommandRunner(), env = process.env, home = homedir2()) {
289
+ return clients.filter((client) => client.id !== "claude_app" && hasMcpServer(client, env, home)).map((client) => registerMcpServer(client, { token: opts.token, mcpUrl: mcpUrlFor(opts.apiBase, registeredToolList(client, env, home)) }, runner));
290
+ }
291
+
292
+ // src/settings-block.ts
293
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
294
+ import { homedir as homedir3 } from "os";
295
+ import { dirname, join as join3 } from "path";
296
+
297
+ // ../../packages/uikit-components/src/rules-model.ts
298
+ var ACTIONS = { deny: "block", ask: "ask first", allow: "allow", block: "block", require_approval: "ask first", model_review: "ask only when a model is unsure", notify: "notify a webhook" };
299
+ var PLUGIN_ACTIONS = { allow: "allow", ask: "ask first", deny: "block", deny_writes: "read only, no changes", off: "off", on_exception: "off unless allowed for a chat", ask_to_enable: "ask before turning on" };
300
+ function action(value, words = ACTIONS) {
301
+ const raw = text(value);
302
+ return words[raw] ?? raw.replace(/_/g, " ");
303
+ }
304
+ function toolDisplayName(id) {
305
+ const raw = id.trim();
306
+ const app = /^(?:app|connector|plugin):(.+)$/i.exec(raw);
307
+ if (app) return appDisplayName(app[1]);
308
+ const mcp = /^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(raw);
309
+ if (mcp) return `${appDisplayName(mcp[1])} ${mcp[2].replace(/[_-]+/g, " ")}`;
310
+ if (/^[a-z][a-z0-9_-]*$/.test(raw) && APP_NAMES[raw.toLowerCase()]) return appDisplayName(raw);
311
+ return raw;
312
+ }
313
+ function text(value) {
314
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
315
+ }
316
+ function dollars(micros) {
317
+ return typeof micros === "number" ? `$${(micros / 1e6).toFixed(2)}` : "";
318
+ }
319
+ var APP_NAMES = {
320
+ gmail: "Gmail",
321
+ github: "GitHub",
322
+ gitlab: "GitLab",
323
+ hubspot: "HubSpot",
324
+ linkedin: "LinkedIn",
325
+ youtube: "YouTube",
326
+ google_calendar: "Google Calendar",
327
+ google_drive: "Google Drive",
328
+ google_docs: "Google Docs",
329
+ google_sheets: "Google Sheets",
330
+ notion: "Notion",
331
+ slack: "Slack",
332
+ linear: "Linear",
333
+ jira: "Jira",
334
+ figma: "Figma",
335
+ stripe: "Stripe",
336
+ salesforce: "Salesforce",
337
+ whatsapp: "WhatsApp",
338
+ wechat: "WeChat",
339
+ outlook: "Outlook",
340
+ dropbox: "Dropbox",
341
+ airtable: "Airtable",
342
+ asana: "Asana"
343
+ };
344
+ function appDisplayName(slug) {
345
+ const key = slug.trim().toLowerCase();
346
+ return APP_NAMES[key] ?? key.split(/[_-]+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
347
+ }
348
+ function triggerMessage(point, match = {}) {
349
+ switch (point) {
350
+ case "tool.call":
351
+ return match.connector_app ? { key: "Before {app} is used", values: { app: appDisplayName(text(match.connector_app)) } } : match.capability_id ? { key: "Before the built-in tool {tool} is used", values: { tool: text(match.capability_id) } } : { key: "Before any tool is used" };
352
+ case "session.start":
353
+ return match.agent_id ? { key: "When a chat starts with one particular agent" } : { key: "When a chat starts" };
354
+ case "spend":
355
+ return { key: "When a chat's spending reaches {amount}", values: { amount: match.amount ? `$${(Number(match.amount) / 100).toFixed(2)}` : "" } };
356
+ case "turn.end":
357
+ return match.agent_id ? { key: "When one particular agent finishes a turn" } : { key: "When an agent finishes a turn" };
358
+ default:
359
+ return { key: "At {point}", values: { point } };
360
+ }
361
+ }
362
+ function ruleMessage(rule) {
363
+ const config = rule.config ?? {};
364
+ switch (rule.kind) {
365
+ case "tool_call": {
366
+ const said = action(config.action);
367
+ return config.matcher ? { key: "Before {tool} is used: {action}", values: { action: said, tool: toolDisplayName(text(config.matcher)) } } : { key: "Before any tool is used: {action}", values: { action: said } };
368
+ }
369
+ case "spend_cap":
370
+ return config.warnUsdMicros !== void 0 && config.warnUsdMicros !== null ? { key: "Ask at {warn}, stop at {cap}", values: { warn: dollars(config.warnUsdMicros), cap: dollars(config.hardCapUsdMicros) } } : { key: "Stop spending at {cap}", values: { cap: dollars(config.hardCapUsdMicros) } };
371
+ case "call_count":
372
+ return { key: "At most {count} tool calls in a chat", values: { count: text(config.limitPerSession) } };
373
+ case "capability": {
374
+ const items = Object.entries(config).map(([tool, verdict]) => ({ what: toolDisplayName(tool), action: action(verdict) }));
375
+ return items.length === 1 ? { key: "{what}: {action}", values: items[0] } : { key: "Built-in tools: {list}", values: { list: "" }, items };
376
+ }
377
+ case "hook": {
378
+ const when = triggerMessage(text(config.point), config.match ?? {});
379
+ return { key: `${when.key}: {action}`, values: { ...when.values, action: action(config.action) } };
380
+ }
381
+ case "sky": {
382
+ const what = config.connector_app ? appDisplayName(text(config.connector_app)) : config.capability_id ? toolDisplayName(text(config.capability_id)) : config.spend_over_cents ? `$${(Number(config.spend_over_cents) / 100).toFixed(2)}` : text(config.text);
383
+ return { key: "{what}: {action}", values: { action: action(config.effect), what } };
384
+ }
385
+ case "plugin": {
386
+ const items = Object.entries(config).map(([plugin, verdict]) => ({ what: toolDisplayName(plugin), action: action(verdict, PLUGIN_ACTIONS) }));
387
+ return items.length === 1 ? { key: "{what}: {action}", values: items[0] } : { key: "Plugins: {list}", values: { list: "" }, items };
388
+ }
389
+ }
390
+ }
391
+ var TRANSLATED_VALUES = ["action", "verdict", "scope"];
392
+ function renderRuleMessage(message, t) {
393
+ const values = Object.fromEntries(Object.entries(message.values ?? {}).map(([name, value]) => [name, TRANSLATED_VALUES.includes(name) ? t(value) : value]));
394
+ if (message.items) values.list = message.items.map((item) => t("{what}: {action}", { what: item.what, action: t(item.action) })).join(t(", "));
395
+ return t(message.key, values);
396
+ }
397
+
398
+ // src/settings-block.ts
399
+ var BLOCK_BEGIN = "<!-- agentsky:begin (managed by AgentSky; edit in Settings, not here) -->";
400
+ var BLOCK_END = "<!-- agentsky:end -->";
401
+ var BLOCK_MAX_BYTES = 16 * 1024;
402
+ var BLOCK = /\n?<!-- agentsky:begin[^\n]*-->\n[\s\S]*?\n<!-- agentsky:end -->\n?/;
403
+ function instructionFiles(env = process.env, home = homedir3()) {
404
+ const files = [];
405
+ for (const agent of detectLocalAgents(env, home)) {
406
+ if (agent.id === "claude_code") files.push({ engine: agent.id, name: agent.name, path: join3(agent.root, "CLAUDE.md") });
407
+ if (agent.id === "codex" || agent.id === "cursor") files.push({ engine: agent.id, name: agent.name, path: join3(agent.root, "AGENTS.md") });
408
+ }
409
+ const hermes = detectHermes(env, home);
410
+ if (hermes) files.push({ engine: "hermes", name: hermes.name, path: join3(hermes.root, "SOUL.md") });
411
+ return files;
412
+ }
413
+ function withoutSettingsBlock(text2) {
414
+ return text2.replace(BLOCK, "");
415
+ }
416
+ function settingsBlockOf(text2) {
417
+ return BLOCK.exec(text2)?.[0].replace(/^\n+/, "").replace(/\n$/, "") ?? null;
418
+ }
419
+ function withSettingsBlock(text2, block) {
420
+ if (BLOCK.test(text2)) return text2.replace(BLOCK, (match) => `${match.startsWith("\n") ? "\n" : ""}${block}
421
+ `);
422
+ if (!text2.trim()) return `${block}
423
+ `;
424
+ return `${text2}${text2.endsWith("\n") ? "" : "\n"}
425
+ ${block}
426
+ `;
427
+ }
428
+ function cut(text2, limit) {
429
+ if (limit === null || text2.length <= limit) return text2;
430
+ return `${text2.slice(0, limit).trimEnd()}
431
+ \u2026`;
432
+ }
433
+ function renderSettingsBlock(settings) {
434
+ const parts = [`These are the settings of the AgentSky workspace ${settings.workspace}. Change them in AgentSky's Settings; this block is rewritten to match.`];
435
+ for (const file of settings.files) parts.push(`## ${file.purpose} (${file.path})
436
+
437
+ ${cut(file.content.trim(), file.limitChars)}`);
438
+ if (settings.rules.length) parts.push(`## Rules
439
+
440
+ AgentSky enforces these where it runs the work; follow them here too.
441
+
442
+ ${settings.rules.map((rule) => `- ${rule}`).join("\n")}`);
443
+ if (settings.plugins.length) parts.push(`## Plugins on for your agents
444
+
445
+ ${settings.plugins.join(", ")}. List them with the agentsky MCP server's list_plugins and use one with call_plugin.`);
446
+ let body = parts.join("\n\n");
447
+ const room = BLOCK_MAX_BYTES - Buffer.byteLength(`${BLOCK_BEGIN}
448
+
449
+ ${BLOCK_END}`) - 200;
450
+ if (Buffer.byteLength(body) > room) {
451
+ while (Buffer.byteLength(body) > room) body = body.slice(0, Math.floor(body.length * 0.9));
452
+ body = `${body.trimEnd()}
453
+
454
+ \u2026 The rest is in AgentSky's Settings (Rules, Memory) and through the agentsky MCP server's search_context.`;
455
+ }
456
+ return `${BLOCK_BEGIN}
457
+ ${body}
458
+ ${BLOCK_END}`;
459
+ }
460
+ async function readWorkspaceSettings(workspace) {
461
+ const { workspace_context: context } = await api("GET", "/workspace-context");
462
+ const files = [];
463
+ if (context.memory_store_id && context.loads_by_default) {
464
+ for (const file of context.always_loaded) {
465
+ if (!file.exists || !file.memory_id) continue;
466
+ const { memory } = await api("GET", `/memory_stores/${encodeURIComponent(context.memory_store_id)}/memories/${encodeURIComponent(file.memory_id)}`);
467
+ if (memory.content.trim()) files.push({ path: file.path, purpose: file.purpose, content: memory.content, limitChars: file.limit_chars });
468
+ }
469
+ }
470
+ const { rules } = await api("GET", "/rules");
471
+ const words = (key, values) => key.replace(/\{(\w+)\}/g, (_, name) => values?.[name] ?? "");
472
+ const said = rules.filter((rule) => rule.enabled && rule.kind !== "plugin").map((rule) => renderRuleMessage(ruleMessage(rule), words));
473
+ const { data } = await api("GET", "/plugins?view=yours");
474
+ const plugins = data.filter((plugin) => plugin.status === "added" && !plugin.uses.every((use) => use === "skills")).map((plugin) => plugin.name);
475
+ return { workspace, files, rules: said, plugins };
476
+ }
477
+ function settingsCachePath() {
478
+ return join3(dirname(configPath()), "settings-block.md");
479
+ }
480
+ function cachedSettingsBlock() {
481
+ try {
482
+ return readFileSync2(settingsCachePath(), "utf8");
483
+ } catch {
484
+ return null;
485
+ }
486
+ }
487
+ function writeSettingsBlocks(block, opts) {
488
+ const outcomes = [];
489
+ for (const file of opts.files ?? instructionFiles()) {
490
+ let text2 = "";
491
+ try {
492
+ text2 = readFileSync2(file.path, "utf8");
493
+ } catch {
494
+ text2 = "";
495
+ }
496
+ if (settingsBlockOf(text2) === block) {
497
+ outcomes.push({ engine: file.engine, path: file.path, outcome: "current" });
498
+ continue;
499
+ }
500
+ if (opts.dryRun) {
501
+ outcomes.push({ engine: file.engine, path: file.path, outcome: "planned" });
502
+ continue;
503
+ }
504
+ try {
505
+ opts.journal.track(file.path, ["settings_block"]);
506
+ mkdirSync(dirname(file.path), { recursive: true });
507
+ writeFileSync2(file.path, withSettingsBlock(text2, block));
508
+ outcomes.push({ engine: file.engine, path: file.path, outcome: "written" });
509
+ } catch (error) {
510
+ outcomes.push({ engine: file.engine, path: file.path, outcome: "failed", detail: error instanceof Error ? error.message : String(error) });
511
+ }
512
+ }
513
+ if (!opts.dryRun && cachedSettingsBlock() !== block) {
514
+ const cache = settingsCachePath();
515
+ if (!existsSync3(cache)) opts.journal.own(cache);
516
+ mkdirSync(dirname(cache), { recursive: true });
517
+ writeFileSync2(cache, block, { mode: 384 });
518
+ }
519
+ return outcomes;
520
+ }
521
+ function settingsBlockState(block, file) {
522
+ let text2 = "";
523
+ try {
524
+ text2 = readFileSync2(file.path, "utf8");
525
+ } catch {
526
+ return "missing";
527
+ }
528
+ const held = settingsBlockOf(text2);
529
+ if (held === null) return "missing";
530
+ return block === null || held === block ? "current" : "behind";
531
+ }
532
+
533
+ export {
534
+ detectLocalAgents,
535
+ selectLocalAgents,
536
+ MCP_SERVER_NAME,
537
+ detectHermes,
538
+ detectClaudeApp,
539
+ detectMcpClients,
540
+ systemCommandRunner,
541
+ mcpUrlFor,
542
+ registerMcpServer,
543
+ mcpConfigPath,
544
+ registeredToolList,
545
+ hasMcpServer,
546
+ withoutTomlServer,
547
+ refreshMcpRegistrations,
548
+ instructionFiles,
549
+ withoutSettingsBlock,
550
+ renderSettingsBlock,
551
+ readWorkspaceSettings,
552
+ cachedSettingsBlock,
553
+ writeSettingsBlocks,
554
+ settingsBlockState
555
+ };