@instruction.md/agents 0.0.0-stage → 0.1.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/acp.js ADDED
@@ -0,0 +1,268 @@
1
+ // src/acp.ts
2
+ import { spawn } from "node:child_process";
3
+ import { join, resolve } from "node:path";
4
+ import { capBlock, contextBlock, DEFAULT_MAX_INJECT_CHARS, DEFAULT_URL, fetchCurrent, FollowConfigError, labelOf, updateBlock } from "instruction.md/cli";
5
+ import { followFor, registryAccess } from "./turns.js";
6
+ var ACP_BRIDGE_NAME = "instruction-md";
7
+ var AcpProxy = class {
8
+ constructor(o = {}) {
9
+ this.o = o;
10
+ this.access = o.access ?? registryAccess("acp", o.url ? { url: o.url } : {});
11
+ }
12
+ systemPrompt = false;
13
+ /** The agent's answer to initialize, awaited before a session is made (what it takes is in it). */
14
+ initialized = null;
15
+ pending = /* @__PURE__ */ new Map();
16
+ sessions = /* @__PURE__ */ new Map();
17
+ reported = /* @__PURE__ */ new Set();
18
+ access;
19
+ log(line) {
20
+ (this.o.log ?? ((l) => process.stderr.write(`${l}
21
+ `)))(line);
22
+ }
23
+ key(id) {
24
+ return JSON.stringify(id);
25
+ }
26
+ /** The follow for a session's directory (a follow.json that can't be read is said once, then none). */
27
+ find(cwd) {
28
+ try {
29
+ const found = followFor(cwd, { ...this.o.follow ? { follow: this.o.follow } : {}, ...this.o.requireSignature ? { requireSignature: true } : {} });
30
+ if (found && this.o.requireSignature) found.config.requireSignature = true;
31
+ return found;
32
+ } catch (e) {
33
+ this.log(`instruction.md: ${e instanceof FollowConfigError ? e.message : String(e)}`);
34
+ return null;
35
+ }
36
+ }
37
+ async current(found) {
38
+ const r = await fetchCurrent(found, { deadlineMs: this.o.deadlineMs ?? 1500, ...this.o.now ? { now: this.o.now } : {}, reader: () => this.access.reader(found) });
39
+ if (!r.current) this.log(`instruction.md: couldn't read ${labelOf(found.config.follow)} (${r.hold?.reason ?? r.error ?? "nothing was read"})`);
40
+ else if (r.hold) this.log(`instruction.md: a newer version of ${r.current.label} is held (${r.hold.reason}); keeping v${r.current.version}`);
41
+ return r.current;
42
+ }
43
+ /** The bridge, as an ACP stdio MCP server (an absolute command, its args, its environment). */
44
+ bridge(found) {
45
+ const url = this.o.url ?? found.config.url ?? process.env.INSTRUCTION_MD_URL ?? DEFAULT_URL;
46
+ const run = this.o.bridgeCommand ?? { command: process.execPath, args: [resolve(process.argv[1] ?? "instruction")] };
47
+ return { name: ACP_BRIDGE_NAME, command: run.command, args: [...run.args, "mcp", "--follow", found.config.follow, "--url", url], env: [] };
48
+ }
49
+ report(sid, cur, found) {
50
+ const k = `${sid}
51
+ ${cur.versionId}`;
52
+ if (this.reported.has(k)) return;
53
+ this.reported.add(k);
54
+ void this.access.report(cur, sid, found).then((ok) => {
55
+ if (!ok) this.reported.delete(k);
56
+ }, () => {
57
+ this.reported.delete(k);
58
+ });
59
+ }
60
+ /** A message from the client, on its way to the agent: the messages to send it (one, changed or not). */
61
+ async fromClient(m) {
62
+ if (!m || typeof m !== "object" || typeof m.method !== "string") return m;
63
+ const p = m.params ?? {};
64
+ if ((m.method === "session/new" || m.method === "session/load" || m.method === "session/resume") && typeof p.cwd === "string") {
65
+ if (this.initialized) await Promise.race([this.initialized.promise, new Promise((r) => {
66
+ const t = setTimeout(r, 5e3);
67
+ t.unref?.();
68
+ })]);
69
+ const cwd = p.cwd;
70
+ const found = this.find(cwd);
71
+ const cur = found ? await this.current(found) : null;
72
+ const params = { ...p };
73
+ let viaSystemPrompt = false;
74
+ if (found && cur) {
75
+ if (this.systemPrompt) {
76
+ const block = { type: "text", text: contextBlock(cur) };
77
+ const sent = p.systemPrompt;
78
+ params.systemPrompt = sent && Array.isArray(sent.content) ? { ...sent, content: [...sent.content, block] } : { mode: "append", content: [block] };
79
+ viaSystemPrompt = true;
80
+ }
81
+ if (!this.o.noBridge) {
82
+ const servers = Array.isArray(p.mcpServers) ? p.mcpServers : [];
83
+ if (!servers.some((s) => s?.name === ACP_BRIDGE_NAME)) params.mcpServers = [...servers, this.bridge(found)];
84
+ }
85
+ }
86
+ if (m.id !== void 0 && m.id !== null) this.pending.set(this.key(m.id), { method: m.method, cwd, found, viaSystemPrompt, cur });
87
+ if (m.method !== "session/new" && typeof p.sessionId === "string") this.started(p.sessionId, cwd, found, viaSystemPrompt, cur);
88
+ return { ...m, params };
89
+ }
90
+ if (m.method === "session/prompt" && typeof p.sessionId === "string" && Array.isArray(p.prompt)) {
91
+ const s = this.sessions.get(p.sessionId);
92
+ if (!s?.found) return m;
93
+ const cur = await this.current(s.found);
94
+ if (!cur) return m;
95
+ let add = null;
96
+ if (!s.given) add = contextBlock(cur);
97
+ else if (s.given.digest !== cur.digest) {
98
+ add = updateBlock(s.given, cur);
99
+ this.log(`instruction.md: ${cur.label} ${s.given.version ? `v${s.given.version}` : s.given.versionId} → v${cur.version}${cur.verified ? " (signature verified)" : ""}`);
100
+ }
101
+ s.given = { digest: cur.digest, version: cur.version, versionId: cur.versionId };
102
+ this.report(p.sessionId, cur, s.found);
103
+ if (!add) return m;
104
+ const max = s.found.config.maxInjectChars ?? DEFAULT_MAX_INJECT_CHARS;
105
+ const where = join(s.found.dir, "current.md");
106
+ return { ...m, params: { ...p, prompt: [{ type: "text", text: capBlock(add, max, where) }, ...p.prompt] } };
107
+ }
108
+ if (m.method === "initialize" && m.id !== void 0 && m.id !== null) {
109
+ this.pending.set(this.key(m.id), { method: "initialize" });
110
+ let done = () => {
111
+ };
112
+ const promise = new Promise((r) => {
113
+ done = r;
114
+ });
115
+ this.initialized = { promise, done };
116
+ }
117
+ return m;
118
+ }
119
+ /** A message from the agent, on its way to the client: always passed on as it is; read for what the proxy learns. */
120
+ fromAgent(m) {
121
+ if (!m || typeof m !== "object" || m.method !== void 0 || m.id === void 0 || m.id === null) return m;
122
+ const k = this.key(m.id);
123
+ const req = this.pending.get(k);
124
+ if (!req) return m;
125
+ this.pending.delete(k);
126
+ if (req.method === "initialize") this.initialized?.done();
127
+ if (m.error || !m.result) return m;
128
+ if (req.method === "initialize") {
129
+ const caps = m.result.agentCapabilities?.sessionCapabilities;
130
+ this.systemPrompt = !!caps && caps.systemPrompt !== void 0 && caps.systemPrompt !== null;
131
+ } else if (req.method === "session/new" && typeof m.result.sessionId === "string") {
132
+ this.started(m.result.sessionId, req.cwd ?? process.cwd(), req.found ?? null, !!req.viaSystemPrompt, req.cur ?? null);
133
+ }
134
+ return m;
135
+ }
136
+ started(sid, cwd, found, viaSystemPrompt, cur) {
137
+ const s = { cwd, found, viaSystemPrompt };
138
+ if (viaSystemPrompt && cur) {
139
+ s.given = { digest: cur.digest, version: cur.version, versionId: cur.versionId };
140
+ if (found) this.report(sid, cur, found);
141
+ }
142
+ this.sessions.set(sid, s);
143
+ }
144
+ async close() {
145
+ if (!this.o.access) await this.access.close();
146
+ }
147
+ };
148
+ var ACP_USAGE = "usage: instruction-agents acp [--follow URI [--require-signature]] [--url U] [--no-bridge] -- <agent command> [args…]";
149
+ function lines(onLine) {
150
+ let rest = "";
151
+ return {
152
+ push(chunk) {
153
+ rest += chunk.toString();
154
+ let i;
155
+ while ((i = rest.indexOf("\n")) >= 0) {
156
+ const l = rest.slice(0, i).replace(/\r$/, "");
157
+ rest = rest.slice(i + 1);
158
+ onLine(l);
159
+ }
160
+ },
161
+ end() {
162
+ if (rest) {
163
+ onLine(rest);
164
+ rest = "";
165
+ }
166
+ }
167
+ };
168
+ }
169
+ var parse = (line) => {
170
+ try {
171
+ const v = JSON.parse(line);
172
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
173
+ } catch {
174
+ return null;
175
+ }
176
+ };
177
+ async function cmdAcp(args) {
178
+ const dash = args.indexOf("--");
179
+ if (dash < 0 || dash === args.length - 1) {
180
+ console.error(ACP_USAGE);
181
+ return 1;
182
+ }
183
+ const agent = args.slice(dash + 1);
184
+ const own = args.slice(0, dash);
185
+ const take = (flag) => {
186
+ const i = own.indexOf(flag);
187
+ if (i < 0) return void 0;
188
+ const v = own[i + 1];
189
+ own.splice(i, 2);
190
+ return v;
191
+ };
192
+ const has = (flag) => {
193
+ const i = own.indexOf(flag);
194
+ if (i < 0) return false;
195
+ own.splice(i, 1);
196
+ return true;
197
+ };
198
+ const follow = take("--follow"), url = take("--url");
199
+ const requireSignature = has("--require-signature"), noBridge = has("--no-bridge");
200
+ if (own.length) {
201
+ console.error(ACP_USAGE);
202
+ return 1;
203
+ }
204
+ const proxy = new AcpProxy({ ...follow ? { follow } : {}, ...url ? { url } : {}, requireSignature, noBridge });
205
+ const child = spawn(agent[0], agent.slice(1), { stdio: ["pipe", "pipe", "inherit"] });
206
+ const toAgent = (m) => {
207
+ child.stdin.write(`${typeof m === "string" ? m : JSON.stringify(m)}
208
+ `);
209
+ };
210
+ const toClient = (m) => {
211
+ process.stdout.write(`${typeof m === "string" ? m : JSON.stringify(m)}
212
+ `);
213
+ };
214
+ let chain = Promise.resolve();
215
+ const fromClient = lines((line) => {
216
+ chain = chain.then(async () => {
217
+ if (!line.trim()) return;
218
+ const m = parse(line);
219
+ if (!m) {
220
+ toAgent(line);
221
+ return;
222
+ }
223
+ try {
224
+ toAgent(await proxy.fromClient(m));
225
+ } catch (e) {
226
+ process.stderr.write(`instruction-agents acp: ${e instanceof Error ? e.message : String(e)}
227
+ `);
228
+ toAgent(m);
229
+ }
230
+ });
231
+ });
232
+ process.stdin.on("data", (c) => fromClient.push(c));
233
+ process.stdin.on("end", () => {
234
+ fromClient.end();
235
+ void chain.then(() => child.stdin.end());
236
+ });
237
+ const fromAgent = lines((line) => {
238
+ if (!line.trim()) return;
239
+ const m = parse(line);
240
+ if (!m) {
241
+ toClient(line);
242
+ return;
243
+ }
244
+ try {
245
+ toClient(proxy.fromAgent(m));
246
+ } catch {
247
+ toClient(line);
248
+ }
249
+ });
250
+ child.stdout.on("data", (c) => fromAgent.push(c));
251
+ child.stdout.on("end", () => fromAgent.end());
252
+ const code = await new Promise((done) => {
253
+ child.on("error", (e) => {
254
+ process.stderr.write(`instruction-agents acp: couldn't run ${agent[0]}: ${e.message}
255
+ `);
256
+ done(127);
257
+ });
258
+ child.on("exit", (c, signal) => done(c ?? (signal ? 1 : 0)));
259
+ });
260
+ await proxy.close();
261
+ return code;
262
+ }
263
+ export {
264
+ ACP_BRIDGE_NAME,
265
+ ACP_USAGE,
266
+ AcpProxy,
267
+ cmdAcp
268
+ };
@@ -0,0 +1,60 @@
1
+ import { JWK } from 'jose';
2
+ import { FollowerClient } from 'instruction.md/consumer';
3
+ import { Current } from 'instruction.md/cli';
4
+ export { Current } from 'instruction.md/cli';
5
+
6
+ interface FollowOptions {
7
+ /** The instruction.md MCP server (default `INSTRUCTION_MD_URL`, else https://instruction.md/mcp). */
8
+ url?: string;
9
+ /** A bearer token, or a function that answers one before each read (default `INSTRUCTION_MD_TOKEN`). An agent's token
10
+ * comes from its client credentials (`instruction agents create`). */
11
+ token?: string | (() => string | undefined | Promise<string | undefined>);
12
+ /** Your own client instead (anything with `readResource` and `callTool`, as the MCP SDK's Client has): url and token
13
+ * are then not used. */
14
+ client?: FollowerClient;
15
+ /** Take only versions whose author signature verifies (a version that doesn't is never handed over). */
16
+ requireSignature?: boolean;
17
+ /** The author keys accepted, else the publisher's from the registry. */
18
+ keys?: JWK[];
19
+ /** How long a version is used before the next read (default 60). */
20
+ refreshSeconds?: number;
21
+ /** How long a read may take before the version in hand is kept (default 5,000 ms). */
22
+ deadlineMs?: number;
23
+ /** The clock (tests). */
24
+ now?: () => number;
25
+ }
26
+ /** An instruction followed: the version in hand and what changed since the model was last told. */
27
+ interface Followed {
28
+ /** The address followed. */
29
+ readonly uri: string;
30
+ /** owner/name, else the address. */
31
+ readonly label: string;
32
+ /** The delivered text of the version in hand. */
33
+ readonly text: string;
34
+ /** Its number: v1, v2 … */
35
+ readonly version: number;
36
+ readonly versionId: string;
37
+ /** sha256:… of its delivered text (what a hook records per session). */
38
+ readonly digest: string;
39
+ /** Its author signature was checked and holds. */
40
+ readonly verified: boolean;
41
+ /** The version in hand, whole. */
42
+ readonly current: Current;
43
+ /** Read again now: true when a new version came. A failed read keeps the version in hand (false). */
44
+ refresh(): Promise<boolean>;
45
+ /** Between turns: reads again once `refreshSeconds` passed, and says whether the version differs from the one the
46
+ * model was last given (the first one counts as given). Once true, the next call is false until another version. */
47
+ changedSinceLastTurn(): Promise<boolean>;
48
+ /** What to tell the model of the version changedSinceLastTurn found: it replaces the earlier one in full. */
49
+ updateBlock(): string;
50
+ /** The version in hand, as a block to give a model at the start (with what it is and that it is to be followed). */
51
+ contextBlock(): string;
52
+ /** Stops: closes the client it made (not one you gave it). */
53
+ close(): Promise<void>;
54
+ }
55
+ /** Follows an instruction: reads its version now (throws when there is none to hand over: not found, not allowed,
56
+ * held for its signature). */
57
+ declare function follow(uri: string, o?: FollowOptions): Promise<Followed>;
58
+
59
+ export { follow };
60
+ export type { FollowOptions, Followed };
package/dist/agent.js ADDED
@@ -0,0 +1,86 @@
1
+ // src/agent.ts
2
+ import { asSdkClient, createClient } from "instruction.md/client";
3
+ import { asInstructionUri as asUri, contextBlock as contextOf, followerReader, readOnce, updateBlock as updateOf } from "instruction.md/cli";
4
+ var DEFAULT_URL = "https://instruction.md/mcp";
5
+ async function follow(uri, o = {}) {
6
+ const target = asUri(uri);
7
+ const now = o.now ?? Date.now;
8
+ const every = (o.refreshSeconds ?? 60) * 1e3;
9
+ let made = null;
10
+ let client;
11
+ if (o.client) client = o.client;
12
+ else {
13
+ const token = o.token ?? process.env.INSTRUCTION_MD_TOKEN;
14
+ const sdk = asSdkClient(createClient({
15
+ url: o.url ?? process.env.INSTRUCTION_MD_URL ?? DEFAULT_URL,
16
+ token: typeof token === "function" ? token : () => token,
17
+ clientInfo: { name: "instruction-md-agent", version: "1" }
18
+ }));
19
+ made = sdk;
20
+ client = { readResource: (p) => sdk.readResource(p), callTool: (p) => sdk.callTool(p) };
21
+ }
22
+ const reader = followerReader(client, { requireSignature: !!o.requireSignature, ...o.keys?.length ? { authorKeys: o.keys } : {} });
23
+ const read = () => readOnce(target, { reader, deadlineMs: o.deadlineMs ?? 5e3, now });
24
+ let cur;
25
+ try {
26
+ cur = await read();
27
+ } catch (e) {
28
+ await made?.close().catch(() => {
29
+ });
30
+ throw e;
31
+ }
32
+ let at = now();
33
+ let given = cur, before = null;
34
+ const refresh = async () => {
35
+ at = now();
36
+ try {
37
+ const got = await read();
38
+ if (got.versionId === cur.versionId) return false;
39
+ cur = got;
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ };
45
+ return {
46
+ uri: target,
47
+ get label() {
48
+ return cur.label;
49
+ },
50
+ get text() {
51
+ return cur.text;
52
+ },
53
+ get version() {
54
+ return cur.version;
55
+ },
56
+ get versionId() {
57
+ return cur.versionId;
58
+ },
59
+ get digest() {
60
+ return cur.digest;
61
+ },
62
+ get verified() {
63
+ return cur.verified;
64
+ },
65
+ get current() {
66
+ return cur;
67
+ },
68
+ refresh,
69
+ async changedSinceLastTurn() {
70
+ if (now() - at >= every) await refresh();
71
+ if (cur.versionId === given.versionId) return false;
72
+ before = given;
73
+ given = cur;
74
+ return true;
75
+ },
76
+ updateBlock: () => updateOf(before, given),
77
+ contextBlock: () => contextOf(cur),
78
+ async close() {
79
+ await made?.close().catch(() => {
80
+ });
81
+ }
82
+ };
83
+ }
84
+ export {
85
+ follow
86
+ };