@instruction.md/agents 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/NOTICE +73 -0
- package/README.md +204 -2
- package/dist/accounts.js +327 -0
- package/dist/acp.js +268 -0
- package/dist/agent.d.ts +60 -0
- package/dist/agent.js +86 -0
- package/dist/apply.js +392 -0
- package/dist/connect.js +138 -0
- package/dist/converse.js +256 -0
- package/dist/fleet.js +1002 -0
- package/dist/hook.js +406 -0
- package/dist/hosts.js +151 -0
- package/dist/main.js +119 -0
- package/dist/oauth.js +374 -0
- package/dist/pi.d.ts +59 -0
- package/dist/pi.js +89 -0
- package/dist/setup.js +324 -0
- package/dist/sync.js +114 -0
- package/dist/turns.js +143 -0
- package/package.json +70 -3
package/dist/apply.js
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// src/apply.ts
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { githubSkillUrl, loadYaml, machineryOf, normalizeTarget, remoteTargets, sha256Hex } from "instruction.md";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { accountsPath, entryFor, loadAccounts } from "./accounts.js";
|
|
7
|
+
import { atomicWrite } from "instruction.md/cli";
|
|
8
|
+
import { syncName } from "./sync.js";
|
|
9
|
+
var APPLY_HOSTS = ["claude-code", "codex"];
|
|
10
|
+
var APPLIED_FILE = join(".instruction", "applied.json");
|
|
11
|
+
var FLEET_MCP = join(".instruction", "mcp.json");
|
|
12
|
+
var FLEET_CLAUDE_SETTINGS = join(".instruction", "claude-settings.json");
|
|
13
|
+
var DEFAULT_CLI = "npx -y @instruction.md/agents";
|
|
14
|
+
var SKILL_CAP = 256 * 1024;
|
|
15
|
+
var MARK = "<!-- instruction.md: skill";
|
|
16
|
+
var claudeToolName = (server, tool) => `mcp__${server.replace(/[^a-zA-Z0-9_-]/g, "_")}__${tool.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
|
|
17
|
+
var shellWord = (s) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
|
|
18
|
+
function readApplied(dir) {
|
|
19
|
+
try {
|
|
20
|
+
const a = JSON.parse(readFileSync(join(dir, APPLIED_FILE), "utf8"));
|
|
21
|
+
return a.format === "instruction-applied/1" ? a : null;
|
|
22
|
+
} catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function helperFor(s, cli, accounts, accountsFile) {
|
|
27
|
+
if (!s.account && !entryFor(accounts, s.id)) return void 0;
|
|
28
|
+
const usual = join(homedir(), ".config", "instruction-md", "accounts.json");
|
|
29
|
+
const file = accountsFile ?? accountsPath();
|
|
30
|
+
return `${cli} credential ${shellWord(s.id)}${s.account ? ` --account ${shellWord(s.account)}` : ""} --url ${shellWord(s.url)}${file !== usual ? ` --accounts ${shellWord(file)}` : ""}`;
|
|
31
|
+
}
|
|
32
|
+
function codexEnvAuth(s, accounts) {
|
|
33
|
+
const e = entryFor(accounts, s.id, s.account)?.entry;
|
|
34
|
+
if (!e?.env) return null;
|
|
35
|
+
const header = e.header ?? "Authorization", scheme = e.scheme ?? "Bearer";
|
|
36
|
+
if (header.toLowerCase() === "authorization" && scheme === "Bearer") return { bearer: e.env };
|
|
37
|
+
if (scheme === "") return { headers: { [header]: e.env } };
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
var parseJson = (text, file) => {
|
|
41
|
+
if (!text?.trim()) return {};
|
|
42
|
+
try {
|
|
43
|
+
const v = JSON.parse(text);
|
|
44
|
+
if (v && typeof v === "object" && !Array.isArray(v)) return v;
|
|
45
|
+
} catch (e) {
|
|
46
|
+
throw new Error(`${file} is not JSON (${e.message}); fix it, or remove it`);
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`${file} is not a JSON object`);
|
|
49
|
+
};
|
|
50
|
+
var asObj = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
51
|
+
function mergeMcpJson(text, servers, owned, helper, file = ".mcp.json") {
|
|
52
|
+
const o = parseJson(text, file);
|
|
53
|
+
const all = { ...asObj(o.mcpServers) };
|
|
54
|
+
const conflicts = [], mine = [];
|
|
55
|
+
const want = new Set(servers.map((s) => s.id));
|
|
56
|
+
for (const n of owned) if (!want.has(n)) delete all[n];
|
|
57
|
+
for (const s of servers) {
|
|
58
|
+
if (all[s.id] !== void 0 && !owned.includes(s.id)) {
|
|
59
|
+
conflicts.push(`${file}: ${s.id}`);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const h = helper(s);
|
|
63
|
+
all[s.id] = { type: "http", url: s.url, ...h ? { headersHelper: h } : {} };
|
|
64
|
+
mine.push(s.id);
|
|
65
|
+
}
|
|
66
|
+
o.mcpServers = all;
|
|
67
|
+
return { text: `${JSON.stringify(o, null, 2)}
|
|
68
|
+
`, owned: mine, conflicts };
|
|
69
|
+
}
|
|
70
|
+
function mergeClaudePermissions(text, servers, owned, file = ".claude/settings.json") {
|
|
71
|
+
const o = parseJson(text, file);
|
|
72
|
+
const p = { ...asObj(o.permissions) };
|
|
73
|
+
const ours = new Set(owned);
|
|
74
|
+
const allow = (Array.isArray(p.allow) ? p.allow.map(String) : []).filter((r) => !ours.has(r));
|
|
75
|
+
const deny = (Array.isArray(p.deny) ? p.deny.map(String) : []).filter((r) => !ours.has(r));
|
|
76
|
+
const mine = [];
|
|
77
|
+
for (const s of servers) {
|
|
78
|
+
for (const t of s.deny ?? []) {
|
|
79
|
+
const r = claudeToolName(s.id, t);
|
|
80
|
+
if (!deny.includes(r)) {
|
|
81
|
+
deny.push(r);
|
|
82
|
+
mine.push(r);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
for (const t of s.allow ?? []) {
|
|
86
|
+
const r = claudeToolName(s.id, t);
|
|
87
|
+
if (!allow.includes(r)) {
|
|
88
|
+
allow.push(r);
|
|
89
|
+
mine.push(r);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (allow.length) p.allow = allow;
|
|
94
|
+
else delete p.allow;
|
|
95
|
+
if (deny.length) p.deny = deny;
|
|
96
|
+
else delete p.deny;
|
|
97
|
+
if (Object.keys(p).length) o.permissions = p;
|
|
98
|
+
else delete o.permissions;
|
|
99
|
+
return { text: `${JSON.stringify(o, null, 2)}
|
|
100
|
+
`, owned: mine };
|
|
101
|
+
}
|
|
102
|
+
function mergeClaudeApproval(text, names, owned, file = ".claude/settings.local.json") {
|
|
103
|
+
const o = parseJson(text, file);
|
|
104
|
+
const ours = new Set(owned);
|
|
105
|
+
const list = (Array.isArray(o.enabledMcpjsonServers) ? o.enabledMcpjsonServers.map(String) : []).filter((n) => !ours.has(n));
|
|
106
|
+
const mine = [];
|
|
107
|
+
for (const n of names) if (!list.includes(n)) {
|
|
108
|
+
list.push(n);
|
|
109
|
+
mine.push(n);
|
|
110
|
+
}
|
|
111
|
+
if (list.length) o.enabledMcpjsonServers = list;
|
|
112
|
+
else delete o.enabledMcpjsonServers;
|
|
113
|
+
return { text: `${JSON.stringify(o, null, 2)}
|
|
114
|
+
`, owned: mine };
|
|
115
|
+
}
|
|
116
|
+
var tomlKey = (k) => /^[A-Za-z0-9_-]+$/.test(k) ? k : JSON.stringify(k);
|
|
117
|
+
var tomlStr = (s) => JSON.stringify(s);
|
|
118
|
+
var tomlList = (l) => `[${l.map(tomlStr).join(", ")}]`;
|
|
119
|
+
var BLOCK = "# instruction.md apply:";
|
|
120
|
+
function mergeCodexToml(text, servers, owned, helper, envAuth = () => null) {
|
|
121
|
+
const lines = (text ?? "").split(/\r?\n/);
|
|
122
|
+
if (lines.length && lines[lines.length - 1] === "") lines.pop();
|
|
123
|
+
const kept = [];
|
|
124
|
+
for (let i = 0; i < lines.length; i++) {
|
|
125
|
+
const m = lines[i].startsWith(BLOCK) ? lines[i].slice(BLOCK.length).trim() : null;
|
|
126
|
+
if (m !== null && owned.includes(m)) {
|
|
127
|
+
i++;
|
|
128
|
+
while (i < lines.length && !/^\s*\[/.test(lines[i]) && !lines[i].startsWith(BLOCK)) i++;
|
|
129
|
+
if (i < lines.length && /^\s*\[\s*mcp_servers\./.test(lines[i])) {
|
|
130
|
+
i++;
|
|
131
|
+
while (i < lines.length && !/^\s*\[/.test(lines[i]) && !lines[i].startsWith(BLOCK)) i++;
|
|
132
|
+
}
|
|
133
|
+
i--;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
kept.push(lines[i]);
|
|
137
|
+
}
|
|
138
|
+
while (kept.length && kept[kept.length - 1].trim() === "") kept.pop();
|
|
139
|
+
const taken = /* @__PURE__ */ new Set();
|
|
140
|
+
for (const l of kept) {
|
|
141
|
+
const h = /^\s*\[\s*mcp_servers\.("?)([^\]"]+)\1\s*\]/.exec(l);
|
|
142
|
+
if (h) taken.add(h[2]);
|
|
143
|
+
}
|
|
144
|
+
const conflicts = [], mine = [], add = [];
|
|
145
|
+
for (const s of servers) {
|
|
146
|
+
if (taken.has(s.id)) {
|
|
147
|
+
conflicts.push(`.codex/config.toml: ${s.id}`);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const ea = envAuth(s);
|
|
151
|
+
const h = ea ? void 0 : helper(s);
|
|
152
|
+
const allow = s.allow?.length ? s.allow : void 0;
|
|
153
|
+
add.push(
|
|
154
|
+
"",
|
|
155
|
+
`${BLOCK} ${s.id}`,
|
|
156
|
+
`[mcp_servers.${tomlKey(s.id)}]`,
|
|
157
|
+
`url = ${tomlStr(s.url)}`,
|
|
158
|
+
...h ? [`http_headers_helper = ${tomlStr(h)}`] : [],
|
|
159
|
+
...ea?.bearer ? [`bearer_token_env_var = ${tomlStr(ea.bearer)}`] : [],
|
|
160
|
+
...ea?.headers ? [`env_http_headers = { ${Object.entries(ea.headers).map(([k, v]) => `${tomlStr(k)} = ${tomlStr(v)}`).join(", ")} }`] : [],
|
|
161
|
+
...allow ? [`enabled_tools = ${tomlList(allow)}`] : [],
|
|
162
|
+
...s.deny?.length ? [`disabled_tools = ${tomlList(s.deny)}`] : []
|
|
163
|
+
);
|
|
164
|
+
mine.push(s.id);
|
|
165
|
+
}
|
|
166
|
+
const out = [...kept, ...add];
|
|
167
|
+
while (out.length && out[0].trim() === "") out.shift();
|
|
168
|
+
return { text: out.length ? `${out.join("\n")}
|
|
169
|
+
` : "", owned: mine, conflicts };
|
|
170
|
+
}
|
|
171
|
+
function skillFile(s, name, body, from) {
|
|
172
|
+
let text = body.replace(/^/, "");
|
|
173
|
+
let description = s.description;
|
|
174
|
+
const fm = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
|
175
|
+
if (fm) {
|
|
176
|
+
const y = loadYaml(fm[1]);
|
|
177
|
+
const d = y.ok && y.value && typeof y.value === "object" ? y.value.description : void 0;
|
|
178
|
+
if (typeof d === "string" && d.trim() && (description === s.id || description === s.title)) description = d.trim().replace(/\s+/g, " ");
|
|
179
|
+
text = text.slice(fm[0].length);
|
|
180
|
+
}
|
|
181
|
+
const desc = description.length > 1024 ? `${description.slice(0, 1023)}…` : description;
|
|
182
|
+
return `---
|
|
183
|
+
name: ${name}
|
|
184
|
+
description: ${JSON.stringify(desc)}
|
|
185
|
+
---
|
|
186
|
+
${MARK} ${s.id} from ${from} -->
|
|
187
|
+
|
|
188
|
+
${text.trim()}
|
|
189
|
+
`;
|
|
190
|
+
}
|
|
191
|
+
async function fetchSkill(s, fetchText) {
|
|
192
|
+
const url = githubSkillUrl(s.src);
|
|
193
|
+
if (!url) throw new Error(`${s.id}: its src isn't a SKILL.md on GitHub`);
|
|
194
|
+
const text = fetchText ? await fetchText(url) : await (async () => {
|
|
195
|
+
const r = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(15e3), headers: { accept: "text/plain" } });
|
|
196
|
+
if (!r.ok) throw new Error(`${s.id}: ${url} answered HTTP ${r.status}`);
|
|
197
|
+
const len = Number(r.headers.get("content-length") ?? 0);
|
|
198
|
+
if (len > SKILL_CAP) throw new Error(`${s.id}: ${url} is larger than 256 KB`);
|
|
199
|
+
const buf = Buffer.from(await r.arrayBuffer());
|
|
200
|
+
if (buf.length > SKILL_CAP) throw new Error(`${s.id}: ${url} is larger than 256 KB`);
|
|
201
|
+
return buf.toString("utf8");
|
|
202
|
+
})();
|
|
203
|
+
if (Buffer.byteLength(text) > SKILL_CAP) throw new Error(`${s.id}: ${url} is larger than 256 KB`);
|
|
204
|
+
if (s.sha256 && `sha256:${sha256Hex(text)}` !== s.sha256) throw new Error(`${s.id}: ${url} doesn't match the sha256 the instruction gives (it changed since it was named): not written`);
|
|
205
|
+
return text;
|
|
206
|
+
}
|
|
207
|
+
var read = (p) => {
|
|
208
|
+
try {
|
|
209
|
+
return readFileSync(p, "utf8");
|
|
210
|
+
} catch {
|
|
211
|
+
return void 0;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
var orNothing = (text) => {
|
|
215
|
+
const v = JSON.parse(text);
|
|
216
|
+
const k = Object.keys(v);
|
|
217
|
+
return !k.length || k.length === 1 && k[0] === "mcpServers" && !Object.keys(asObj(v.mcpServers)).length ? null : text;
|
|
218
|
+
};
|
|
219
|
+
async function applyMachinery(src, o) {
|
|
220
|
+
const m = src.machinery;
|
|
221
|
+
const cli = o.cli ?? DEFAULT_CLI;
|
|
222
|
+
const accounts = o.accounts ?? loadAccounts();
|
|
223
|
+
const before = readApplied(o.dir);
|
|
224
|
+
const owned = (f) => before?.owned[f] ?? [];
|
|
225
|
+
const writes = /* @__PURE__ */ new Map();
|
|
226
|
+
const result = { wrote: [], removed: [], conflicts: [], skipped: [...m.skipped], notes: [] };
|
|
227
|
+
const nextOwned = {};
|
|
228
|
+
const helper = (s) => helperFor(s, cli, accounts, o.accountsFile);
|
|
229
|
+
const hosts = new Set(o.hosts);
|
|
230
|
+
const serversFor = (h) => hosts.has(h) ? m.servers : [];
|
|
231
|
+
const skillsFor = (h) => hosts.has(h) ? m.skills : [];
|
|
232
|
+
const mcpFile = o.fleet ? FLEET_MCP : ".mcp.json";
|
|
233
|
+
const permFile = o.fleet ? FLEET_CLAUDE_SETTINGS : join(".claude", "settings.json");
|
|
234
|
+
if (hosts.has("claude-code") || owned(mcpFile).length) {
|
|
235
|
+
const r = mergeMcpJson(read(join(o.dir, mcpFile)), serversFor("claude-code"), owned(mcpFile), helper, mcpFile);
|
|
236
|
+
result.conflicts.push(...r.conflicts);
|
|
237
|
+
writes.set(mcpFile, r.owned.length || read(join(o.dir, mcpFile)) !== void 0 ? orNothing(r.text) : null);
|
|
238
|
+
nextOwned[mcpFile] = r.owned;
|
|
239
|
+
}
|
|
240
|
+
if (hosts.has("claude-code") || owned(permFile).length) {
|
|
241
|
+
const r = mergeClaudePermissions(read(join(o.dir, permFile)), serversFor("claude-code").filter((s) => nextOwned[mcpFile]?.includes(s.id)), owned(permFile), permFile);
|
|
242
|
+
if (r.owned.length || owned(permFile).length) writes.set(permFile, orNothing(r.text));
|
|
243
|
+
nextOwned[permFile] = r.owned;
|
|
244
|
+
}
|
|
245
|
+
const approvalFile = join(".claude", "settings.local.json");
|
|
246
|
+
if (!o.fleet && (hosts.has("claude-code") && o.approve || owned(approvalFile).length)) {
|
|
247
|
+
const names = o.approve && hosts.has("claude-code") ? nextOwned[mcpFile] ?? [] : [];
|
|
248
|
+
const r = mergeClaudeApproval(read(join(o.dir, approvalFile)), names, owned(approvalFile), approvalFile);
|
|
249
|
+
writes.set(approvalFile, orNothing(r.text));
|
|
250
|
+
nextOwned[approvalFile] = r.owned;
|
|
251
|
+
}
|
|
252
|
+
const tomlFile = join(".codex", "config.toml");
|
|
253
|
+
if (hosts.has("codex") || owned(tomlFile).length) {
|
|
254
|
+
const r = mergeCodexToml(read(join(o.dir, tomlFile)), serversFor("codex"), owned(tomlFile), helper, (s) => codexEnvAuth(s, accounts));
|
|
255
|
+
result.conflicts.push(...r.conflicts);
|
|
256
|
+
if (r.owned.length || owned(tomlFile).length) writes.set(tomlFile, r.text.trim() ? r.text : null);
|
|
257
|
+
nextOwned[tomlFile] = r.owned;
|
|
258
|
+
}
|
|
259
|
+
const fetched = /* @__PURE__ */ new Map();
|
|
260
|
+
for (const [h, root] of [["claude-code", join(".claude", "skills")], ["codex", join(".agents", "skills")]]) {
|
|
261
|
+
const want = skillsFor(h);
|
|
262
|
+
const mine = [];
|
|
263
|
+
const keep = /* @__PURE__ */ new Set();
|
|
264
|
+
for (const s of want) {
|
|
265
|
+
const name = syncName(s.id);
|
|
266
|
+
const file = join(root, name, "SKILL.md");
|
|
267
|
+
const there = read(join(o.dir, file));
|
|
268
|
+
if (there !== void 0 && !owned(root).includes(name) && !there.includes(MARK)) {
|
|
269
|
+
result.conflicts.push(`${file}`);
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
let body = s.body;
|
|
273
|
+
if (!body) {
|
|
274
|
+
try {
|
|
275
|
+
body = fetched.get(s.id) ?? await fetchSkill(s, o.fetchText);
|
|
276
|
+
fetched.set(s.id, body);
|
|
277
|
+
} catch (e) {
|
|
278
|
+
result.skipped.push({ kind: "skill", id: s.id, why: e.message });
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
writes.set(file, skillFile(s, name, body, s.src ?? `${src.label}${src.version ? ` v${src.version}` : ""}`));
|
|
283
|
+
mine.push(name);
|
|
284
|
+
keep.add(name);
|
|
285
|
+
}
|
|
286
|
+
for (const n of owned(root)) if (!keep.has(n)) writes.set(join(root, n, "SKILL.md"), null);
|
|
287
|
+
if (mine.length || owned(root).length) nextOwned[root] = mine;
|
|
288
|
+
}
|
|
289
|
+
for (const [f, text] of writes) {
|
|
290
|
+
const p = join(o.dir, f), now = read(p);
|
|
291
|
+
if (text === null) {
|
|
292
|
+
if (now !== void 0) result.removed.push(f);
|
|
293
|
+
} else if (now !== text) result.wrote.push(f);
|
|
294
|
+
}
|
|
295
|
+
const applied = {
|
|
296
|
+
format: "instruction-applied/1",
|
|
297
|
+
follow: src.follow,
|
|
298
|
+
label: src.label,
|
|
299
|
+
...src.versionId ? { versionId: src.versionId } : {},
|
|
300
|
+
...src.version ? { version: src.version } : {},
|
|
301
|
+
digest: m.digest,
|
|
302
|
+
hosts: [...hosts],
|
|
303
|
+
servers: m.servers.map((s) => ({ id: s.id, url: s.url, ...s.account ? { account: s.account } : {} })),
|
|
304
|
+
skills: m.skills.map((s) => ({ id: s.id, source: s.src ?? "inline" })),
|
|
305
|
+
owned: Object.fromEntries(Object.entries(nextOwned).filter(([, v]) => v.length)),
|
|
306
|
+
...result.skipped.length ? { skipped: result.skipped } : {},
|
|
307
|
+
at: (o.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
|
|
308
|
+
};
|
|
309
|
+
const changed = result.wrote.length > 0 || result.removed.length > 0 || before?.digest !== applied.digest || JSON.stringify(before?.owned ?? {}) !== JSON.stringify(applied.owned);
|
|
310
|
+
if (!o.dryRun) {
|
|
311
|
+
for (const [f, text] of writes) {
|
|
312
|
+
const p = join(o.dir, f);
|
|
313
|
+
if (text === null) {
|
|
314
|
+
if (existsSync(p)) {
|
|
315
|
+
rmSync(p, { force: true });
|
|
316
|
+
if (f.endsWith("SKILL.md")) rmSync(dirname(p), { recursive: true, force: true });
|
|
317
|
+
}
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if (read(p) === text) continue;
|
|
321
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
322
|
+
atomicWrite(p, text);
|
|
323
|
+
}
|
|
324
|
+
if (changed || !before) atomicWrite(join(o.dir, APPLIED_FILE), `${JSON.stringify({ ...applied, at: changed || !before ? applied.at : before.at }, null, 2)}
|
|
325
|
+
`);
|
|
326
|
+
}
|
|
327
|
+
if (hosts.has("claude-code") && !o.fleet && !o.approve && nextOwned[mcpFile]?.length) result.notes.push("Claude Code asks once before it uses a project's servers (or run `instruction-agents apply --approve` to approve them for yourself).");
|
|
328
|
+
if (hosts.has("codex") && !o.fleet && nextOwned[tomlFile]?.length) result.notes.push("Codex reads a project's .codex/config.toml once you trust the folder (it asks when you start it here).");
|
|
329
|
+
return { ...result, changed, applied };
|
|
330
|
+
}
|
|
331
|
+
function targetsOf(text) {
|
|
332
|
+
const m = machineryOf(text);
|
|
333
|
+
const out = /* @__PURE__ */ new Set();
|
|
334
|
+
for (const s of m.servers) for (const t of remoteTargets("mcp", { src: s.url })) out.add(t);
|
|
335
|
+
for (const s of m.skills) if (s.src) for (const t of remoteTargets("skill", { src: s.src })) out.add(t);
|
|
336
|
+
return [...out];
|
|
337
|
+
}
|
|
338
|
+
function catalogFrom(r) {
|
|
339
|
+
return { targets: (r.approved ?? []).map(normalizeTarget), restricted: !!r.integrationsOnly, ...r.blocked ? { blocked: r.blocked } : {} };
|
|
340
|
+
}
|
|
341
|
+
function sayApplied(r) {
|
|
342
|
+
const s = r.applied.servers.map((x) => x.id), k = r.applied.skills.map((x) => x.id);
|
|
343
|
+
const parts = [s.length ? `servers ${s.join(", ")}` : "", k.length ? `skills ${k.join(", ")}` : ""].filter(Boolean);
|
|
344
|
+
return `${parts.length ? parts.join("; ") : "no servers or skills"}${r.conflicts.length ? ` (left alone, not ours: ${r.conflicts.join(", ")})` : ""}${r.skipped.length ? ` (not set up: ${r.skipped.map((x) => `${x.id ?? x.kind} — ${x.why}`).join("; ")})` : ""}`;
|
|
345
|
+
}
|
|
346
|
+
function codexTrust(configText, folders) {
|
|
347
|
+
const begin = "# instruction.md fleet: trusted folders (begin)", end = "# instruction.md fleet: trusted folders (end)";
|
|
348
|
+
const lines = (configText ?? "").split(/\r?\n/);
|
|
349
|
+
const out = [];
|
|
350
|
+
for (let i = 0; i < lines.length; i++) {
|
|
351
|
+
if (lines[i] === begin) {
|
|
352
|
+
while (i < lines.length && lines[i] !== end) i++;
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
out.push(lines[i]);
|
|
356
|
+
}
|
|
357
|
+
while (out.length && out[out.length - 1].trim() === "") out.pop();
|
|
358
|
+
const theirs = new Set(out.map((l) => /^\s*\[\s*projects\.("(?:[^"\\]|\\.)*"|'[^']*')\s*\]/.exec(l)?.[1]).filter((x) => !!x).map((k) => k.startsWith("'") ? k.slice(1, -1) : JSON.parse(k)));
|
|
359
|
+
const ours = folders.filter((f) => !theirs.has(f));
|
|
360
|
+
if (!ours.length) return out.length ? `${out.join("\n")}
|
|
361
|
+
` : "";
|
|
362
|
+
const block = [begin, ...ours.flatMap((f) => [`[projects.${tomlStr(f)}]`, `trust_level = "trusted"`]), end];
|
|
363
|
+
return `${[...out, ...out.length ? [""] : [], ...block].join("\n")}
|
|
364
|
+
`;
|
|
365
|
+
}
|
|
366
|
+
function fleetCodexConfigPath(env = process.env) {
|
|
367
|
+
return join(env.CODEX_HOME ?? join(env.HOME ?? env.USERPROFILE ?? ".", ".codex"), "config.toml");
|
|
368
|
+
}
|
|
369
|
+
export {
|
|
370
|
+
APPLIED_FILE,
|
|
371
|
+
APPLY_HOSTS,
|
|
372
|
+
DEFAULT_CLI,
|
|
373
|
+
FLEET_CLAUDE_SETTINGS,
|
|
374
|
+
FLEET_MCP,
|
|
375
|
+
applyMachinery,
|
|
376
|
+
catalogFrom,
|
|
377
|
+
claudeToolName,
|
|
378
|
+
codexEnvAuth,
|
|
379
|
+
codexTrust,
|
|
380
|
+
fetchSkill,
|
|
381
|
+
fleetCodexConfigPath,
|
|
382
|
+
helperFor,
|
|
383
|
+
mergeClaudeApproval,
|
|
384
|
+
mergeClaudePermissions,
|
|
385
|
+
mergeCodexToml,
|
|
386
|
+
mergeMcpJson,
|
|
387
|
+
readApplied,
|
|
388
|
+
sayApplied,
|
|
389
|
+
shellWord,
|
|
390
|
+
skillFile,
|
|
391
|
+
targetsOf
|
|
392
|
+
};
|
package/dist/connect.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// src/connect.ts
|
|
2
|
+
import { chmodSync, readFileSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { AGENTS_CLI, connectSnippet, followConfig, HOOKED_HOSTS, hookSetup, MANAGED_HOSTS, managedSnippet, mergeSetupFile } from "instruction.md/connect";
|
|
5
|
+
import { atomicWrite, ensureGitignore } from "instruction.md/cli";
|
|
6
|
+
import { CliError, cliContext, cliOut, projectJson, registryConnection } from "instruction.md/cli/registry";
|
|
7
|
+
var asUri = (s) => s.startsWith("instruction://") ? s : `instruction://${s}`;
|
|
8
|
+
var take = (args, flag) => {
|
|
9
|
+
const i = args.indexOf(flag);
|
|
10
|
+
if (i < 0) return void 0;
|
|
11
|
+
const v = args[i + 1];
|
|
12
|
+
args.splice(i, 2);
|
|
13
|
+
return v;
|
|
14
|
+
};
|
|
15
|
+
var has = (args, flag) => {
|
|
16
|
+
const i = args.indexOf(flag);
|
|
17
|
+
if (i < 0) return false;
|
|
18
|
+
args.splice(i, 1);
|
|
19
|
+
return true;
|
|
20
|
+
};
|
|
21
|
+
function connectWithHooks(ctx, host, target, full, o) {
|
|
22
|
+
const snippet = full.split("\n").filter((l) => !/--with-hooks/.test(l)).join("\n");
|
|
23
|
+
const follow = followConfig(target, { requireSignature: o.requireSignature, url: ctx.url });
|
|
24
|
+
const setup = hookSetup(host, o.cli);
|
|
25
|
+
const followFile = join(o.dir, ".instruction", "follow.json");
|
|
26
|
+
const shown = (f) => f.startsWith(o.dir) ? f.slice(o.dir.length + 1) : f;
|
|
27
|
+
const read = (f) => {
|
|
28
|
+
try {
|
|
29
|
+
return readFileSync(f, "utf8");
|
|
30
|
+
} catch {
|
|
31
|
+
return void 0;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const already = (setup.alsoReads ?? []).find((f) => /instruction(\.md)? hook|instruction\.js hook|instruction-agents hook|@instruction\.md\/agents hook/.test(read(join(o.dir, f)) ?? ""));
|
|
35
|
+
const files = already ? [] : setup.files;
|
|
36
|
+
const said = [
|
|
37
|
+
...already ? [`# ${host} also runs the hooks in ${already}, which already give this project's instruction: nothing more to add`] : [],
|
|
38
|
+
...setup.manual ? [setup.manual] : []
|
|
39
|
+
];
|
|
40
|
+
if (!o.write) {
|
|
41
|
+
const text2 = [
|
|
42
|
+
snippet,
|
|
43
|
+
``,
|
|
44
|
+
`# ${shown(followFile)} — commit it: everyone working here follows the same instruction`,
|
|
45
|
+
JSON.stringify(follow, null, 2),
|
|
46
|
+
``,
|
|
47
|
+
`# ${shown(join(o.dir, ".instruction", ".gitignore"))} — the fetched text and its state stay out of the repository`,
|
|
48
|
+
`current.md`,
|
|
49
|
+
`state.json`,
|
|
50
|
+
`given/`,
|
|
51
|
+
``,
|
|
52
|
+
...files.flatMap((f) => [`# ${f.path} — ${f.merge === "script" ? "an executable" : "merged into what is there"}`, typeof f.value === "string" ? f.value.replace(/\n$/, "") : JSON.stringify(f.value, null, 2), ``]),
|
|
53
|
+
...said.map((l) => `# ${l.replace(/\n/g, "\n# ")}`),
|
|
54
|
+
...setup.note ? [`# ${setup.note}`] : [],
|
|
55
|
+
...files.length ? [`# or let this write them: instruction-agents connect --host ${host} ${target} --with-hooks --write`] : []
|
|
56
|
+
].join("\n");
|
|
57
|
+
cliOut(ctx, text2, { host, uri: target, follow, setup: { files: files.map((f) => ({ path: f.path, merge: f.merge, value: f.value })), manual: setup.manual ?? null, note: setup.note }, files: { follow: followFile, hooks: files.map((f) => join(o.dir, f.path)) }, snippet });
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
const merged = [];
|
|
61
|
+
const left = [];
|
|
62
|
+
for (const f of files) {
|
|
63
|
+
const abs = join(o.dir, f.path);
|
|
64
|
+
let text2;
|
|
65
|
+
try {
|
|
66
|
+
text2 = mergeSetupFile(f, read(abs));
|
|
67
|
+
} catch (e) {
|
|
68
|
+
throw new CliError(`${abs}: ${e.message}`, 2);
|
|
69
|
+
}
|
|
70
|
+
if (text2 === null) left.push(f.path);
|
|
71
|
+
else merged.push({ path: abs, text: text2, ...f.mode ? { mode: f.mode } : {} });
|
|
72
|
+
}
|
|
73
|
+
const before = projectJson(followFile);
|
|
74
|
+
const had = before && typeof before === "object" && !Array.isArray(before) ? before : {};
|
|
75
|
+
const applyHosts = o.apply && (host === "claude-code" || host === "codex") ? [.../* @__PURE__ */ new Set([...Array.isArray(had.apply) ? had.apply : had.apply === true ? ["claude-code"] : [], host])] : void 0;
|
|
76
|
+
const followed = { ...had, ...follow, ...applyHosts ? { apply: applyHosts } : {} };
|
|
77
|
+
atomicWrite(followFile, `${JSON.stringify(followed, null, 2)}
|
|
78
|
+
`);
|
|
79
|
+
ensureGitignore(join(o.dir, ".instruction"));
|
|
80
|
+
for (const m of merged) {
|
|
81
|
+
atomicWrite(m.path, m.text, m.mode);
|
|
82
|
+
if (m.mode) chmodSync(m.path, m.mode);
|
|
83
|
+
}
|
|
84
|
+
const wrote = [shown(followFile), shown(join(o.dir, ".instruction", ".gitignore")), ...merged.map((m) => shown(m.path))];
|
|
85
|
+
const text = [
|
|
86
|
+
`wrote ${wrote.join(", ")} (follows ${target})`,
|
|
87
|
+
...left.length ? [`left alone, not instruction.md's: ${left.join(", ")} — add \`${o.cli} hook ${host}\` to them by hand`] : [],
|
|
88
|
+
...said,
|
|
89
|
+
`commit ${wrote.join(", ")}${setup.note ? `; ${setup.note}` : ""}`,
|
|
90
|
+
``,
|
|
91
|
+
snippet
|
|
92
|
+
].join("\n");
|
|
93
|
+
cliOut(ctx, text, { host, uri: target, files: { follow: followFile, hooks: merged.map((m) => m.path) }, left, manual: setup.manual ?? null, follow: followed });
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
async function cmdConnect(args) {
|
|
97
|
+
const ctx = await cliContext(args);
|
|
98
|
+
let host = take(args, "--host") ?? "";
|
|
99
|
+
const withHooks = has(args, "--with-hooks");
|
|
100
|
+
const write = has(args, "--write");
|
|
101
|
+
const managed = has(args, "--managed");
|
|
102
|
+
const requireSignature = has(args, "--require-signature");
|
|
103
|
+
const noApply = has(args, "--no-apply");
|
|
104
|
+
const cli = take(args, "--cli") ?? AGENTS_CLI;
|
|
105
|
+
const dir = resolve(take(args, "--dir") ?? process.cwd());
|
|
106
|
+
if (managed && !host && MANAGED_HOSTS.includes(args[0] ?? "")) host = args.shift();
|
|
107
|
+
const uri = args.shift();
|
|
108
|
+
if (!withHooks && !write && !managed) throw new CliError("instruction-agents connect sets a project's hooks up (--with-hooks, --write) or prints an organization's managed settings (--managed); for an MCP host's snippet: instruction connect --host HOST", 2);
|
|
109
|
+
if ((withHooks || write) && !HOOKED_HOSTS.includes(host)) throw new CliError(`--with-hooks and --write are for --host ${HOOKED_HOSTS.join(", ")}; another host follows a file instruction.md keeps (instruction connect --host ${host || "HOST"} says how)`, 2);
|
|
110
|
+
if (managed && !MANAGED_HOSTS.includes(host)) throw new CliError(`--managed is for --host ${MANAGED_HOSTS.join(" or ")}`, 2);
|
|
111
|
+
if (!uri) throw new CliError(`name the instruction to follow: instruction-agents connect --host ${host} <uri> ${managed ? "--managed" : "--with-hooks"}`, 2);
|
|
112
|
+
if (managed && (write || withHooks)) throw new CliError("--managed prints an organization's settings, for an administrator to deploy; it writes nothing", 2);
|
|
113
|
+
const target = asUri(uri);
|
|
114
|
+
if (managed) {
|
|
115
|
+
const s2 = managedSnippet(host, { mcpUrl: ctx.url, target, cli });
|
|
116
|
+
cliOut(ctx, s2, { host, url: ctx.url, uri: target, managed: true, snippet: s2 });
|
|
117
|
+
return 0;
|
|
118
|
+
}
|
|
119
|
+
const s = connectSnippet(host, { mcpUrl: ctx.url, target });
|
|
120
|
+
const code = connectWithHooks(ctx, host, target, s, { write, dir, cli, requireSignature, apply: !noApply });
|
|
121
|
+
if (code === 0 && write && !noApply && (host === "claude-code" || host === "codex") && await ctx.token()) {
|
|
122
|
+
const { cmdApply } = await import("./setup.js");
|
|
123
|
+
await cmdApply([target, "--host", host, "--dir", dir, "--cli", cli, "--url", ctx.url, ...ctx.given ? ["--token", ctx.given] : [], ...ctx.json ? ["--quiet"] : []]).catch((e) => console.error(`the instruction's servers and skills weren't written (${e instanceof Error ? e.message : String(e)}); run \`instruction-agents apply\``));
|
|
124
|
+
}
|
|
125
|
+
return code;
|
|
126
|
+
}
|
|
127
|
+
async function cmdSync(args) {
|
|
128
|
+
const m = await import("./sync.js");
|
|
129
|
+
try {
|
|
130
|
+
return await m.cmdSync(args, registryConnection);
|
|
131
|
+
} catch (e) {
|
|
132
|
+
throw e instanceof m.SyncError ? new CliError(e.message, e.code) : e;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export {
|
|
136
|
+
cmdConnect,
|
|
137
|
+
cmdSync
|
|
138
|
+
};
|