@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.
@@ -0,0 +1,229 @@
1
+ // src/converse.ts
2
+ import { basename } from "node:path";
3
+ var VALUE_FLAGS = /* @__PURE__ */ new Set([
4
+ "--model",
5
+ "--fallback-model",
6
+ "--permission-mode",
7
+ "--settings",
8
+ "--setting-sources",
9
+ "--append-system-prompt",
10
+ "--system-prompt",
11
+ "--system-prompt-file",
12
+ "--append-system-prompt-file",
13
+ "--max-turns",
14
+ "--max-budget-usd",
15
+ "--agents",
16
+ "--agent",
17
+ "--session-id",
18
+ "--resume",
19
+ "-r",
20
+ "--json-schema",
21
+ "--permission-prompt-tool",
22
+ "--output-format",
23
+ "--input-format",
24
+ "--betas",
25
+ "--debug-file",
26
+ "--name",
27
+ "-n",
28
+ "--effort"
29
+ ]);
30
+ var MANY_FLAGS = /* @__PURE__ */ new Set(["--mcp-config", "--allowedTools", "--allowed-tools", "--disallowedTools", "--disallowed-tools", "--add-dir", "--plugin-dir", "--tools"]);
31
+ function converseArgv(argv) {
32
+ if (basename(argv[0] ?? "").replace(/\.(exe|cmd)$/i, "") !== "claude") return null;
33
+ const p = argv.findIndex((a) => a === "-p" || a === "--print");
34
+ if (p < 0 || argv.includes("--input-format") || argv.includes("--output-format")) return null;
35
+ let at = -1;
36
+ if (argv[p + 1] !== void 0 && !argv[p + 1].startsWith("-")) at = p + 1;
37
+ else {
38
+ const last = argv.length - 1, before = argv[last - 1] ?? "";
39
+ let inMany = false;
40
+ for (let i = 1; i < last; i++) {
41
+ if (argv[i].startsWith("-")) inMany = MANY_FLAGS.has(argv[i]);
42
+ }
43
+ if (last > p && !argv[last].startsWith("-") && !VALUE_FLAGS.has(before) && !inMany) at = last;
44
+ }
45
+ if (at < 0 || !argv[at].trim()) return null;
46
+ const out = argv.filter((_, i) => i !== at);
47
+ out.push("--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--permission-prompt-tool", "stdio");
48
+ if (!argv.includes("--permission-mode") && !argv.includes("--dangerously-skip-permissions")) out.push("--permission-mode", "default");
49
+ return { argv: out, prompt: argv[at] };
50
+ }
51
+ var SECRETS = [
52
+ /\b(?:sk|rk|pk)-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{16,}/g,
53
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
54
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
55
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}/g,
56
+ /\bAKIA[0-9A-Z]{16}\b/g,
57
+ /\bAIza[0-9A-Za-z_-]{30,}/g,
58
+ /\bglpat-[A-Za-z0-9_-]{16,}/g,
59
+ /\bnpm_[A-Za-z0-9]{30,}/g,
60
+ /(\b[Bb]earer\s+)[A-Za-z0-9._~+/=-]{12,}/g,
61
+ /(\b(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*)("[^"]+"|'[^']+'|\S+)/gi,
62
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
63
+ // (a long random string: upper and lower case and digits together — not a path, not a commit's lowercase hex)
64
+ /(?<![A-Za-z0-9+_-])(?=[A-Za-z0-9+_-]*[0-9])(?=[A-Za-z0-9+_-]*[a-z])(?=[A-Za-z0-9+_-]*[A-Z])[A-Za-z0-9+_-]{32,}={0,2}/g
65
+ ];
66
+ function maskText(s) {
67
+ let out = s;
68
+ for (const re of SECRETS) out = out.replace(re, (m, a) => typeof a === "string" && m.startsWith(a) && a.length < m.length ? `${a}•••` : "•••");
69
+ return out;
70
+ }
71
+ function masked(v, max = 3500) {
72
+ const walk = (x, depth) => {
73
+ if (typeof x === "string") return maskText(x.length > 1500 ? `${x.slice(0, 1500)}…` : x);
74
+ if (Array.isArray(x)) return depth > 6 ? "…" : x.slice(0, 40).map((y) => walk(y, depth + 1));
75
+ if (x && typeof x === "object") return depth > 6 ? "…" : Object.fromEntries(Object.entries(x).slice(0, 40).map(([k, y]) => [k, /secret|token|password|api.?key|authorization/i.test(k) ? "•••" : walk(y, depth + 1)]));
76
+ return x;
77
+ };
78
+ let out = walk(v, 0);
79
+ if (JSON.stringify(out ?? null).length > max) out = { shown: maskText(JSON.stringify(v)).slice(0, max - 200) + "…" };
80
+ return out;
81
+ }
82
+ var cut = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
83
+ function toolLine(name, input) {
84
+ const i = input ?? {};
85
+ const what = typeof i.command === "string" ? i.command : typeof i.file_path === "string" ? i.file_path : typeof i.path === "string" ? i.path : typeof i.pattern === "string" ? i.pattern : typeof i.url === "string" ? i.url : typeof i.description === "string" ? i.description : "";
86
+ return cut(maskText(`${name}${what ? `: ${what.replace(/\s+/g, " ")}` : ""}`), 480);
87
+ }
88
+ function cardOf(req, context) {
89
+ const input = req.input ?? {};
90
+ if (req.tool_name === "AskUserQuestion" && Array.isArray(input.questions)) {
91
+ const questions = input.questions.slice(0, 4).map((q) => ({
92
+ question: cut(String(q.question ?? ""), 500),
93
+ ...typeof q.header === "string" ? { header: cut(q.header, 40) } : {},
94
+ multiSelect: q.multiSelect === true,
95
+ options: (Array.isArray(q.options) ? q.options : []).slice(0, 6).map((o) => ({ label: cut(String(o.label ?? ""), 80), ...typeof o.description === "string" ? { description: cut(o.description, 300) } : {} }))
96
+ }));
97
+ return { kind: "question", questions, ...context ? { context: cut(context, 1e3) } : {} };
98
+ }
99
+ const description = typeof req.description === "string" ? req.description : typeof input.description === "string" ? input.description : void 0;
100
+ return {
101
+ kind: "permission",
102
+ tool: { name: cut(String(req.tool_name ?? "a tool"), 120), input: masked(input), ...description ? { description: cut(maskText(description), 500) } : {} },
103
+ ...Array.isArray(req.permission_suggestions) && JSON.stringify(req.permission_suggestions).length <= 2048 ? { suggestions: req.permission_suggestions } : {},
104
+ ...context ? { context: cut(context, 1e3) } : {}
105
+ };
106
+ }
107
+ function responseOf(req, a, minutes) {
108
+ const note = a.answer?.note ? `${a.by ? `${a.by} added` : "A note"}: ${a.answer.note}` : void 0;
109
+ if (req.tool_name === "AskUserQuestion") {
110
+ if (a.state === "answered" && a.answer?.answers) return { response: { behavior: "allow", updatedInput: { ...req.input ?? {}, answers: a.answer.answers } }, ...note ? { note } : {} };
111
+ return { response: { behavior: "deny", message: a.state === "expired" ? `Nobody answered within ${minutes} minutes: choose the safest option yourself, and say which you chose.` : "The question was withdrawn: go on as you think best, and say what you chose." } };
112
+ }
113
+ if (a.state === "answered" && (a.answer?.decision === "allow" || a.answer?.decision === "allow_run")) {
114
+ return { response: { behavior: "allow", updatedInput: req.input ?? {}, ...a.answer.decision === "allow_run" && Array.isArray(req.permission_suggestions) ? { updatedPermissions: req.permission_suggestions } : {} }, ...note ? { note } : {} };
115
+ }
116
+ if (a.state === "answered") return { response: { behavior: "deny", message: `${a.by ?? "A person"} said no through instruction.md.${a.answer?.note ? ` Their note: ${a.answer.note}` : ""}` } };
117
+ return { response: { behavior: "deny", message: a.state === "expired" ? `Nobody answered within ${minutes} minutes, so this was not allowed. Go on without it, or stop and say what you need.` : "The request was withdrawn, so this was not allowed." } };
118
+ }
119
+ var ClaudeSession = class {
120
+ constructor(child, hooks) {
121
+ this.child = child;
122
+ this.hooks = hooks;
123
+ child.stdout?.on("data", (c) => {
124
+ hooks.raw?.(c);
125
+ this.feed(c.toString("utf8"));
126
+ });
127
+ child.on("exit", () => {
128
+ this.ended = true;
129
+ for (const c of this.pending.values()) c.abort();
130
+ this.pending.clear();
131
+ });
132
+ child.stdin?.on("error", () => {
133
+ this.ended = true;
134
+ });
135
+ }
136
+ sessionId = "";
137
+ busy = true;
138
+ buf = "";
139
+ n = 0;
140
+ pending = /* @__PURE__ */ new Map();
141
+ ended = false;
142
+ lastSaid = "";
143
+ write(o) {
144
+ if (this.ended || !this.child.stdin || this.child.stdin.destroyed) return false;
145
+ try {
146
+ this.child.stdin.write(`${JSON.stringify(o)}
147
+ `);
148
+ return true;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ /** The first message: the command's prompt. */
154
+ begin(prompt) {
155
+ this.write({ type: "control_request", request_id: `imd-init-${++this.n}`, request: { subtype: "initialize", hooks: null } });
156
+ this.say(prompt);
157
+ }
158
+ /** A user message: the task, or a person's words. */
159
+ say(text) {
160
+ this.busy = true;
161
+ return this.write({ type: "user", message: { role: "user", content: text }, parent_tool_use_id: null, session_id: this.sessionId });
162
+ }
163
+ interrupt() {
164
+ return this.write({ type: "control_request", request_id: `imd-int-${++this.n}`, request: { subtype: "interrupt" } });
165
+ }
166
+ /** No more messages: it exits once its task ends. */
167
+ end() {
168
+ try {
169
+ this.child.stdin?.end();
170
+ } catch {
171
+ }
172
+ }
173
+ feed(s) {
174
+ this.buf += s;
175
+ let i;
176
+ while ((i = this.buf.indexOf("\n")) >= 0) {
177
+ const line = this.buf.slice(0, i).trim();
178
+ this.buf = this.buf.slice(i + 1);
179
+ if (!line) continue;
180
+ let m;
181
+ try {
182
+ m = JSON.parse(line);
183
+ } catch {
184
+ continue;
185
+ }
186
+ this.on(m);
187
+ }
188
+ if (this.buf.length > 4e6) this.buf = "";
189
+ }
190
+ on(m) {
191
+ if (m.type === "system" && m.subtype === "init" && typeof m.session_id === "string") this.sessionId = m.session_id;
192
+ else if (m.type === "assistant" && Array.isArray(m.message?.content)) {
193
+ if (m.parent_tool_use_id) return;
194
+ for (const b of m.message.content) {
195
+ if (b?.type === "text" && typeof b.text === "string" && b.text.trim()) {
196
+ this.lastSaid = b.text.trim();
197
+ this.hooks.line({ type: "said", text: cut(maskText(b.text.trim().replace(/\s+/g, " ")), 480) });
198
+ } else if (b?.type === "tool_use" && b.name !== "AskUserQuestion") this.hooks.line({ type: "ran", text: toolLine(String(b.name), b.input) });
199
+ }
200
+ } else if (m.type === "result") {
201
+ this.busy = false;
202
+ const err = m.is_error === true || typeof m.subtype === "string" && m.subtype !== "success";
203
+ const said = !err && typeof m.result === "string" && m.result.trim() === this.lastSaid;
204
+ this.lastSaid = "";
205
+ this.hooks.line({ type: err ? "error" : "done", text: said ? "Finished" : cut(maskText(String(err ? m.result || m.subtype || "it stopped" : m.result || "Finished").replace(/\s+/g, " ")), 480) });
206
+ this.hooks.idle();
207
+ } else if (m.type === "control_request" && m.request?.subtype === "can_use_tool" && typeof m.request_id === "string") {
208
+ const id = m.request_id, ctl = new AbortController();
209
+ this.pending.set(id, ctl);
210
+ void this.hooks.decide({ ...m.request, request_id: id }, ctl.signal).catch(() => ({ response: { behavior: "deny", message: "It couldn't be asked of a person through instruction.md, so it was not allowed." } })).then((r) => {
211
+ if (!this.pending.delete(id) || ctl.signal.aborted) return;
212
+ this.write({ type: "control_response", response: { subtype: "success", request_id: id, response: r.response } });
213
+ if (r.note) this.say(r.note);
214
+ });
215
+ } else if (m.type === "control_cancel_request" && typeof m.request_id === "string") {
216
+ this.pending.get(m.request_id)?.abort();
217
+ this.pending.delete(m.request_id);
218
+ }
219
+ }
220
+ };
221
+ export {
222
+ ClaudeSession,
223
+ cardOf,
224
+ converseArgv,
225
+ maskText,
226
+ masked,
227
+ responseOf,
228
+ toolLine
229
+ };