@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/main.js ADDED
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ // package.json
3
+ var name = "@instruction.md/agents";
4
+ var version = "0.2.0";
5
+
6
+ // src/main.ts
7
+ import { cmdHook } from "./hook.js";
8
+ var USAGE = `instruction-agents — run agents with instruction.md (${name} ${version})
9
+
10
+ instruction-agents sync [<uri>] --as claude-agent|claude-skill|codex-skill [--name N] [--dir D] [--force]
11
+ write an instruction as a Claude Code subagent
12
+ (.claude/agents/), a Claude Code skill (.claude/skills/) or a
13
+ Codex skill (.agents/skills/); again to take a new version
14
+ instruction-agents connect --host HOST <uri> --with-hooks [--write] [--require-signature] [--dir D] [--cli CMD] [--no-apply]
15
+ a project follows <uri>: .instruction/follow.json and the
16
+ agent's hooks (instruction-agents hook), printed, or --write: written
17
+ into the project, merged into what is there. HOST: claude-code,
18
+ codex, qwen-code, droid, devin, gemini-cli, antigravity,
19
+ copilot, cursor, cline, crush (kiro, junie: said how, by hand)
20
+ instruction-agents connect --host claude-code|codex <uri> --managed organization-wide settings for an administrator (Claude Code
21
+ managed-settings.json, Codex requirements.toml); also
22
+ instruction-agents connect --managed claude-code|codex <uri>
23
+ instruction-agents hook HOST|auto [--event NAME] [--fail-closed] [--follow URI [--require-signature]] [--dir D]
24
+ run by the agent's hooks: the event on stdin; the project's
25
+ instruction-agents at a session's start, a new version at the next
26
+ prompt, nothing when nothing changed; exit 0 even offline.
27
+ HOST: claude-code, codex, qwen-code, droid, devin, gemini-cli,
28
+ antigravity, copilot, cursor, kiro, cline, junie, crush, goose;
29
+ --event: the event, for a host that doesn't name it on stdin;
30
+ auto: the host told from the event and its environment
31
+ instruction-agents acp [--follow URI [--require-signature]] [--url U] [--no-bridge] -- <agent command…>
32
+ an ACP proxy (Zed, JetBrains): runs the agent; a session's
33
+ system prompt carries the instruction where the agent takes
34
+ one (else its first prompt), a new version at the next prompt,
35
+ and the instruction mcp bridge among its MCP servers
36
+ instruction-agents turn <app> --session ID [--start [--source S]] [--cwd D] [--follow URI]
37
+ one turn for a plugin that runs a command (Amp's): JSON
38
+ {context, notice} on stdout, or nothing; exit 0 even offline
39
+ instruction-agents fleet (--rule dpr_… | --platform LABEL [--org SLUG]) [--dir D] [--max N] [--interval S] [--once] [--dry-run]
40
+ [--restart-on-exit] [--clean] [--host APP] -- <command…>
41
+ an agent per instruction (RFC-0042 §10): runs the command once
42
+ per active deployment of a rule or a platform, each in a folder
43
+ of its own with its .instruction/follow.json; starts new ones,
44
+ stops retired ones, restarts a "restart" one on a new version,
45
+ leaves a "live" one to its hooks; at most --max or the rule's
46
+ maxAgents; reports each. {instruction} {name} {dir} in the
47
+ command are replaced. --once: one pass, waiting for each
48
+ command to end (a cron job); --dry-run: what it would do
49
+ instruction-agents apply [<uri>] [--host claude-code|codex|both] [--approve] [--dry-run] [--remove] [--dir D] [--cli CMD]
50
+ write the instruction's MCP servers and skills into the agent's
51
+ own files (.mcp.json, .claude/skills/, .codex/config.toml,
52
+ .agents/skills/), its allowed and denied tools as the agent's
53
+ rules; only its own entries are changed or removed
54
+ (.instruction/applied.json); --approve: Claude Code uses the
55
+ servers without asking you
56
+ instruction-agents doctor [--host claude-code|codex|both] [--fleet] [--no-probe] [--json]
57
+ what stops the agent, each with its fix: instruction.md's
58
+ sign-in, the agent's own (Claude Code, Codex), each server's
59
+ account on this machine; exit 1 when something does
60
+ instruction-agents accounts [list | set <server[@account]> --env VAR | --command CMD | --oauth | --xaa-idp URL … | host <app> --env VAR
61
+ (--from-env V | --from-command C) | remove <server[@account]>]
62
+ what an instruction's \\\`account\\\` means on this machine
63
+ (~/.config/instruction-md/accounts.json): a variable, a command
64
+ (your organization's secret store), a sign-in, or your identity
65
+ provider (XAA); never a value printed
66
+ instruction-agents signin <server> --url U [--account A] [--device] [--no-browser]
67
+ sign this machine in to an MCP server (OAuth): a browser here,
68
+ a code on any device (--device), or the address pasted back
69
+ instruction-agents credential <server> [--account A] [--url U] the headers for a server, as JSON: what the agent's app runs
70
+ (Claude Code's headersHelper, Codex's http_headers_helper)
71
+ instruction-agents connect --host HOST <uri> --with-hooks|--write|--managed … as above
72
+ instruction-agents login [--device] [--no-browser] [--url U] sign in to instruction.md (the same sign-in as \`instruction login\`)
73
+ instruction-agents whoami who the server says you are
74
+ instruction-agents mcp … instruction.md's stdio MCP server (instruction mcp)
75
+ instruction-agents --version
76
+
77
+ Writing, checking and releasing instructions: the \`instruction\` command (npm i -g instruction.md).`;
78
+ var commands = {
79
+ hook: cmdHook,
80
+ acp: async (a) => (await import("./acp.js")).cmdAcp(a),
81
+ turn: async (a) => (await import("./turns.js")).cmdTurn(a),
82
+ sync: async (a) => (await import("./connect.js")).cmdSync(a),
83
+ connect: async (a) => (await import("./connect.js")).cmdConnect(a),
84
+ fleet: async (a) => (await import("./fleet.js")).cmdFleet(a),
85
+ apply: async (a) => (await import("./setup.js")).cmdApply(a),
86
+ doctor: async (a) => (await import("./setup.js")).cmdDoctor(a),
87
+ accounts: async (a) => (await import("./accounts.js")).cmdAccounts(a),
88
+ credential: async (a) => (await import("./accounts.js")).cmdCredential(a),
89
+ signin: async (a) => (await import("./accounts.js")).cmdSignin(a),
90
+ mcp: async (a) => (await import("instruction.md/cli/registry")).cmdMcp(a),
91
+ // (instruction.md's sign-in, which these commands use: the same tokens as \`instruction login\`)
92
+ login: async (a) => (await import("instruction.md/cli/registry")).cmdLogin(a),
93
+ whoami: async (a) => (await import("instruction.md/cli/registry")).cmdWhoami(a)
94
+ };
95
+ var [cmd, ...rest] = process.argv.slice(2);
96
+ if (!cmd || [cmd, ...rest].some((a) => a === "--help" || a === "-h")) {
97
+ console.log(USAGE);
98
+ process.exit(0);
99
+ }
100
+ if (cmd === "--version" || cmd === "-v") {
101
+ console.log(`${name} ${version}`);
102
+ process.exit(0);
103
+ }
104
+ var fn = commands[cmd];
105
+ if (!fn) {
106
+ console.error(`unknown command ${cmd}
107
+
108
+ ${USAGE}`);
109
+ process.exit(2);
110
+ }
111
+ Promise.resolve(fn(rest)).then((code) => process.exit(code)).catch(async (e) => {
112
+ const { CliError } = await import("instruction.md/cli/registry");
113
+ if (e instanceof CliError) {
114
+ console.error(e.message);
115
+ process.exit(e.code);
116
+ }
117
+ console.error(e instanceof Error ? e.message : String(e));
118
+ process.exit(1);
119
+ });
package/dist/oauth.js ADDED
@@ -0,0 +1,374 @@
1
+ // src/oauth.ts
2
+ import { randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { readFileSync } from "node:fs";
4
+ import { createServer } from "node:http";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { createInterface } from "node:readline";
8
+ import { browserProblem, clean, openBrowser, page, pkce, safeUrl } from "instruction.md/cli";
9
+ import { atomicWrite } from "instruction.md/cli";
10
+ var CIMD_URL = "https://instruction.md/agents/cli-client.json";
11
+ var CLIENT_NAME = "instruction.md CLI";
12
+ var OAuthError = class extends Error {
13
+ constructor(message, code = 1) {
14
+ super(message);
15
+ this.code = code;
16
+ }
17
+ };
18
+ var configDir = (env = process.env) => join(env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "instruction-md");
19
+ var tokensPath = (env = process.env) => env.INSTRUCTION_MD_MCP_TOKENS ?? join(configDir(env), "mcp-tokens.json");
20
+ function loadTokens(path = tokensPath()) {
21
+ try {
22
+ const s = JSON.parse(readFileSync(path, "utf8"));
23
+ return { tokens: s.tokens ?? {} };
24
+ } catch {
25
+ return { tokens: {} };
26
+ }
27
+ }
28
+ function saveTokens(s, path = tokensPath()) {
29
+ atomicWrite(path, `${JSON.stringify(s, null, 2)}
30
+ `, 384);
31
+ }
32
+ var bare = (s) => s.replace(/\/+$/, "");
33
+ var form = (body, headers = {}) => ({ method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", ...headers }, body: new URLSearchParams(body).toString(), redirect: "error" });
34
+ async function json(r) {
35
+ try {
36
+ const v = await r.json();
37
+ return v && typeof v === "object" ? v : {};
38
+ } catch {
39
+ return {};
40
+ }
41
+ }
42
+ var basic = (id, secret) => `Basic ${Buffer.from(`${encodeURIComponent(id)}:${encodeURIComponent(secret)}`).toString("base64")}`;
43
+ function why(t, status) {
44
+ const e = typeof t.error === "string" ? clean(t.error).slice(0, 100) : `HTTP ${status}`;
45
+ const d = typeof t.error_description === "string" ? `: ${clean(t.error_description).slice(0, 300)}` : "";
46
+ return `${e}${d}`;
47
+ }
48
+ async function resourceMetadata(url, f = fetch) {
49
+ const u = safeUrl(url, "The server's address");
50
+ const path = u.pathname.replace(/\/$/, "");
51
+ for (const p of [`/.well-known/oauth-protected-resource${path}`, "/.well-known/oauth-protected-resource"]) {
52
+ try {
53
+ const r = await f(new URL(p, u.origin), { headers: { accept: "application/json" }, redirect: "error" });
54
+ if (!r.ok) continue;
55
+ const m = await json(r);
56
+ if (typeof m.resource !== "string" || bare(m.resource) !== bare(u.href)) continue;
57
+ const servers = (Array.isArray(m.authorization_servers) ? m.authorization_servers : []).filter((x) => typeof x === "string");
58
+ if (!servers.length) continue;
59
+ return { resource: m.resource, authorization_servers: servers, ...Array.isArray(m.scopes_supported) ? { scopes_supported: m.scopes_supported.filter((x) => typeof x === "string") } : {} };
60
+ } catch {
61
+ }
62
+ }
63
+ return null;
64
+ }
65
+ async function serverMetadata(issuer, f = fetch) {
66
+ const u = safeUrl(issuer, "The sign-in service");
67
+ const path = u.pathname.replace(/\/$/, "");
68
+ const places = [`${u.origin}/.well-known/oauth-authorization-server${path}`, `${u.origin}/.well-known/openid-configuration${path}`, `${bare(u.href)}/.well-known/openid-configuration`];
69
+ for (const p of [...new Set(places)]) {
70
+ let m;
71
+ try {
72
+ const r = await f(p, { headers: { accept: "application/json" }, redirect: "error" });
73
+ if (!r.ok) continue;
74
+ m = await json(r);
75
+ } catch {
76
+ continue;
77
+ }
78
+ if (typeof m.issuer !== "string" || bare(m.issuer) !== bare(issuer)) continue;
79
+ if (typeof m.token_endpoint !== "string") continue;
80
+ for (const k of ["token_endpoint", "authorization_endpoint", "device_authorization_endpoint", "registration_endpoint"]) if (typeof m[k] === "string") safeUrl(m[k], `The sign-in service's ${k.replace(/_/g, " ")}`);
81
+ return m;
82
+ }
83
+ throw new OAuthError(`The sign-in service ${clean(issuer).slice(0, 200)} publishes no metadata (RFC 8414 or OpenID Connect discovery) that names it.`, 3);
84
+ }
85
+ async function signInServiceOf(url, f = fetch) {
86
+ const resource = await resourceMetadata(url, f);
87
+ if (!resource) return null;
88
+ return { resource, server: await serverMetadata(resource.authorization_servers[0], f) };
89
+ }
90
+ async function asksForSignIn(url, f = fetch, headers = {}) {
91
+ try {
92
+ const r = await f(url, {
93
+ method: "POST",
94
+ redirect: "error",
95
+ signal: AbortSignal.timeout(1e4),
96
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": "2026-07-28", ...headers },
97
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2026-07-28", capabilities: {}, clientInfo: { name: "instruction-md-doctor", version: "1" } } })
98
+ });
99
+ await r.body?.cancel().catch(() => {
100
+ });
101
+ return { status: r.status, asks: r.status === 401 || r.status === 403 && /invalid_token|insufficient_scope/.test(r.headers.get("www-authenticate") ?? "") };
102
+ } catch (e) {
103
+ return { status: 0, asks: false, error: e instanceof Error ? e.message : String(e) };
104
+ }
105
+ }
106
+ async function clientFor(m, redirectUri, o = {}) {
107
+ if (o.clientId) return { client_id: o.clientId, ...o.clientSecret ? { client_secret: o.clientSecret } : {} };
108
+ if (m.client_id_metadata_document_supported) return { client_id: CIMD_URL };
109
+ if (!m.registration_endpoint) throw new OAuthError(`${clean(m.issuer)} offers no way for the CLI to register (no client metadata documents, no dynamic registration): ask its administrator for a client id, then run \`instruction-agents signin … --client-id ID\`.`, 2);
110
+ const grants = ["authorization_code", "refresh_token", ...m.device_authorization_endpoint ? ["urn:ietf:params:oauth:grant-type:device_code"] : []];
111
+ const r = await (o.f ?? fetch)(m.registration_endpoint, {
112
+ method: "POST",
113
+ redirect: "error",
114
+ headers: { "content-type": "application/json", accept: "application/json" },
115
+ body: JSON.stringify({ client_name: CLIENT_NAME, client_uri: "https://instruction.md", application_type: "native", token_endpoint_auth_method: "none", grant_types: grants, response_types: ["code"], redirect_uris: redirectUri ? [redirectUri] : [] })
116
+ });
117
+ const t = await json(r);
118
+ if (!r.ok || typeof t.client_id !== "string") throw new OAuthError(`${clean(m.issuer)} refused the CLI's registration (${why(t, r.status)}).`, 3);
119
+ return { client_id: t.client_id, ...typeof t.client_secret === "string" ? { client_secret: t.client_secret } : {} };
120
+ }
121
+ var clientAuth = (c) => c.client_secret ? { body: {}, headers: { authorization: basic(c.client_id, c.client_secret) } } : { body: { client_id: c.client_id }, headers: {} };
122
+ async function signIn(o) {
123
+ const f = o.f ?? fetch;
124
+ const found = await signInServiceOf(o.url, f);
125
+ if (!found) throw new OAuthError(`${clean(o.url)} describes no sign-in (no protected-resource metadata): it may take a key instead — \`instruction-agents accounts set <server> --env VAR\`.`, 2);
126
+ const { resource, server } = found;
127
+ const scope = o.scope ?? resource.scopes_supported?.join(" ") ?? "";
128
+ if (o.device) return deviceGrant(o, server, resource.resource, scope);
129
+ return codeGrant(o, server, resource.resource, scope);
130
+ }
131
+ async function deviceGrant(o, m, resource, scope) {
132
+ const f = o.f ?? fetch, log = o.log ?? ((l) => console.error(l));
133
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))), now = o.now ?? Date.now;
134
+ if (!m.device_authorization_endpoint) throw new OAuthError(`${clean(m.issuer)} doesn't offer signing in with a code. Run \`instruction-agents signin\` without --device: open the link on any device and paste back the address you end on.`, 2);
135
+ const c = await clientFor(m, null, { ...o, f });
136
+ const auth = clientAuth(c);
137
+ const { verifier, challenge } = pkce();
138
+ const dev = await f(m.device_authorization_endpoint, form({ ...auth.body, ...scope ? { scope } : {}, resource, code_challenge: challenge, code_challenge_method: "S256" }, auth.headers));
139
+ const dj = await json(dev);
140
+ if (!dev.ok || typeof dj.device_code !== "string") throw new OAuthError(`${clean(m.issuer)} didn't give a code (${why(dj, dev.status)}).`, 3);
141
+ const at = clean(safeUrl(dj.verification_uri, "The sign-in link").href);
142
+ let complete;
143
+ try {
144
+ if (typeof dj.verification_uri_complete === "string") complete = clean(safeUrl(dj.verification_uri_complete, "The sign-in link").href);
145
+ } catch {
146
+ }
147
+ const expires = Math.min(Math.max(Number(dj.expires_in) || 600, 1), 3600);
148
+ log(["Open this link on any device (a phone works too):", "", ` ${at}`, "", `and enter the code: ${clean(dj.user_code).slice(0, 64)}`, "", ...complete ? [`(or open ${complete} — the code is filled in)`] : [], "Waiting…"].join("\n"));
149
+ const deadline = now() + expires * 1e3;
150
+ let interval = Math.max(1, Number(dj.interval ?? 5)) * 1e3;
151
+ while (now() < deadline) {
152
+ await sleep(interval);
153
+ let t;
154
+ try {
155
+ t = await f(m.token_endpoint, form({ ...auth.body, grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: dj.device_code, code_verifier: verifier, resource }, auth.headers));
156
+ } catch {
157
+ continue;
158
+ }
159
+ const tj = await json(t);
160
+ if (typeof tj.access_token === "string") return stored("oauth", tj, m, c, resource, scope, now);
161
+ if (tj.error === "authorization_pending") continue;
162
+ if (tj.error === "slow_down") {
163
+ interval += 5e3;
164
+ continue;
165
+ }
166
+ throw new OAuthError(`The sign-in didn't finish (${why(tj, t.status)}).`, tj.error === "access_denied" ? 7 : 1);
167
+ }
168
+ throw new OAuthError("The code expired before it was approved. Run `instruction-agents signin` again.", 3);
169
+ }
170
+ function send(res, status, html) {
171
+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'", "referrer-policy": "no-referrer", "x-content-type-options": "nosniff", connection: "close" });
172
+ res.end(html);
173
+ }
174
+ function terminalLines() {
175
+ if (!process.stdin.isTTY) return null;
176
+ const rl = createInterface({ input: process.stdin, terminal: false });
177
+ return rl;
178
+ }
179
+ async function codeGrant(o, m, resource, scope) {
180
+ const f = o.f ?? fetch, log = o.log ?? ((l) => console.error(l)), now = o.now ?? Date.now;
181
+ if (!m.authorization_endpoint) throw new OAuthError(`${clean(m.issuer)} offers no browser sign-in${m.device_authorization_endpoint ? "; try `--device`" : ""}.`, 2);
182
+ if (m.code_challenge_methods_supported && !m.code_challenge_methods_supported.includes("S256")) throw new OAuthError(`${clean(m.issuer)} doesn't support PKCE (S256), which MCP requires: nothing was sent.`, 2);
183
+ const server = createServer();
184
+ await new Promise((resolve, reject) => {
185
+ server.once("error", reject);
186
+ server.listen(0, "127.0.0.1", () => resolve());
187
+ });
188
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
189
+ let c;
190
+ try {
191
+ c = await clientFor(m, redirectUri, { ...o, f });
192
+ } catch (e) {
193
+ server.close();
194
+ throw e;
195
+ }
196
+ const { verifier, challenge } = pkce();
197
+ const state = randomBytes(16).toString("base64url");
198
+ const link = safeUrl(m.authorization_endpoint, "The sign-in page");
199
+ for (const [k, v] of Object.entries({ client_id: c.client_id, response_type: "code", redirect_uri: redirectUri, state, code_challenge: challenge, code_challenge_method: "S256", resource, ...scope ? { scope } : {} })) link.searchParams.set(k, v);
200
+ const ours = Buffer.from(state);
201
+ const sameState = (got) => {
202
+ const b = Buffer.from(got ?? "");
203
+ return b.length === ours.length && timingSafeEqual(b, ours);
204
+ };
205
+ const timeoutMs = o.timeoutMs ?? 10 * 6e4;
206
+ const name = new URL(o.url).host;
207
+ return new Promise((resolve, reject) => {
208
+ let settled = false, redeeming = false;
209
+ const finish = (e, t) => {
210
+ if (settled) return;
211
+ settled = true;
212
+ clearTimeout(timer);
213
+ server.close();
214
+ server.closeAllConnections?.();
215
+ if (e) reject(e);
216
+ else resolve(t);
217
+ };
218
+ const timer = setTimeout(() => finish(new OAuthError(`Nothing came back in ${Math.round(timeoutMs / 6e4)} minutes. Run \`instruction-agents signin\` again.`, 3)), timeoutMs);
219
+ timer.unref?.();
220
+ const take = async (u, res) => {
221
+ if (!sameState(u.searchParams.get("state"))) {
222
+ const w = "That address belongs to another sign-in, not this one.";
223
+ if (res) send(res, 400, page("Sign-in didn't finish", [w]));
224
+ else log(w);
225
+ return;
226
+ }
227
+ const iss = u.searchParams.get("iss");
228
+ if ((iss !== null || m.authorization_response_iss_parameter_supported) && bare(iss ?? "") !== bare(m.issuer)) {
229
+ const w = `The answer came from another sign-in service (${clean(iss ?? "none named").slice(0, 200)}), not ${clean(m.issuer)}: nothing was signed in.`;
230
+ if (res) send(res, 400, page("Sign-in didn't finish", [w]));
231
+ finish(new OAuthError(w));
232
+ return;
233
+ }
234
+ const error = u.searchParams.get("error");
235
+ if (error) {
236
+ const w = `${name} said: ${clean(error).slice(0, 100)}${u.searchParams.get("error_description") ? ` (${clean(u.searchParams.get("error_description")).slice(0, 300)})` : ""}`;
237
+ if (res) send(res, 400, page("Sign-in didn't finish", [w]));
238
+ finish(new OAuthError(w, error === "access_denied" ? 7 : 1));
239
+ return;
240
+ }
241
+ const code = u.searchParams.get("code");
242
+ if (!code) {
243
+ if (res) send(res, 400, page("Sign-in didn't finish", ["No code came back."]));
244
+ return;
245
+ }
246
+ if (redeeming) {
247
+ if (res) send(res, 409, page("Already finishing", ["This sign-in is already being completed."]));
248
+ return;
249
+ }
250
+ redeeming = true;
251
+ try {
252
+ const auth = clientAuth(c);
253
+ const r = await f(m.token_endpoint, form({ ...auth.body, grant_type: "authorization_code", code, redirect_uri: redirectUri, code_verifier: verifier, resource }, auth.headers));
254
+ const t = await json(r);
255
+ if (!r.ok || typeof t.access_token !== "string") throw new OAuthError(`${name} didn't give a token (${why(t, r.status)}).`);
256
+ if (res) send(res, 200, page("You're signed in", [`The instruction command on your computer is signed in to ${name}.`, "You can close this tab."]));
257
+ finish(null, stored("oauth", t, m, c, resource, scope, now));
258
+ } catch (e) {
259
+ const err = e instanceof OAuthError ? e : new OAuthError(`Couldn't finish at ${name} (${e instanceof Error ? e.message : e}).`, 3);
260
+ if (res) send(res, 400, page("Sign-in didn't finish", [err.message]));
261
+ finish(err);
262
+ }
263
+ };
264
+ server.on("request", (req, res) => {
265
+ const u = new URL(req.url ?? "/", redirectUri);
266
+ if (req.method !== "GET" || u.pathname !== "/callback") {
267
+ res.writeHead(404, { connection: "close" }).end();
268
+ return;
269
+ }
270
+ void take(u, res);
271
+ });
272
+ void (async () => {
273
+ const problem = o.noBrowser ? "asked not to" : browserProblem();
274
+ const opened = !problem && await (o.open ?? openBrowser)(link.href);
275
+ if (settled) return;
276
+ log([
277
+ opened ? `Opening your browser to sign in to ${name}… If it didn't open, use this link:` : `Open this link in a browser — on this computer, or any other device:`,
278
+ "",
279
+ ` ${link.href}`,
280
+ "",
281
+ ...opened ? [] : ["On another device, you'll end on a page at 127.0.0.1 that doesn't load: copy that page's whole address and paste it here."],
282
+ "Waiting…"
283
+ ].join("\n"));
284
+ const lines = o.pasted === void 0 ? terminalLines() : o.pasted;
285
+ if (!lines) return;
286
+ for await (const line of lines) {
287
+ if (settled) break;
288
+ const s = line.trim();
289
+ if (!s) continue;
290
+ let u;
291
+ try {
292
+ u = new URL(s);
293
+ } catch {
294
+ log("That isn't an address. Paste the whole address of the page you ended on (it starts with http://127.0.0.1).");
295
+ continue;
296
+ }
297
+ if (u.origin !== new URL(redirectUri).origin || u.pathname !== "/callback") {
298
+ log(`That address isn't this sign-in's (it should start with ${redirectUri}).`);
299
+ continue;
300
+ }
301
+ await take(u);
302
+ }
303
+ })();
304
+ });
305
+ }
306
+ function stored(kind, t, m, c, resource, scope, now) {
307
+ const exp = Number(t.expires_in);
308
+ return {
309
+ kind,
310
+ access_token: String(t.access_token),
311
+ ...typeof t.refresh_token === "string" ? { refresh_token: t.refresh_token } : {},
312
+ ...Number.isFinite(exp) && exp > 0 ? { expires_at: Math.floor(now() / 1e3) + exp } : {},
313
+ token_endpoint: m.token_endpoint,
314
+ client_id: c.client_id,
315
+ ...c.client_secret ? { client_secret: c.client_secret } : {},
316
+ issuer: m.issuer,
317
+ ...resource ? { resource } : {},
318
+ ...typeof t.scope === "string" ? { scope: t.scope } : scope ? { scope } : {}
319
+ };
320
+ }
321
+ var fresh = (t, now = Date.now()) => !t.expires_at || t.expires_at > now / 1e3 + 60;
322
+ async function refresh(t, f = fetch, now = Date.now) {
323
+ if (!t.refresh_token) throw new OAuthError("The sign-in has lapsed and can't be renewed here", 3);
324
+ const c = { client_id: t.client_id, ...t.client_secret ? { client_secret: t.client_secret } : {} };
325
+ const auth = clientAuth(c);
326
+ const r = await f(t.token_endpoint, form({ ...auth.body, grant_type: "refresh_token", refresh_token: t.refresh_token, ...t.resource ? { resource: t.resource } : {} }, auth.headers));
327
+ const j = await json(r);
328
+ if (!r.ok || typeof j.access_token !== "string") throw new OAuthError(`The sign-in couldn't be renewed (${why(j, r.status)})`, 3);
329
+ const n = stored(t.kind, j, { issuer: t.issuer ?? "", token_endpoint: t.token_endpoint }, c, t.resource, t.scope ?? "", now);
330
+ return { ...n, ...n.refresh_token ? {} : t.refresh_token ? { refresh_token: t.refresh_token } : {} };
331
+ }
332
+ var ID_JAG = "urn:ietf:params:oauth:token-type:id-jag";
333
+ var ID_TOKEN = "urn:ietf:params:oauth:token-type:id_token";
334
+ async function xaaToken(x, f = fetch, now = Date.now) {
335
+ safeUrl(x.idp, "The identity provider's token address");
336
+ let audience = x.audience, tokenEndpoint = x.tokenEndpoint;
337
+ if (!audience || !tokenEndpoint) {
338
+ const found = await signInServiceOf(x.resource, f);
339
+ if (!found) throw new OAuthError(`${clean(x.resource)} describes no sign-in service, so no assertion can be made for it`, 2);
340
+ audience ??= found.server.issuer;
341
+ tokenEndpoint ??= found.server.token_endpoint;
342
+ }
343
+ safeUrl(tokenEndpoint, "The server's token address");
344
+ const ia = clientAuth(x.idpClient);
345
+ const r1 = await f(x.idp, form({ ...ia.body, grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", requested_token_type: ID_JAG, subject_token: x.subjectToken, subject_token_type: x.subjectTokenType ?? ID_TOKEN, audience, resource: x.resource, ...x.scope ? { scope: x.scope } : {} }, ia.headers));
346
+ const j1 = await json(r1);
347
+ if (!r1.ok || typeof j1.access_token !== "string") throw new OAuthError(`The identity provider gave no assertion for ${new URL(x.resource).host} (${why(j1, r1.status)})`, 3);
348
+ if (typeof j1.issued_token_type === "string" && j1.issued_token_type !== ID_JAG) throw new OAuthError(`The identity provider gave a ${clean(j1.issued_token_type).slice(0, 80)}, not an identity assertion`, 3);
349
+ const sa = clientAuth(x.serverClient);
350
+ const r2 = await f(tokenEndpoint, form({ ...sa.body, grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: j1.access_token, ...x.scope ? { scope: x.scope } : {} }, sa.headers));
351
+ const j2 = await json(r2);
352
+ if (!r2.ok || typeof j2.access_token !== "string") throw new OAuthError(`${new URL(x.resource).host} didn't take the identity assertion (${why(j2, r2.status)})`, 3);
353
+ return stored("xaa", j2, { issuer: audience, token_endpoint: tokenEndpoint }, x.serverClient, x.resource, x.scope ?? "", now);
354
+ }
355
+ export {
356
+ CIMD_URL,
357
+ CLIENT_NAME,
358
+ ID_JAG,
359
+ ID_TOKEN,
360
+ OAuthError,
361
+ asksForSignIn,
362
+ clientFor,
363
+ configDir,
364
+ fresh,
365
+ loadTokens,
366
+ refresh,
367
+ resourceMetadata,
368
+ saveTokens,
369
+ serverMetadata,
370
+ signIn,
371
+ signInServiceOf,
372
+ tokensPath,
373
+ xaaToken
374
+ };
package/dist/pi.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ import { FoundFollow, Reader, Current } from 'instruction.md/cli';
2
+ export { Current, FoundFollow, Reader } from 'instruction.md/cli';
3
+
4
+ /** How a follower reads, and reports what a session applied, for one app. */
5
+ interface Access {
6
+ reader(found: FoundFollow): Promise<Reader | null>;
7
+ report(cur: Current, sessionId: string, found: FoundFollow): Promise<boolean>;
8
+ close(): Promise<void>;
9
+ }
10
+
11
+ /** The name of the system prompt section: pi writes it as `<instruction>…</instruction>`. */
12
+ declare const PI_SECTION = "instruction";
13
+ /** What this extension uses of pi's ExtensionContext. */
14
+ interface PiContext {
15
+ cwd?: string;
16
+ hasUI?: boolean;
17
+ ui?: {
18
+ notify(message: string, level?: "info" | "warning" | "error"): void;
19
+ };
20
+ sessionManager?: {
21
+ getSessionId?(): string | undefined;
22
+ };
23
+ }
24
+ /** What it uses of `before_agent_start`'s event. */
25
+ interface PiBeforeAgentStart {
26
+ messageType?: "user" | "custom";
27
+ systemPromptOptions?: {
28
+ cwd?: string;
29
+ sections?: Record<string, string>;
30
+ };
31
+ }
32
+ /** What it uses of pi's ExtensionAPI. */
33
+ interface PiApi {
34
+ on(event: "before_agent_start", handler: (event: PiBeforeAgentStart, ctx: PiContext) => unknown): unknown;
35
+ on(event: "session_start" | "session_shutdown", handler: (event: {
36
+ reason?: string;
37
+ }, ctx: PiContext) => unknown): unknown;
38
+ }
39
+ interface PiOptions {
40
+ /** Follow this instruction by its address, not a project's follow.json. */
41
+ follow?: string;
42
+ requireSignature?: boolean;
43
+ /** The MCP server (default follow.json's url, INSTRUCTION_MD_URL, else https://instruction.md/mcp). */
44
+ url?: string;
45
+ /** How long a read may take before the last good copy is used (default 1,500 ms). */
46
+ deadlineMs?: number;
47
+ /** How to read and report (tests). */
48
+ access?: Access;
49
+ now?: () => number;
50
+ }
51
+ /** The section's text: where it comes from, then the instruction as a model receives it. */
52
+ declare function piSection(cur: Current): string;
53
+ /** The extension, with options (for the pi SDK's `extensionFactories`). */
54
+ declare function piExtension(o?: PiOptions): (pi: PiApi) => void;
55
+ /** pi loads a module's default export as the extension. */
56
+ declare const _default: (pi: PiApi) => void;
57
+
58
+ export { PI_SECTION, _default as default, piExtension, piSection };
59
+ export type { Access, PiApi, PiBeforeAgentStart, PiContext, PiOptions };
package/dist/pi.js ADDED
@@ -0,0 +1,89 @@
1
+ // src/pi.ts
2
+ import { fetchCurrent, FollowConfigError, labelOf } from "instruction.md/cli";
3
+ import { followFor, registryAccess } from "./turns.js";
4
+ var PI_SECTION = "instruction";
5
+ var ver = (c) => c.version ? `v${c.version}` : c.versionId;
6
+ function piSection(cur) {
7
+ return [
8
+ `These are this project's instructions from instruction.md (${cur.label} ${ver(cur)}, ${cur.digest.slice(0, 19)}). Follow them; a newer version replaces this one in full.`,
9
+ "",
10
+ cur.text.replace(/\n+$/, "")
11
+ ].join("\n");
12
+ }
13
+ function piExtension(o = {}) {
14
+ return (pi) => {
15
+ let access = o.access ?? null;
16
+ const holds = /* @__PURE__ */ new Map();
17
+ const said = /* @__PURE__ */ new Set();
18
+ const reported = /* @__PURE__ */ new Set();
19
+ const tell = (ctx, key, message, level = "info") => {
20
+ if (said.has(key)) return;
21
+ said.add(key);
22
+ try {
23
+ if (ctx.hasUI !== false) ctx.ui?.notify(message, level);
24
+ } catch {
25
+ }
26
+ };
27
+ pi.on("before_agent_start", async (event, ctx) => {
28
+ try {
29
+ const sections = event.systemPromptOptions?.sections;
30
+ if (!sections) return;
31
+ const cwd = event.systemPromptOptions?.cwd ?? ctx.cwd ?? process.cwd();
32
+ let found;
33
+ try {
34
+ found = followFor(cwd, { ...o.follow ? { follow: o.follow } : {}, ...o.requireSignature ? { requireSignature: true } : {} });
35
+ } catch (e) {
36
+ tell(ctx, "config", `instruction.md: ${e instanceof FollowConfigError ? e.message : String(e)}`, "warning");
37
+ return;
38
+ }
39
+ if (!found) return;
40
+ if (o.requireSignature) found.config.requireSignature = true;
41
+ access ??= registryAccess("pi", o.url ? { url: o.url } : {});
42
+ const acc = access;
43
+ const r = await fetchCurrent(found, { deadlineMs: o.deadlineMs ?? 1500, ...o.now ? { now: o.now } : {}, reader: () => acc.reader(found) });
44
+ const cur = r.current;
45
+ const label = cur?.label ?? labelOf(found.config.follow);
46
+ if (!cur) {
47
+ tell(ctx, "none", `instruction.md: couldn't read ${label} (${r.hold?.reason ?? r.error ?? "nothing was read"}); this session goes on without it`, "warning");
48
+ return;
49
+ }
50
+ sections[PI_SECTION] = piSection(cur);
51
+ const sid = ctx.sessionManager?.getSessionId?.() ?? "pi";
52
+ const prev = holds.get(sid);
53
+ if (prev && prev.digest !== cur.digest) {
54
+ said.delete(`v:${cur.digest}`);
55
+ tell(ctx, `v:${cur.digest}`, `instruction.md: ${label} ${prev.version ? `v${prev.version}` : prev.versionId} → ${ver(cur)}${cur.verified ? " (signature verified)" : ""}`);
56
+ }
57
+ if (r.hold) tell(ctx, `hold:${r.hold.versionId ?? r.hold.reason}`, `instruction.md: a newer version of ${label} is held (${r.hold.reason}); keeping ${ver(cur)}`, "warning");
58
+ if (r.source === "stale" && r.error && !prev) tell(ctx, "stale", `instruction.md: ${label} couldn't be read now (${r.error}); using the last good copy, ${ver(cur)}`, "warning");
59
+ holds.set(sid, { digest: cur.digest, version: cur.version, versionId: cur.versionId });
60
+ const key = `${sid}
61
+ ${cur.versionId}`;
62
+ if (!reported.has(key)) {
63
+ reported.add(key);
64
+ void acc.report(cur, sid, found).then((ok) => {
65
+ if (!ok) reported.delete(key);
66
+ }, () => {
67
+ reported.delete(key);
68
+ });
69
+ }
70
+ } catch {
71
+ }
72
+ });
73
+ pi.on("session_shutdown", async () => {
74
+ if (!o.access && access) {
75
+ const a = access;
76
+ access = null;
77
+ await a.close().catch(() => {
78
+ });
79
+ }
80
+ });
81
+ };
82
+ }
83
+ var pi_default = piExtension();
84
+ export {
85
+ PI_SECTION,
86
+ pi_default as default,
87
+ piExtension,
88
+ piSection
89
+ };