@mnaimfaizy/agent-kit 1.0.0-beta.1 → 1.0.0-beta.11

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,215 @@
1
+ // The Deep scan's model credential (#370): where it is read from, and the
2
+ // checks it passes before anything starts. It is an Anthropic API key (the
3
+ // default, `--credential api-key`) or, opted into with `--credential
4
+ // subscription` (#375), a Claude subscription token from `claude
5
+ // setup-token`. It is read from an environment variable (ANTHROPIC_API_KEY,
6
+ // or CLAUDE_CODE_OAUTH_TOKEN for a subscription token, by default; `op run`
7
+ // can fill either) or from 1Password with `op read`, never from the command
8
+ // line, where other processes could see it. Once read, it lives only in the
9
+ // launcher's memory, for the model proxy: every command the launcher runs
10
+ // gets an environment with the model credential variables removed, and the
11
+ // sandbox gets only a placeholder.
12
+
13
+ import { firstLine } from "../exec.mjs";
14
+ import { GITHUB_TOKEN_VARS } from "./preflight.mjs";
15
+
16
+ /** The default variable the API key is read from. */
17
+ export const API_KEY_VAR = "ANTHROPIC_API_KEY";
18
+
19
+ /** The non-secret key the sandboxed Claude Code holds; the proxy swaps it. */
20
+ export const PLACEHOLDER_API_KEY = "agent-kit-deep-scan-placeholder";
21
+
22
+ /**
23
+ * The non-secret subscription token the sandboxed Claude Code holds on the
24
+ * subscription path; the proxy swaps the bearer value it sends. It is shaped
25
+ * like a token, in case Claude Code checks the prefix.
26
+ */
27
+ export const PLACEHOLDER_OAUTH_TOKEN = "sk-ant-oat01-agent-kit-deep-scan-placeholder";
28
+
29
+ /** The kinds `--credential` takes: an API key (the default) or the opt-in. */
30
+ export const API_KEY = "api-key";
31
+ export const SUBSCRIPTION = "subscription";
32
+ const CREDENTIAL_KINDS = Object.freeze([API_KEY, SUBSCRIPTION]);
33
+
34
+ /** Model credential variables, removed from every command the launcher runs. */
35
+ export const CREDENTIAL_VARS = Object.freeze([
36
+ "ANTHROPIC_API_KEY",
37
+ "ANTHROPIC_AUTH_TOKEN",
38
+ "CLAUDE_CODE_OAUTH_TOKEN",
39
+ ]);
40
+
41
+ /** The variable Claude Code reads a subscription (OAuth) token from. */
42
+ const OAUTH_TOKEN_VAR = "CLAUDE_CODE_OAUTH_TOKEN";
43
+ /** How a Claude subscription (OAuth) token starts; an API key starts sk-ant-api. */
44
+ const OAUTH_TOKEN_PREFIX = "sk-ant-oat";
45
+
46
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
47
+ const OP_REF = /^op:\/\/[^/\s][^\r\n]*$/;
48
+ const USAGE =
49
+ "--credential-from takes env:<NAME> or an op:// reference (for example op://Private/Anthropic/credential), never the key itself: a command line is visible to other processes.";
50
+
51
+ /**
52
+ * The credential kind, from `--credential` (undefined: an API key). The
53
+ * value is never echoed: it may be a key passed by mistake.
54
+ * @param {string | undefined} value
55
+ * @returns {{ kind: "api-key" | "subscription" } | { error: string }}
56
+ */
57
+ export function credentialKind(value) {
58
+ if (value === undefined) return { kind: API_KEY };
59
+ if (value === API_KEY || value === SUBSCRIPTION) return { kind: value };
60
+ return {
61
+ error: `--credential takes ${CREDENTIAL_KINDS[0]} (the default) or ${CREDENTIAL_KINDS[1]} (a Claude subscription token, opted into at your own risk).`,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Where the credential comes from, from `--credential-from` (undefined: the
67
+ * default variable for `kind`). The value is never echoed: it may be the
68
+ * key itself.
69
+ * @param {string | undefined} value
70
+ * @param {"api-key" | "subscription"} [kind]
71
+ * @returns {{ kind: "env", name: string } | { kind: "op", ref: string } | { error: string }}
72
+ */
73
+ export function credentialSource(value, kind = API_KEY) {
74
+ if (value === undefined) {
75
+ return { kind: "env", name: kind === SUBSCRIPTION ? OAUTH_TOKEN_VAR : API_KEY_VAR };
76
+ }
77
+ if (value.startsWith("env:")) {
78
+ const name = value.slice(4);
79
+ if (!ENV_NAME.test(name)) return { error: USAGE };
80
+ if (GITHUB_TOKEN_VARS.includes(name.toUpperCase())) {
81
+ return {
82
+ error: `--credential-from: ${name} is a GitHub token variable, and a GitHub token is never the model credential.`,
83
+ };
84
+ }
85
+ return { kind: "env", name };
86
+ }
87
+ if (OP_REF.test(value)) return { kind: "op", ref: value };
88
+ return { error: USAGE };
89
+ }
90
+
91
+ /**
92
+ * Read the credential of `kind`. Returns it with a description of where it
93
+ * came from (never the value), or refusal lines that never hold it.
94
+ * @param {{
95
+ * source: { kind: "env", name: string } | { kind: "op", ref: string },
96
+ * env: Record<string, string | undefined>,
97
+ * runner: import("../exec.mjs").Runner,
98
+ * kind?: "api-key" | "subscription",
99
+ * }} opts
100
+ * @returns {{ credential: string, from: string } | { refused: string[] }}
101
+ */
102
+ export function readCredential({ source, env, runner, kind = API_KEY }) {
103
+ const token = kind === SUBSCRIPTION;
104
+ if (source.kind === "op") {
105
+ const r = runner("op", ["read", "--no-newline", source.ref]);
106
+ if (r.status !== 0) {
107
+ return {
108
+ refused: [
109
+ `Could not read the model credential with op read: ${firstLine(r.stderr) || `exit ${r.status}`}`,
110
+ "Sign in to the 1Password CLI (op signin, or unlock the desktop app's integration) and check the reference, then run deep-scan again.",
111
+ ],
112
+ };
113
+ }
114
+ return checked(
115
+ r.stdout.replace(/\r?\n$/, ""),
116
+ "the op read result",
117
+ "1Password (op read)",
118
+ kind,
119
+ );
120
+ }
121
+ const { name } = source;
122
+ if (!token && name.toUpperCase() === OAUTH_TOKEN_VAR) return notAnApiKey(name);
123
+ const command = `npx @mnaimfaizy/agent-kit deep-scan${token ? " --credential subscription" : ""}`;
124
+ const value = valueOf(env, name);
125
+ if (!value) {
126
+ return {
127
+ refused: token
128
+ ? [
129
+ `No model credential: ${name} is not set. deep-scan --credential subscription needs a Claude subscription token, which stays outside the sandbox, in its model proxy.`,
130
+ `Make one with claude setup-token, keep it in 1Password, and read it from there: --credential-from op://<vault>/<item>/<field>, or op run -- ${command} with ${name} set to an op:// reference.`,
131
+ ]
132
+ : [
133
+ `No model credential: ${name} is not set. deep-scan needs an Anthropic API key, which stays outside the sandbox, in its model proxy.`,
134
+ `Set ${name} for this run, or read it from 1Password: --credential-from op://<vault>/<item>/<field>, or op run -- ${command} with ${name} set to an op:// reference.`,
135
+ ],
136
+ };
137
+ }
138
+ if (value.startsWith("op://")) {
139
+ return {
140
+ refused: [
141
+ `${name} holds a 1Password reference, not a ${token ? "token" : "key"}: run deep-scan under op run, which resolves it, for example:`,
142
+ ` op run -- ${command}`,
143
+ "or pass the reference with --credential-from instead.",
144
+ ],
145
+ };
146
+ }
147
+ return checked(value, name, name, kind);
148
+ }
149
+
150
+ /** The variable's value, by name in any letter case (as Windows matches it). */
151
+ function valueOf(env, name) {
152
+ if (env[name] !== undefined) return env[name];
153
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
154
+ return key === undefined ? undefined : env[key];
155
+ }
156
+
157
+ function checked(value, what, from, kind) {
158
+ if (!value) return { refused: [`No model credential: ${what} is empty.`] };
159
+ // The credential goes into an HTTP header: printable ASCII with no space only.
160
+ if (!/^[\x21-\x7e]+$/.test(value)) {
161
+ return {
162
+ refused: [
163
+ `${what} holds whitespace or a control character, so it is not a model credential (its value is not shown).`,
164
+ ],
165
+ };
166
+ }
167
+ const isToken = value.startsWith(OAUTH_TOKEN_PREFIX);
168
+ if (kind !== SUBSCRIPTION && isToken) return notAnApiKey(what);
169
+ if (kind === SUBSCRIPTION && !isToken) {
170
+ return {
171
+ refused: [
172
+ `${what} does not hold a Claude subscription token (one starts sk-ant-oat; its value is not shown). --credential subscription takes the token claude setup-token prints.`,
173
+ "For an Anthropic API key, leave out --credential subscription: the API-key path is the default, and the supported one.",
174
+ ],
175
+ };
176
+ }
177
+ return { credential: value, from };
178
+ }
179
+
180
+ // Without the opt-in, the model proxy sends the credential as x-api-key,
181
+ // which a subscription token is not: the model API would answer 401 once
182
+ // the sandbox is built.
183
+ function notAnApiKey(what) {
184
+ return {
185
+ refused: [
186
+ `${what} holds a Claude subscription token, not an API key (its value is not shown). deep-scan runs on an API key unless you opt into the subscription path with --credential subscription, at your own risk: it relies on undocumented behaviour (see the caveats in the docs).`,
187
+ "Or make an API key in a dedicated Anthropic Console workspace with its own spend limit, and pass that instead.",
188
+ ],
189
+ };
190
+ }
191
+
192
+ /**
193
+ * `runner`, with the model credential variables (and `extra`) removed from
194
+ * every command's environment, so no runtime CLI, and nothing it starts,
195
+ * inherits the key.
196
+ * @param {import("../exec.mjs").Runner} runner
197
+ * @param {Record<string, string | undefined>[]} envs the environments the
198
+ * variables could come from (the launcher's and the process's)
199
+ * @param {string[]} [extra]
200
+ * @returns {import("../exec.mjs").Runner}
201
+ */
202
+ export function withoutCredentials(runner, envs, extra = []) {
203
+ const names = new Set([...CREDENTIAL_VARS, ...extra]);
204
+ for (const env of envs) {
205
+ for (const key of Object.keys(env)) {
206
+ if ([...names].some((n) => n.toUpperCase() === key.toUpperCase())) names.add(key);
207
+ }
208
+ }
209
+ const scrub = Object.fromEntries([...names].map((n) => [n, undefined]));
210
+ const wrapped = (cmd, args, opts = {}) =>
211
+ runner(cmd, args, { ...opts, env: { ...opts.env, ...scrub } });
212
+ wrapped.start = (cmd, args, opts = {}) =>
213
+ runner.start(cmd, args, { ...opts, env: { ...opts.env, ...scrub } });
214
+ return wrapped;
215
+ }