@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/dist/setup.js ADDED
@@ -0,0 +1,324 @@
1
+ // src/setup.ts
2
+ import { spawnSync } from "node:child_process";
3
+ import { resolve } from "node:path";
4
+ import { machineryOf } from "instruction.md";
5
+ import { entryFor, headersFor, hostEnv, loadAccounts, SecretError } from "./accounts.js";
6
+ import { APPLY_HOSTS, applyMachinery, catalogFrom, DEFAULT_CLI, readApplied, sayApplied, targetsOf } from "./apply.js";
7
+ import { asksForSignIn } from "./oauth.js";
8
+ import { findFollow } from "instruction.md/cli";
9
+ var orgIds = /* @__PURE__ */ new WeakMap();
10
+ async function machinerySource(c, follow) {
11
+ const { readAuthored, callRegistry } = await import("instruction.md/cli/registry");
12
+ const client = c.client;
13
+ const r = await readAuthored(client, follow);
14
+ const addr = follow.replace(/^instruction:\/\//, "").split("@")[0];
15
+ let owner, name;
16
+ if (addr.includes("/")) [owner, name] = addr.split("/", 2);
17
+ else {
18
+ const id = (r.canonical ?? follow).replace(/^instruction:\/\//, "").split("@")[0];
19
+ try {
20
+ const g = await callRegistry(client, "instructions_get", { instructionId: id });
21
+ owner = g.owner;
22
+ name = g.name;
23
+ } catch {
24
+ }
25
+ }
26
+ const targets = targetsOf(r.text);
27
+ let catalog;
28
+ if (owner && targets.length) {
29
+ let ids = orgIds.get(c);
30
+ if (!ids) {
31
+ ids = /* @__PURE__ */ new Map();
32
+ try {
33
+ const b = await callRegistry(client, "session_bootstrap", {});
34
+ for (const o of b.orgs ?? []) if (o.slug) ids.set(o.slug.toLowerCase(), o.id);
35
+ } catch {
36
+ }
37
+ orgIds.set(c, ids);
38
+ }
39
+ const orgId = ids.get(owner.toLowerCase());
40
+ if (orgId) {
41
+ try {
42
+ catalog = catalogFrom(await callRegistry(client, "orgs_integrations_search", { orgId, targets: targets.slice(0, 100), limit: 1 }));
43
+ } catch {
44
+ }
45
+ }
46
+ }
47
+ const machinery = machineryOf(r.text, catalog ? { catalog } : {});
48
+ return { follow, label: owner && name ? `${owner}/${name}` : addr, ...r.versionId ? { versionId: r.versionId } : {}, ...r.version ? { version: r.version } : {}, machinery, text: r.text };
49
+ }
50
+ function take(args, flag) {
51
+ const i = args.indexOf(flag);
52
+ if (i < 0) return void 0;
53
+ const v = args[i + 1];
54
+ args.splice(i, 2);
55
+ return v;
56
+ }
57
+ function has(args, flag) {
58
+ const i = args.indexOf(flag);
59
+ if (i < 0) return false;
60
+ args.splice(i, 1);
61
+ return true;
62
+ }
63
+ function hostsOf(v, fallback) {
64
+ if (!v) return [...fallback];
65
+ const list = v === "both" || v === "all" ? [...APPLY_HOSTS] : v.split(",").map((x) => x.trim());
66
+ for (const h of list) if (!APPLY_HOSTS.includes(h)) throw new Error(`--host is ${APPLY_HOSTS.join(", ")} or both, not ${h}`);
67
+ return [...new Set(list)];
68
+ }
69
+ var APPLY_USAGE = "usage: instruction-agents apply [<uri>] [--host claude-code|codex|both] [--dir D] [--approve] [--dry-run] [--remove] [--cli CMD] [--if-changed] [--quiet] [--note] [--json]";
70
+ async function cmdApply(argv) {
71
+ const args = [...argv];
72
+ const json = has(args, "--json"), approve = has(args, "--approve"), dryRun = has(args, "--dry-run"), remove = has(args, "--remove"), ifChanged = has(args, "--if-changed"), quiet = has(args, "--quiet"), note = has(args, "--note");
73
+ const hostFlag = take(args, "--host"), cli = take(args, "--cli") ?? DEFAULT_CLI;
74
+ const dirFlag = take(args, "--dir");
75
+ const conn = [take(args, "--url"), take(args, "--token")];
76
+ const uri = args[0] && !args[0].startsWith("--") ? args.shift() : void 0;
77
+ if (args.length) {
78
+ console.error(`${APPLY_USAGE}
79
+ not understood: ${args.join(" ")}`);
80
+ return 2;
81
+ }
82
+ const found = findFollow(dirFlag ?? process.cwd());
83
+ const dir = resolve(dirFlag ?? found?.root ?? process.cwd());
84
+ const before = readApplied(dir);
85
+ let hosts;
86
+ try {
87
+ hosts = hostsOf(hostFlag, found?.config.apply?.length ? found.config.apply : before?.hosts?.length ? before.hosts : ["claude-code"]);
88
+ } catch (e) {
89
+ console.error(e.message);
90
+ return 2;
91
+ }
92
+ const say = (l) => {
93
+ if (!quiet) console.error(l);
94
+ };
95
+ if (remove) {
96
+ const empty = { format: "agent-machinery/1", servers: [], skills: [], skipped: [], digest: "" };
97
+ const r = await applyMachinery({ follow: before?.follow ?? uri ?? "", label: before?.label ?? "", machinery: empty }, { dir, hosts: [], dryRun });
98
+ if (json) console.log(JSON.stringify({ removed: r.removed, dryRun }, null, 2));
99
+ else say(r.removed.length ? `${dryRun ? "would remove" : "removed"} ${r.removed.join(", ")}` : "nothing of the instruction's was written here");
100
+ if (!dryRun) {
101
+ const { rmSync } = await import("node:fs");
102
+ rmSync(resolve(dir, ".instruction", "applied.json"), { force: true });
103
+ }
104
+ return 0;
105
+ }
106
+ const follow = uri ?? found?.config.follow;
107
+ if (!follow) {
108
+ console.error(`name the instruction (instruction-agents apply owner/name), or run it in a project that follows one (.instruction/follow.json)
109
+ ${APPLY_USAGE}`);
110
+ return 2;
111
+ }
112
+ const { registryConnection } = await import("instruction.md/cli/registry");
113
+ const c = await registryConnection([...conn[0] ? ["--url", conn[0]] : found?.config.url ? ["--url", found.config.url] : [], ...conn[1] ? ["--token", conn[1]] : []]);
114
+ if (!c) {
115
+ console.error("instruction-agents apply reads the instruction from instruction.md: sign in first (`instruction-agents login`, or --token)");
116
+ return 3;
117
+ }
118
+ try {
119
+ const src = await machinerySource(c, follow);
120
+ if (ifChanged && before && before.digest === src.machinery.digest && before.hosts.join() === hosts.join()) {
121
+ if (before.versionId !== src.versionId && !dryRun) {
122
+ const { atomicWrite } = await import("instruction.md/cli");
123
+ atomicWrite(resolve(dir, ".instruction", "applied.json"), `${JSON.stringify({ ...before, versionId: src.versionId, version: src.version }, null, 2)}
124
+ `);
125
+ }
126
+ return 0;
127
+ }
128
+ const r = await applyMachinery(src, { dir, hosts, cli, approve, dryRun });
129
+ if (note && r.changed && !dryRun) {
130
+ const { atomicWrite } = await import("instruction.md/cli");
131
+ atomicWrite(resolve(dir, ".instruction", "applied-note"), `${src.label}${src.version ? ` v${src.version}` : ""} — the agent's ${sayApplied(r)}; they load when its next session starts
132
+ `);
133
+ }
134
+ if (json) {
135
+ console.log(JSON.stringify({ dryRun, changed: r.changed, wrote: r.wrote, removed: r.removed, conflicts: r.conflicts, skipped: r.skipped, notes: r.notes, applied: r.applied }, null, 2));
136
+ return 0;
137
+ }
138
+ say(`${src.label}${src.version ? ` v${src.version}` : ""} for ${hosts.join(" and ")}: ${sayApplied(r)}`);
139
+ if (r.wrote.length) say(`${dryRun ? "would write" : "wrote"} ${r.wrote.join(", ")}`);
140
+ if (r.removed.length) say(`${dryRun ? "would remove" : "removed"} ${r.removed.join(", ")}`);
141
+ if (!r.wrote.length && !r.removed.length) say("nothing to change");
142
+ for (const n of r.notes) say(n);
143
+ const unbound = src.machinery.servers.filter((s) => s.account && !entryFor(loadAccounts(), s.id, s.account));
144
+ if (unbound.length) say(`On this machine, say what ${unbound.map((s) => `${s.id}'s account "${s.account}"`).join(", ")} means: instruction-agents accounts set ${unbound[0].id}@${unbound[0].account} --env VAR (or --command, or instruction-agents signin ${unbound[0].id} --account ${unbound[0].account})`);
145
+ return 0;
146
+ } finally {
147
+ await c.client.close().catch(() => {
148
+ });
149
+ }
150
+ }
151
+ var runCmd = (cmd, args, env) => {
152
+ const r = spawnSync(cmd, args, { env, encoding: "utf8", timeout: 2e4, stdio: ["ignore", "pipe", "pipe"] });
153
+ return { status: r.status, stdout: r.stdout ?? "", ...r.error ? { error: r.error.message } : {} };
154
+ };
155
+ var HOST_BIN = { "claude-code": "claude", codex: "codex" };
156
+ var HOST_VARS = { "claude-code": ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"], codex: ["CODEX_API_KEY", "OPENAI_API_KEY", "CODEX_ACCESS_TOKEN"] };
157
+ var HOST_LABEL = { "claude-code": "Claude Code", codex: "Codex" };
158
+ var HOST_SIGNIN = { "claude-code": "claude auth login (or, for a machine with no browser, claude setup-token, then instruction-agents accounts host claude-code --env CLAUDE_CODE_OAUTH_TOKEN --from-command …)", codex: "codex login --device-auth (or printenv OPENAI_API_KEY | codex login --with-api-key)" };
159
+ async function checkSetup(o) {
160
+ const env = o.env ?? process.env, run = o.run ?? runCmd, accounts = o.accounts ?? loadAccounts();
161
+ const out = [];
162
+ for (const h of o.hosts) {
163
+ const label = HOST_LABEL[h], bin = HOST_BIN[h];
164
+ let hostVars = {};
165
+ try {
166
+ hostVars = hostEnv(accounts, h, env);
167
+ } catch (e) {
168
+ out.push({ kind: "host", name: h, level: "block", what: `${label}'s sign-in from this machine's accounts: ${e.message}`, ...e instanceof SecretError && e.fix ? { fix: e.fix } : {} });
169
+ continue;
170
+ }
171
+ const henv = { ...env, ...hostVars };
172
+ const v = run(bin, ["--version"], henv);
173
+ if (v.error || v.status !== 0) {
174
+ out.push({ kind: "host", name: h, level: "block", what: `${label} isn't installed here (\`${bin}\` didn't run)`, fix: h === "codex" ? "npm install -g @openai/codex" : "npm install -g @anthropic-ai/claude-code" });
175
+ continue;
176
+ }
177
+ const version = v.stdout.trim().split(/\s+/).find((w) => /^\d+\.\d+/.test(w)) ?? v.stdout.trim().slice(0, 40);
178
+ const byVar = HOST_VARS[h].find((k) => henv[k]?.trim());
179
+ if (byVar) {
180
+ out.push({ kind: "host", name: h, level: "ok", what: `${label} ${version}, signed in by the variable ${byVar}${hostVars[byVar] ? " (from this machine's accounts)" : ""}` });
181
+ continue;
182
+ }
183
+ if (h === "claude-code") {
184
+ const s = run(bin, ["auth", "status", "--json"], henv);
185
+ let st = {};
186
+ try {
187
+ st = JSON.parse(s.stdout);
188
+ } catch {
189
+ }
190
+ if (st.loggedIn !== true) {
191
+ out.push({ kind: "host", name: h, level: "block", what: `${label} ${version} isn't signed in`, fix: HOST_SIGNIN[h] });
192
+ continue;
193
+ }
194
+ const exp = st.loginExpiresAt ? Date.parse(st.loginExpiresAt) : NaN;
195
+ const soon = Number.isFinite(exp) && exp - Date.now() < 3 * 864e5;
196
+ out.push({ kind: "host", name: h, level: soon ? "warn" : "ok", what: `${label} ${version}, signed in${soon ? ` — until ${new Date(exp).toISOString().slice(0, 16).replace("T", " ")} UTC` : ""}`, ...soon ? { fix: HOST_SIGNIN[h] } : {} });
197
+ } else {
198
+ const s = run(bin, ["login", "status"], henv);
199
+ if (s.status !== 0) {
200
+ out.push({ kind: "host", name: h, level: "block", what: `${label} ${version} isn't signed in`, fix: HOST_SIGNIN[h] });
201
+ continue;
202
+ }
203
+ out.push({ kind: "host", name: h, level: "ok", what: `${label} ${version}, signed in` });
204
+ }
205
+ }
206
+ for (const s of o.servers) {
207
+ const key = s.account ? `${s.id}@${s.account}` : s.id;
208
+ const found = entryFor(accounts, s.id, s.account);
209
+ let headers = {};
210
+ if (found) {
211
+ try {
212
+ headers = await headersFor(found.key, found.entry, { url: s.url, env, ...o.f ? { f: o.f } : {} });
213
+ } catch (e) {
214
+ out.push({ kind: "server", name: s.id, ...s.account ? { account: s.account } : {}, level: "block", what: `${key}: ${e.message}`, ...e instanceof SecretError && e.fix ? { fix: e.fix } : {} });
215
+ continue;
216
+ }
217
+ }
218
+ if (o.probe === false) {
219
+ out.push({ kind: "server", name: s.id, ...s.account ? { account: s.account } : {}, level: found ? "ok" : "warn", what: found ? `${key}: a credential is ready` : `${key}: no account on this machine` });
220
+ continue;
221
+ }
222
+ const p = await asksForSignIn(s.url, o.f, headers);
223
+ const host = (() => {
224
+ try {
225
+ return new URL(s.url).host;
226
+ } catch {
227
+ return s.url;
228
+ }
229
+ })();
230
+ const signinFix = `instruction-agents signin ${s.id}${s.account ? ` --account ${s.account}` : ""} --url ${s.url}`;
231
+ if (p.status === 0) {
232
+ out.push({ kind: "server", name: s.id, ...s.account ? { account: s.account } : {}, level: "warn", what: `${key}: ${host} didn't answer (${p.error ?? "no answer"})` });
233
+ continue;
234
+ }
235
+ if (found) {
236
+ if (p.asks) out.push({ kind: "server", name: s.id, ...s.account ? { account: s.account } : {}, level: "block", what: `${key}: ${host} refused this machine's credential (HTTP ${p.status})`, fix: found.entry.oauth ? signinFix : `check what instruction-agents accounts says for ${found.key}` });
237
+ else out.push({ kind: "server", name: s.id, ...s.account ? { account: s.account } : {}, level: "ok", what: `${key}: ${host} takes this machine's credential` });
238
+ continue;
239
+ }
240
+ if (!p.asks) {
241
+ out.push({ kind: "server", name: s.id, ...s.account ? { account: s.account } : {}, level: "ok", what: `${key}: ${host} needs no sign-in` });
242
+ continue;
243
+ }
244
+ out.push({
245
+ kind: "server",
246
+ name: s.id,
247
+ ...s.account ? { account: s.account } : {},
248
+ level: o.unattended ? "block" : "warn",
249
+ what: o.unattended ? `${key}: ${host} needs a sign-in, and nobody is here to give it` : `${key}: ${host} needs a sign-in — the agent's app will ask you${s.account ? ` (the instruction asks for the account "${s.account}")` : ""}`,
250
+ fix: s.account ? `${signinFix} (or: instruction-agents accounts set ${key} --env VAR | --command CMD)` : signinFix
251
+ });
252
+ }
253
+ return out;
254
+ }
255
+ var needsOf = (f) => f.filter((x) => x.level === "block").map((x) => ({ kind: x.kind, name: x.name, ...x.account ? { account: x.account } : {}, what: x.what.slice(0, 300), ...x.fix ? { fix: x.fix.slice(0, 300) } : {} }));
256
+ var MARK = { ok: "✓", warn: "!", block: "✗" };
257
+ var DOCTOR_USAGE = "usage: instruction-agents doctor [--host claude-code|codex|both] [--dir D] [--fleet] [--no-probe] [--json]";
258
+ async function cmdDoctor(argv) {
259
+ const args = [...argv];
260
+ const json = has(args, "--json"), unattended = has(args, "--fleet"), noProbe = has(args, "--no-probe");
261
+ const hostFlag = take(args, "--host"), dirFlag = take(args, "--dir");
262
+ const conn = [take(args, "--url"), take(args, "--token")];
263
+ if (args.length) {
264
+ console.error(DOCTOR_USAGE);
265
+ return 2;
266
+ }
267
+ const found = findFollow(dirFlag ?? process.cwd());
268
+ const dir = resolve(dirFlag ?? found?.root ?? process.cwd());
269
+ const applied = readApplied(dir);
270
+ let hosts;
271
+ try {
272
+ hosts = hostsOf(hostFlag, applied?.hosts?.length ? applied.hosts : found?.config.apply?.length ? found.config.apply : ["claude-code"]);
273
+ } catch (e) {
274
+ console.error(e.message);
275
+ return 2;
276
+ }
277
+ const findings = [];
278
+ let servers = applied?.servers ?? [];
279
+ const { registryConnection } = await import("instruction.md/cli/registry");
280
+ const c = await registryConnection([...conn[0] ? ["--url", conn[0]] : found?.config.url ? ["--url", found.config.url] : [], ...conn[1] ? ["--token", conn[1]] : []]).catch(() => null);
281
+ if (!c) findings.push({ kind: "instruction-md", name: "instruction.md", level: found ? "block" : "warn", what: "not signed in to instruction.md", fix: "instruction-agents login (instruction-agents login --device on a machine with no browser), or INSTRUCTION_MD_TOKEN" });
282
+ else {
283
+ try {
284
+ if (found) {
285
+ const src = await machinerySource(c, found.config.follow);
286
+ findings.push({ kind: "instruction-md", name: "instruction.md", level: "ok", what: `signed in; this project follows ${src.label}${src.version ? ` (v${src.version})` : ""}` });
287
+ if (!applied) servers = src.machinery.servers.map((s) => ({ id: s.id, url: s.url, ...s.account ? { account: s.account } : {} }));
288
+ if (applied && applied.digest !== src.machinery.digest) findings.push({ kind: "instruction-md", name: "instruction.md", level: "warn", what: `the servers and skills written here are an earlier version's`, fix: "instruction-agents apply" });
289
+ if (!applied && (src.machinery.servers.length || src.machinery.skills.length)) findings.push({ kind: "instruction-md", name: "instruction.md", level: "warn", what: `the instruction's ${src.machinery.servers.length} server(s) and ${src.machinery.skills.length} skill(s) aren't written here yet`, fix: `instruction-agents apply --host ${hosts.join(",")}` });
290
+ } else findings.push({ kind: "instruction-md", name: "instruction.md", level: "ok", what: "signed in (no project here follows an instruction)" });
291
+ } catch (e) {
292
+ findings.push({ kind: "instruction-md", name: "instruction.md", level: "block", what: `the followed instruction can't be read: ${e.message}` });
293
+ } finally {
294
+ await c.client.close().catch(() => {
295
+ });
296
+ }
297
+ }
298
+ findings.push(...await checkSetup({ hosts, servers, unattended, probe: !noProbe }));
299
+ const blocked = findings.some((f) => f.level === "block");
300
+ if (json) {
301
+ console.log(JSON.stringify({ ok: !blocked, findings }, null, 2));
302
+ return blocked ? 1 : 0;
303
+ }
304
+ for (const f of findings) console.log(`${MARK[f.level]} ${f.what}${f.fix ? `
305
+ fix: ${f.fix}` : ""}`);
306
+ console.log(blocked ? "\nSomething above stops the agent: fix it, then run `instruction-agents doctor` again." : "\nNothing stops the agent.");
307
+ return blocked ? 1 : 0;
308
+ }
309
+ function signInFailure(lines) {
310
+ const PATTERNS = [/Invalid API key/i, /Please run \/login/i, /run `?claude (?:auth )?login`?/i, /OAuth token (?:has )?expired/i, /401 Unauthorized/i, /auth(?:entication)? error: 401/i, /Incorrect API key provided/i, /Not logged in/i, /codex login/i, /invalid_api_key/i];
311
+ for (const l of [...lines].reverse()) if (PATTERNS.some((p) => p.test(l))) return l.slice(0, 300);
312
+ return null;
313
+ }
314
+ export {
315
+ APPLY_USAGE,
316
+ DOCTOR_USAGE,
317
+ checkSetup,
318
+ cmdApply,
319
+ cmdDoctor,
320
+ hostsOf,
321
+ machinerySource,
322
+ needsOf,
323
+ signInFailure
324
+ };
package/dist/sync.js ADDED
@@ -0,0 +1,114 @@
1
+ // src/sync.ts
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join, relative, resolve } from "node:path";
4
+ import { asInstructionUri as asUri, atomicWrite, findFollow, followerReader, keysOf, namePartsOf, readCurrent, readOnce } from "instruction.md/cli";
5
+ var SYNC_TARGETS = ["claude-agent", "claude-skill", "codex-skill"];
6
+ var SYNC_MARK = "<!-- instruction.md:";
7
+ function syncName(s) {
8
+ const n = s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-").slice(0, 64).replace(/-+$/, "");
9
+ return n || "instruction";
10
+ }
11
+ function syncDescription(c) {
12
+ const d = (c.description ?? c.title ?? `The instructions ${c.label} from instruction.md.`).replace(/\s+/g, " ").trim();
13
+ return d.length > 1024 ? `${d.slice(0, 1023).trimEnd()}…` : d;
14
+ }
15
+ function syncPath(target, name) {
16
+ return target === "claude-agent" ? join(".claude", "agents", `${name}.md`) : join(target === "claude-skill" ? ".claude" : ".agents", "skills", name, "SKILL.md");
17
+ }
18
+ function syncFile(target, c, name) {
19
+ const front = `---
20
+ name: ${name}
21
+ description: ${JSON.stringify(syncDescription(c))}
22
+ ---
23
+ `;
24
+ const mark = `${SYNC_MARK} ${c.uri} v${c.version} ${c.digest} — written by \`instruction-agents sync --as ${target}\`; changed here, it is replaced on the next sync -->
25
+ `;
26
+ return `${front}${mark}
27
+ ${c.text.replace(/\s+$/, "")}
28
+ `;
29
+ }
30
+ function syncedFrom(text) {
31
+ const m = new RegExp(`^${SYNC_MARK.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} (\\S+) v\\d+`, "m").exec(text);
32
+ return m ? m[1] : null;
33
+ }
34
+ function writeSync(dir, target, c, name, force = false) {
35
+ const path = join(dir, syncPath(target, name));
36
+ const text = syncFile(target, c, name);
37
+ if (existsSync(path)) {
38
+ const had = readFileSync(path, "utf8");
39
+ if (had === text) return { path, written: false };
40
+ const from = syncedFrom(had);
41
+ if (!force && from === null) return { path, written: false, refused: `${path} is not one sync wrote; --force replaces it` };
42
+ if (!force && asUri(from) !== asUri(c.uri)) return { path, written: false, refused: `${path} came from ${from}; --force replaces it with ${c.uri}` };
43
+ }
44
+ atomicWrite(path, text);
45
+ return { path, written: true };
46
+ }
47
+ var SyncError = class extends Error {
48
+ constructor(message, code = 1) {
49
+ super(message);
50
+ this.code = code;
51
+ }
52
+ };
53
+ var USAGE = "usage: instruction-agents sync [<uri>] --as claude-agent|claude-skill|codex-skill [--name N] [--dir D] [--force]";
54
+ var take = (args, flag) => {
55
+ const i = args.indexOf(flag);
56
+ if (i < 0) return void 0;
57
+ const v = args[i + 1];
58
+ args.splice(i, 2);
59
+ return v;
60
+ };
61
+ var has = (args, flag) => {
62
+ const i = args.indexOf(flag);
63
+ if (i < 0) return false;
64
+ args.splice(i, 1);
65
+ return true;
66
+ };
67
+ async function cmdSync(args, connect) {
68
+ const as = take(args, "--as");
69
+ const nameArg = take(args, "--name");
70
+ const dirArg = take(args, "--dir");
71
+ const force = has(args, "--force");
72
+ if (!as || !SYNC_TARGETS.includes(as)) throw new SyncError(USAGE, 2);
73
+ const project = findFollow(dirArg ? resolve(dirArg) : process.cwd());
74
+ const json = args.includes("--json");
75
+ let remote = null, unreachable = null;
76
+ try {
77
+ remote = await connect(args);
78
+ } catch (e) {
79
+ unreachable = e;
80
+ }
81
+ const uriArg = args.find((a) => !a.startsWith("--"));
82
+ const uri = uriArg ? asUri(uriArg) : project ? project.config.follow : null;
83
+ if (!uri) throw new SyncError(`${USAGE}
84
+ (no uri, and no .instruction/follow.json here names one)`, 2);
85
+ const same = !!project && project.config.follow === uri;
86
+ let c = null;
87
+ if (remote) {
88
+ const keys = same ? keysOf(project) : void 0;
89
+ const policy = { requireSignature: same ? !!project.config.requireSignature : false, ...keys?.length ? { authorKeys: keys } : {} };
90
+ c = await readOnce(uri, { reader: followerReader(remote.client, policy), deadlineMs: 15e3 });
91
+ } else if (same) c = readCurrent(project.dir);
92
+ if (!c && unreachable) throw unreachable;
93
+ if (!c) throw new SyncError(`${uri}: not signed in, and nothing of it is cached here — run \`instruction-agents login\` (or pass --token)`, 3);
94
+ const dir = dirArg ? resolve(dirArg) : project?.root ?? process.cwd();
95
+ const name = syncName(nameArg ?? namePartsOf(c).name ?? uri.replace(/^instruction:\/\//, "").split("@")[0].split("/").pop() ?? "instruction");
96
+ const r = writeSync(dir, as, c, name, force);
97
+ if (r.refused) throw new SyncError(r.refused, 2);
98
+ const shown = relative(process.cwd(), r.path) || r.path;
99
+ if (json) console.log(JSON.stringify({ path: r.path, written: r.written, target: as, name, uri: c.uri, versionId: c.versionId, version: c.version, digest: c.digest }, null, 2));
100
+ else console.error(r.written ? `${shown} ← ${c.label} v${c.version}` : `${shown}: already ${c.label} v${c.version}`);
101
+ return 0;
102
+ }
103
+ export {
104
+ SYNC_MARK,
105
+ SYNC_TARGETS,
106
+ SyncError,
107
+ cmdSync,
108
+ syncDescription,
109
+ syncFile,
110
+ syncName,
111
+ syncPath,
112
+ syncedFrom,
113
+ writeSync
114
+ };
package/dist/turns.js ADDED
@@ -0,0 +1,143 @@
1
+ // src/turns.ts
2
+ import { hostname } from "node:os";
3
+
4
+ // package.json
5
+ var version = "0.2.0";
6
+
7
+ // src/turns.ts
8
+ import { runHook } from "./hook.js";
9
+ import { DEFAULT_URL, findFollow, FollowConfigError, followAt, followerReader, httpReader, keysOf } from "instruction.md/cli";
10
+ function registryAccess(app, o = {}) {
11
+ let connection = null;
12
+ const addressOf = (found) => o.url ?? found.config.url ?? process.env.INSTRUCTION_MD_URL ?? DEFAULT_URL;
13
+ const connect = (found) => {
14
+ connection ??= (async () => {
15
+ process.env.INSTRUCTION_MD_CLIENT_NAME ??= `instruction-md-cli ${app}`;
16
+ if (o.connect) return o.connect(addressOf(found));
17
+ const { registryConnection } = await import("instruction.md/cli/registry");
18
+ return registryConnection(["--url", addressOf(found)]).catch(() => null);
19
+ })();
20
+ return connection;
21
+ };
22
+ return {
23
+ async reader(found) {
24
+ const authorKeys = keysOf(found);
25
+ const policy = { ...found.config.requireSignature ? { requireSignature: true } : {}, ...authorKeys?.length ? { authorKeys } : {} };
26
+ const c = await connect(found);
27
+ return c ? followerReader(c.client, policy) : httpReader(addressOf(found), policy);
28
+ },
29
+ async report(cur, _sid, found) {
30
+ const c = await connect(found);
31
+ if (!c) return false;
32
+ const id = /^instruction:\/\/(ins_[0-9A-Z]{26})/i.exec(cur.canonical ?? "")?.[1];
33
+ if (!id) return false;
34
+ const call = async (name, a) => await c.client.callTool({ name, arguments: a });
35
+ const refused = (r2) => !!r2.isError && /host/i.test(r2.content?.[0]?.text ?? "");
36
+ const withHost = async (name, a) => {
37
+ let r2 = await call(name, { ...a, host: app });
38
+ if (refused(r2) && app !== "other") r2 = await call(name, { ...a, host: "other" });
39
+ return refused(r2) ? call(name, a) : r2;
40
+ };
41
+ const selector = /@([^/?#]+)$/.exec(cur.uri)?.[1];
42
+ const target = selector && !/^(v\d+|ver_[0-9A-Z]+)$/i.test(selector) ? selector : void 0;
43
+ const consumer = { name: `instruction.md ${app} on ${hostname()}`, kind: app, version };
44
+ const made = await withHost("instructions_bindings_create", { instructionId: id, mode: "follow", consumer, ...target ? { target } : {} });
45
+ const bindingId = made.structuredContent?.binding?.id;
46
+ if (made.isError || !bindingId) return false;
47
+ const r = await withHost("instructions_bindings_report", { bindingId, versionId: cur.versionId, deliveredDigest: cur.digest, client: { name: `instruction.md ${app}`, version } });
48
+ return !r.isError;
49
+ },
50
+ async close() {
51
+ const c = connection ? await connection.catch(() => null) : null;
52
+ connection = null;
53
+ await c?.client.close().catch(() => {
54
+ });
55
+ }
56
+ };
57
+ }
58
+ function followFor(cwd, o = {}) {
59
+ const env = o.env ?? process.env;
60
+ const uri = o.follow ?? null;
61
+ if (uri) return followAt(uri, o.requireSignature ? { requireSignature: true } : {});
62
+ const found = findFollow(cwd);
63
+ if (found) return found;
64
+ const fromEnv = env.INSTRUCTION_MD_FOLLOW?.trim();
65
+ return fromEnv ? followAt(fromEnv, env.INSTRUCTION_MD_REQUIRE_SIGNATURE === "1" || o.requireSignature ? { requireSignature: true } : {}) : null;
66
+ }
67
+ async function followTurn(app, o) {
68
+ const access = o.access ?? registryAccess(app);
69
+ const own = !o.access;
70
+ try {
71
+ let found = null;
72
+ try {
73
+ found = followFor(o.cwd, { ...o.follow ? { follow: o.follow } : {}, ...o.requireSignature ? { requireSignature: true } : {} });
74
+ } catch (e) {
75
+ return o.start ? { notice: `instruction.md: ${e instanceof FollowConfigError ? e.message : String(e)}` } : {};
76
+ }
77
+ if (!found) return {};
78
+ const event = { session_id: o.sessionId, hook_event_name: o.start ? "SessionStart" : "UserPromptSubmit", cwd: o.cwd, ...o.start ? { source: o.source ?? "startup" } : {} };
79
+ const byUri = found.root === null;
80
+ const out = await runHook("claude-code", event, {
81
+ ...byUri ? { follow: found.config.follow } : { dir: found.root },
82
+ ...o.requireSignature || byUri && found.config.requireSignature ? { requireSignature: true } : {},
83
+ ...o.deadlineMs !== void 0 ? { deadlineMs: o.deadlineMs } : {},
84
+ ...o.maxChars !== void 0 ? { maxChars: o.maxChars } : {},
85
+ ...o.now ? { now: o.now } : {},
86
+ reader: (f) => access.reader(f),
87
+ report: (cur, sid, f) => access.report(cur, sid, f)
88
+ });
89
+ const turn = {};
90
+ if (out?.hookSpecificOutput?.additionalContext) turn.context = out.hookSpecificOutput.additionalContext;
91
+ if (out?.systemMessage) turn.notice = out.systemMessage;
92
+ return turn;
93
+ } finally {
94
+ if (own) await access.close();
95
+ }
96
+ }
97
+ var TURN_USAGE = "usage: instruction-agents turn <app> --session ID [--start [--source S]] [--cwd D] [--follow URI [--require-signature]] [--url U]";
98
+ function take(args, flag) {
99
+ const i = args.indexOf(flag);
100
+ if (i < 0) return void 0;
101
+ const v = args[i + 1];
102
+ args.splice(i, 2);
103
+ return v;
104
+ }
105
+ function has(args, flag) {
106
+ const i = args.indexOf(flag);
107
+ if (i < 0) return false;
108
+ args.splice(i, 1);
109
+ return true;
110
+ }
111
+ async function cmdTurn(args) {
112
+ const start = has(args, "--start");
113
+ const requireSignature = has(args, "--require-signature");
114
+ const source = take(args, "--source");
115
+ const sessionId = take(args, "--session");
116
+ const cwd = take(args, "--cwd") ?? process.cwd();
117
+ const follow = take(args, "--follow");
118
+ const url = take(args, "--url");
119
+ const deadline = take(args, "--deadline");
120
+ const app = args.shift();
121
+ if (!app || !/^[a-z0-9][a-z0-9-]{0,31}$/.test(app) || !sessionId) {
122
+ console.error(TURN_USAGE);
123
+ return 1;
124
+ }
125
+ const access = registryAccess(app, url ? { url } : {});
126
+ try {
127
+ const t = await followTurn(app, { cwd, sessionId, start, ...source ? { source } : {}, ...follow ? { follow } : {}, requireSignature, access, ...deadline ? { deadlineMs: Number(deadline) } : {} });
128
+ if (t.context || t.notice) process.stdout.write(`${JSON.stringify(t)}
129
+ `);
130
+ } catch (e) {
131
+ console.error(`instruction-agents turn: ${e instanceof Error ? e.message : String(e)}`);
132
+ } finally {
133
+ await access.close();
134
+ }
135
+ return 0;
136
+ }
137
+ export {
138
+ TURN_USAGE,
139
+ cmdTurn,
140
+ followFor,
141
+ followTurn,
142
+ registryAccess
143
+ };
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@instruction.md/agents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Run agents with instruction.md: the `instruction-agents` CLI. Hooks that give Claude Code, Codex and other agents the instruction a project follows, and each new version as it is released; the ACP proxy, pi's extension and the SDK helper; `fleet`, an agent for every deployment, whose questions and permission requests reach you on instruction.md/agents; and an agent's MCP servers, skills and sign-ins (apply, doctor, accounts, signin, credential). Built on the instruction.md package.",
5
+ "keywords": [
6
+ "instruction.md",
7
+ "agents",
8
+ "claude-code",
9
+ "codex",
10
+ "hooks",
11
+ "fleet",
12
+ "mcp",
13
+ "acp",
14
+ "pi-package"
15
+ ],
16
+ "homepage": "https://instruction.md/agents/",
17
+ "bugs": "https://github.com/instruction-md/specification/issues",
18
+ "license": "MIT",
19
+ "type": "module",
20
+ "bin": {
21
+ "instruction-agents": "./dist/main.js"
22
+ },
23
+ "exports": {
24
+ "./agent": {
25
+ "types": "./dist/agent.d.ts",
26
+ "default": "./dist/agent.js"
27
+ },
28
+ "./pi": {
29
+ "types": "./dist/pi.d.ts",
30
+ "default": "./dist/pi.js"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "provided": {
35
+ "@instruction-md/spec": "instruction.md",
36
+ "@instruction-md/mcp-client": "instruction.md/client"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "README.md",
44
+ "LICENSE",
45
+ "NOTICE"
46
+ ],
47
+ "engines": {
48
+ "node": ">=18"
49
+ },
50
+ "sideEffects": false,
51
+ "pi": {
52
+ "extensions": [
53
+ "./dist/pi.js"
54
+ ]
55
+ },
56
+ "dependencies": {
57
+ "jose": "^5.9.6",
58
+ "instruction.md": "^0.10.0"
59
+ },
60
+ "devDependencies": {
61
+ "@modelcontextprotocol/sdk": "^1.32.0",
62
+ "@types/node": "^22.10.0",
63
+ "tsx": "^4.19.2",
64
+ "typescript": "^5.7.2",
65
+ "@instruction-md/mcp-client": "^0.1.0",
66
+ "@instruction-md/spec": "^0.1.0"
67
+ },
68
+ "scripts": {
69
+ "build": "node ../../scripts/build-library.mjs",
70
+ "typecheck": "tsc --noEmit",
71
+ "test": "node --import tsx --test 'test/**/*.test.ts'"
72
+ }
6
73
  }