kryptheon 0.1.71 → 0.1.73

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/bin/kryptheon.js CHANGED
@@ -2935,7 +2935,15 @@ async function apiRecheckCommand(target, opened) {
2935
2935
  console.log(' Reading ' + origin + ' again, read-only - nothing is added to your app...');
2936
2936
  const run = await api.runLive(USER_DIR, { origin, packageDir: PACKAGE_DIR, say: () => {} });
2937
2937
  if (!run.ran) attempt.why = run.why;
2938
- else {
2938
+ else if (api.answerKindOf(target.headline)) {
2939
+ // a key or a quiz's answers in what the app sends: that page read again, and looked through again
2940
+ const kind = api.answerKindOf(target.headline);
2941
+ const still = run.findings.find((f) => f.where === target.where && f.kind === kind);
2942
+ const read = run.answers && run.answers.ran && run.answers.tried.some((x) => x.what === target.where && x.status === 200);
2943
+ if (still) { attempt.verdict = 'still open'; attempt.why = 'it is still sent: ' + still.headline; }
2944
+ else if (read) attempt.verdict = 'fixed';
2945
+ else attempt.why = 'that page could not be read again (it did not answer 200)';
2946
+ } else {
2939
2947
  const still = run.findings.find((f) => f.where === target.where && f.kind === (String(target.headline).match(/another organization/i) ? 'tenant' : f.kind) && f.status === 'confirmed');
2940
2948
  const tried = run.wall && run.wall.ran && run.wall.result.attempts.some((a) => a.method + ' ' + a.template === target.where && !a.notTried);
2941
2949
  if (still) { attempt.verdict = 'still open'; attempt.why = 'it still answered: ' + still.headline; }
@@ -3463,6 +3471,23 @@ function openInBrowser(url) {
3463
3471
  }
3464
3472
  }
3465
3473
 
3474
+ /**
3475
+ * The dashboard's page, opened in the browser. Started at sign-in by Start with
3476
+ * Windows (KRYPTHEON_OPEN_DAILY), only at the first sign-in of the day; every
3477
+ * other start opens it as before.
3478
+ */
3479
+ function openDashboardPage(address) {
3480
+ if (process.env.KRYPTHEON_OPEN_DAILY && !process.env.KRYPTHEON_NO_OPEN) {
3481
+ try {
3482
+ const dir = require(path.join(PACKAGE_DIR, 'kryptheon-store.js')).pathsFor(USER_DIR).dir;
3483
+ if (!require(path.join(PACKAGE_DIR, 'kryptheon-autostart.js')).firstOpenToday(dir)) return false;
3484
+ } catch (err) {
3485
+ /* opened as any other start */
3486
+ }
3487
+ }
3488
+ return openInBrowser(address);
3489
+ }
3490
+
3466
3491
  /**
3467
3492
  * The person's own folder picker, on this computer: the one Windows or the
3468
3493
  * Mac shows everywhere else. Resolves to the folder, or null when it was
@@ -3802,7 +3827,7 @@ async function dashboardCommand() {
3802
3827
  }
3803
3828
  if (running && running.version === mine) {
3804
3829
  const address = 'http://127.0.0.1:' + DASHBOARD_PORT + '/';
3805
- const shown = openInBrowser(address);
3830
+ const shown = openDashboardPage(address);
3806
3831
  console.log('');
3807
3832
  console.log(' The Kryptheon dashboard for ' + path.basename(USER_DIR) + ' is already running:');
3808
3833
  console.log('');
@@ -3814,6 +3839,8 @@ async function dashboardCommand() {
3814
3839
  }
3815
3840
  const opened = openStore();
3816
3841
  if (!opened) return 1;
3842
+ // A Start with Windows file from an older version, which never opened the page, gets today's text.
3843
+ try { require(path.join(PACKAGE_DIR, 'kryptheon-autostart.js')).refresh(USER_DIR); } catch (err) { /* left as it was */ }
3817
3844
  const dash = require(path.join(PACKAGE_DIR, 'kryptheon-dashboard.js'));
3818
3845
  const app = dash.createServer(USER_DIR, {
3819
3846
  run: (id, say) => runFromDashboard(id, opened, say),
@@ -3836,7 +3863,7 @@ async function dashboardCommand() {
3836
3863
  port = await app.listen(0);
3837
3864
  }
3838
3865
  const address = 'http://127.0.0.1:' + port + '/';
3839
- const shown = openInBrowser(address);
3866
+ const shown = openDashboardPage(address);
3840
3867
  console.log('');
3841
3868
  console.log(' Kryptheon dashboard for ' + path.basename(USER_DIR) + ':');
3842
3869
  console.log('');
@@ -116,7 +116,9 @@ async function refresh(root, env) {
116
116
  return { ok: true, account: summary(read(root, env)) };
117
117
  }
118
118
  if (r.status !== 200) return { ok: false, why: (r.body && r.body.error) || 'kryptheon.tech did not answer', account: summary(a) };
119
- return { ok: true, account: summary(keep(root, env, a.code, r.body, a.unlocked)) };
119
+ const kept = keep(root, env, a.code, r.body, a.unlocked);
120
+ if (a.setupReported) write(root, env, Object.assign({}, kept, { setupReported: a.setupReported }));
121
+ return { ok: true, account: summary(read(root, env)) };
120
122
  }
121
123
 
122
124
  /** Opens one finding's fix prompt: free on Pro and Studio; on Starter, one of the five this month. */
@@ -141,6 +143,23 @@ async function unlock(root, env, findingId) {
141
143
  return { ok: true, account: summary(read(root, env)) };
142
144
  }
143
145
 
146
+ /**
147
+ * The set-up is finished - the guide on this dashboard reached its end. Said to kryptheon.tech once, so the account
148
+ * page there opens instead of the first-time journey. Kept as said only when kryptheon.tech answers that it recorded
149
+ * it (setupRecorded); an older kryptheon.tech that does not know the word is asked again next time.
150
+ */
151
+ async function setupDone(root, env) {
152
+ const a = read(root, env);
153
+ if (!a || !a.code) return { ok: false, status: 409, why: 'connect your Kryptheon account first' };
154
+ if (a.setupReported) return { ok: true, already: true, account: summary(a) };
155
+ const r = await ask(env, a.code, { setupDone: true });
156
+ if (r.status === 0) return { ok: false, status: 503, why: r.why };
157
+ if (r.status !== 200) return { ok: false, status: r.status, why: (r.body && r.body.error) || 'kryptheon.tech did not answer' };
158
+ if (!r.body.setupRecorded) return { ok: true, recorded: false, account: summary(a) };
159
+ write(root, env, Object.assign({}, a, { setupReported: new Date().toISOString() }));
160
+ return { ok: true, recorded: true, account: summary(read(root, env)) };
161
+ }
162
+
144
163
  function disconnect(root, env) {
145
164
  forget(root, env);
146
165
  return { ok: true, account: summary(null) };
@@ -153,7 +172,7 @@ function summary(a) {
153
172
  }
154
173
  return {
155
174
  connected: true, app: a.app, plan: a.plan, clientReport: !!a.clientReport, prompts: a.prompts, month: a.month,
156
- checkedAt: a.checkedAt, accountPage: ACCOUNT_PAGE, pricing: PRICING,
175
+ checkedAt: a.checkedAt, accountPage: ACCOUNT_PAGE, pricing: PRICING, setupReported: !!a.setupReported,
157
176
  };
158
177
  }
159
178
 
@@ -180,4 +199,4 @@ function lock(state, root, env) {
180
199
  return out;
181
200
  }
182
201
 
183
- module.exports = { connect, refresh, unlock, disconnect, lock, summary, fingerprintOf, read, ENTITLEMENT, CODE };
202
+ module.exports = { connect, refresh, unlock, setupDone, disconnect, lock, summary, fingerprintOf, read, ENTITLEMENT, CODE };
@@ -0,0 +1,416 @@
1
+ 'use strict';
2
+ // Apps built around an AI: a chat, an "add your API key and it answers your email" assistant, a study app with quizzes.
3
+ // Read from the code (no request is ever sent to an AI route - each one costs the owner money, and some send real
4
+ // email): which routes ask an AI provider, whether anyone at all may call them, whether one account may call them
5
+ // without end, and whether what the AI wrote is sent or fetched with no person approving it first.
6
+ // Read from the running app's answers (GET only): an AI provider's key, or a stored token, sent to the browser; and
7
+ // a quiz's answers sent along with its questions.
8
+ // Nothing here is an AI: these are fixed rules over the code and over the answers.
9
+
10
+ // The packages an app talks to an AI provider through.
11
+ const AI_PKG = /^(openai|@anthropic-ai\/sdk|@google\/generative-ai|@google\/genai|@google-cloud\/vertexai|ai|@ai-sdk\/[\w-]+|groq-sdk|@mistralai\/mistralai|cohere-ai|replicate|together-ai|@huggingface\/inference|ollama|@langchain\/[\w-]+|langchain(\/.*)?|@openrouter\/[\w-]+|@fal-ai\/[\w-]+|@aws-sdk\/client-bedrock-runtime)$/;
12
+ // ... and their addresses, for an app that calls them with fetch.
13
+ const AI_HOST = /\b(api\.openai\.com|api\.anthropic\.com|generativelanguage\.googleapis\.com|aiplatform\.googleapis\.com|openrouter\.ai\/api|api\.groq\.com|api\.mistral\.ai|api\.cohere\.(ai|com)|api\.together\.xyz|api\.deepseek\.com|api\.perplexity\.ai|api\.replicate\.com|api-inference\.huggingface\.co|api\.x\.ai|api\.fireworks\.ai)\b/;
14
+ // A method of a provider's client that asks the model for an answer (not one that lists models or counts tokens).
15
+ const CLIENT_METHOD = /^(create|stream|generateContent|generateContentStream|sendMessage|sendMessageStream|invoke|ainvoke|batch|run|chat|chatStream|complete|completion|generate|embedContent|parse|textGeneration|chatCompletion)$/;
16
+ // A function of the AI SDKs that asks the model: generateText({ model, prompt }).
17
+ const SDK_FN = /^(generate|stream)(Text|Object)$|^embed(Many)?$/;
18
+ // Strong enough on its own when the file imports an AI package: openai.chat.completions.create(...)
19
+ const STRONG = /(^|\.)chat\.completions\.(create|stream)$|(^|\.)responses\.create$|(^|\.)generateContent(Stream)?$/;
20
+ // Packages that send email, messages or posts in the app owner's name.
21
+ const SEND_PKG = /^(nodemailer|resend|@sendgrid\/mail|postmark|mailgun\.js|mailgun-js|@mailchimp\/mailchimp_transactional|twilio|@slack\/web-api|@slack\/bolt|googleapis|@googleapis\/gmail|@microsoft\/microsoft-graph-client|discord\.js|telegraf|node-telegram-bot-api)$/;
22
+ const SEND_CALL = /(^|\.)(sendMail|sendEmail|send_email|sendSms|sendSMS|sendWhatsapp|sendWhatsApp)$|(^|\.)emails\.send$|(^|\.)messages\.(send|create)$|(^|\.)chat\.postMessage$|(^|\.)drafts\.send$|(^|\.)users\.messages\.send$|(^|\.)sendMessage$/;
23
+ // A person's yes in front of the action: an approval, a review, a confirm step.
24
+ const APPROVAL = /approv|\breview|confirm|human[_-]?in[_-]?the[_-]?loop|awaiting[_-]?(user|owner)/i;
25
+ // A limit on how often one caller may ask.
26
+ const LIMIT = /rate[-_ ]?limit|ratelimit|limiter|throttl|slowDown|\bquota|\bcredits?\b|usage[_-]?(count|limit)|daily[_-]?limit|max[_-]?requests|tokens[_-]?used/i;
27
+ const LIMIT_PKG = /^(express-rate-limit|rate-limiter-flexible|@upstash\/ratelimit|express-slow-down|@nestjs\/throttler|koa-ratelimit|hono-rate-limiter|limiter|bottleneck)$/;
28
+
29
+ const unwrap = (n) => {
30
+ while (n && /^(AwaitExpression|TSAsExpression|TSNonNullExpression|ParenthesizedExpression|TSSatisfiesExpression)$/.test(n.type)) n = n.argument || n.expression;
31
+ return n;
32
+ };
33
+
34
+ /** The AI package a module imports or requires, if any. */
35
+ function anyAiImport(mod) {
36
+ for (const i of mod.imports.values()) if (AI_PKG.test(i.source)) return i.source;
37
+ const m = /require\(\s*['"]([^'"]+)['"]\s*\)/g;
38
+ let x;
39
+ while ((x = m.exec(mod.source))) if (AI_PKG.test(x[1])) return x[1];
40
+ return null;
41
+ }
42
+
43
+ // a file of the app's own: ./x, ../x, @/x, ~/x, #x - not a package
44
+ const ownFile = (spec) => /^\.{1,2}\//.test(spec) || /^[@~]\//.test(spec) || /^#/.test(spec) || spec.startsWith('/');
45
+
46
+ function importSource(mod, name) {
47
+ const imp = mod.imports.get(name);
48
+ if (imp) return imp.source;
49
+ return null;
50
+ }
51
+
52
+ /**
53
+ * The AI package a name in this scope comes from: imported from it, made from its client (new OpenAI()), or made in
54
+ * another file of the app that does (import { openai } from '@/lib/openai'). null when it is not one.
55
+ */
56
+ function rootSource(ctx, H, mod, scope, name, depth) {
57
+ if (depth > 4 || !scope) return null;
58
+ const b = scope.getBinding(name);
59
+ if (!b) return null;
60
+ const bp = b.path;
61
+ if (bp.isImportSpecifier() || bp.isImportDefaultSpecifier() || bp.isImportNamespaceSpecifier()) {
62
+ const imp = mod.imports.get(name);
63
+ if (!imp) return null;
64
+ if (AI_PKG.test(imp.source)) return imp.source;
65
+ // another package (express, pg) is not an AI one; a file of the app's own may make the client
66
+ return ownFile(imp.source) ? fromOtherFile(ctx, H, mod, imp.source, imp.imported, depth) : null;
67
+ }
68
+ if (bp.isVariableDeclarator()) {
69
+ const init = unwrap(bp.node.init);
70
+ if (!init) return null;
71
+ const req = H.requireOf(ctx.t, init) || (init.type === 'MemberExpression' && H.requireOf(ctx.t, init.object));
72
+ if (req) {
73
+ if (AI_PKG.test(req)) return req;
74
+ return ownFile(req) ? fromOtherFile(ctx, H, mod, req, 'default', depth) : null;
75
+ }
76
+ if ((init.type === 'NewExpression' || init.type === 'CallExpression') && init.callee) {
77
+ const c = H.memberChain(init.callee);
78
+ if (c && c.length) return rootSource(ctx, H, mod, bp.scope, c[0], depth + 1);
79
+ }
80
+ if (init.type === 'Identifier') return rootSource(ctx, H, mod, bp.scope, init.name, depth + 1);
81
+ if (init.type === 'MemberExpression') {
82
+ const c = H.memberChain(init);
83
+ if (c && c.length) return rootSource(ctx, H, mod, bp.scope, c[0], depth + 1);
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ /** A file of the app's own that an import names, loaded - @/lib/x and ~/lib/x as a Next.js app names them too. */
90
+ function loadOwn(ctx, mod, spec) {
91
+ let abs = null;
92
+ try {
93
+ abs = ctx.resolveModule(mod.abs, spec);
94
+ if (!abs && /^[@~]\//.test(spec) && ctx.root) {
95
+ const anchor = require('path').join(ctx.root, 'kryptheon-anchor.js');
96
+ abs = ctx.resolveModule(anchor, './' + spec.slice(2)) || ctx.resolveModule(anchor, './src/' + spec.slice(2)) || null;
97
+ }
98
+ } catch (e) { abs = null; }
99
+ return abs ? ctx.load(abs) : null;
100
+ }
101
+
102
+ /** The function an import of the app's own names, when the map's own following could not reach it (an @/ path). */
103
+ function ownFunction(ctx, mod, name) {
104
+ const imp = mod.imports.get(name);
105
+ if (!imp || !ownFile(imp.source)) return null;
106
+ const other = loadOwn(ctx, mod, imp.source);
107
+ if (!other || !other.program) return null;
108
+ let e = imp.imported === 'default' ? other.exportDefault : other.exportsNamed.get(imp.imported);
109
+ if (e && e.local) { const b = other.program.scope.getBinding(e.local); e = b ? b.path : null; }
110
+ if (e && e.node && e.node.type === 'Identifier') { const b = other.program.scope.getBinding(e.node.name); e = b ? b.path : null; }
111
+ if (e && e.isVariableDeclarator && e.isVariableDeclarator()) e = e.get('init');
112
+ if (e && e.node && /Function/.test(e.node.type)) return { kind: 'fn', path: e, mod: other };
113
+ return null;
114
+ }
115
+
116
+ function fromOtherFile(ctx, H, mod, spec, imported, depth) {
117
+ const other = loadOwn(ctx, mod, spec);
118
+ if (!other || !other.program) return null;
119
+ const e = imported === 'default' || imported === '*' ? other.exportDefault || other.cjsExports : other.exportsNamed.get(imported);
120
+ if (e && e.node) {
121
+ const n = unwrap(e.node.type === 'VariableDeclarator' ? e.node.init : e.node);
122
+ if (n && n.type === 'Identifier') return rootSource(ctx, H, other, other.program.scope, n.name, depth + 1);
123
+ if (n && (n.type === 'NewExpression' || n.type === 'CallExpression')) {
124
+ const c = H.memberChain(n.callee);
125
+ if (c && c.length) {
126
+ const s = rootSource(ctx, H, other, other.program.scope, c[0], depth + 1);
127
+ if (s) return s;
128
+ }
129
+ }
130
+ } else if (e && e.local) {
131
+ return rootSource(ctx, H, other, other.program.scope, e.local, depth + 1);
132
+ }
133
+ // module.exports = { openai } or a function that makes the client: the file is about an AI provider
134
+ return anyAiImport(other);
135
+ }
136
+
137
+ /** A string an argument is, when it can be read here: a literal, a template, or a constant holding one. */
138
+ function textOf(node, scope, depth) {
139
+ node = unwrap(node);
140
+ if (!node || depth > 3) return '';
141
+ if (node.type === 'StringLiteral') return node.value;
142
+ if (node.type === 'TemplateLiteral') return node.quasis.map((q) => q.value.cooked || '').join('{}');
143
+ if (node.type === 'BinaryExpression' && node.operator === '+') return textOf(node.left, scope, depth + 1) + textOf(node.right, scope, depth + 1);
144
+ if (node.type === 'Identifier' && scope) {
145
+ const b = scope.getBinding(node.name);
146
+ if (b && b.path.isVariableDeclarator()) return textOf(b.path.node.init, b.path.scope, depth + 1);
147
+ }
148
+ if (node.type === 'NewExpression' && node.callee.type === 'Identifier' && node.callee.name === 'URL') return textOf(node.arguments[0], scope, depth + 1);
149
+ return '';
150
+ }
151
+
152
+ const FETCHERS = /^(fetch|axios|got|ky|request|ofetch|\$fetch|undiciRequest)$/;
153
+
154
+ /** The provider an AI call reaches, or null. */
155
+ function aiCallOf(ctx, H, mod, p) {
156
+ const chain = H.memberChain(p.node.callee);
157
+ if (!chain || !chain.length) return null;
158
+ const root = chain[0];
159
+ const last = chain[chain.length - 1];
160
+ if ((chain.length === 1 && FETCHERS.test(root)) || (chain.length === 2 && FETCHERS.test(root) && /^(get|post|put|request|create)$/.test(last))) {
161
+ const url = textOf(p.node.arguments[0], p.scope, 0);
162
+ const m = AI_HOST.exec(url);
163
+ return m ? m[1] : null;
164
+ }
165
+ const src = rootSource(ctx, H, mod, p.scope, root, 0);
166
+ if (src) {
167
+ if (chain.length === 1) return SDK_FN.test(root) ? src : null;
168
+ return CLIENT_METHOD.test(last) && !/^(countTokens|list|retrieve|del|delete)$/.test(last) ? src : null;
169
+ }
170
+ if (chain.length > 1 && STRONG.test(chain.join('.'))) return anyAiImport(mod);
171
+ return null;
172
+ }
173
+
174
+ function sendOf(ctx, H, mod, p) {
175
+ const chain = H.memberChain(p.node.callee);
176
+ if (!chain || !chain.length) return null;
177
+ const joined = chain.join('.');
178
+ const src = importSource(mod, chain[0]) || (() => {
179
+ const b = p.scope.getBinding(chain[0]);
180
+ const init = b && b.path.isVariableDeclarator() ? unwrap(b.path.node.init) : null;
181
+ const req = init && H.requireOf(ctx.t, init);
182
+ if (req) return req;
183
+ if (init && (init.type === 'CallExpression' || init.type === 'NewExpression')) {
184
+ const c = H.memberChain(init.callee);
185
+ if (c && c.length) {
186
+ const cb = p.scope.getBinding(c[0]);
187
+ const ci = cb && cb.path.isVariableDeclarator() ? unwrap(cb.path.node.init) : null;
188
+ return importSource(mod, c[0]) || (ci && H.requireOf(ctx.t, ci)) || null;
189
+ }
190
+ }
191
+ return null;
192
+ })();
193
+ const fromSender = src && SEND_PKG.test(src) && /^(send|sendMail|create|postMessage|sendMessage)$/.test(chain[chain.length - 1]);
194
+ if (!SEND_CALL.test(joined) && !fromSender) return null;
195
+ return /mail|email|resend|sendgrid|postmark|mailgun|gmail|drafts/i.test(joined + ' ' + (src || '')) ? 'sends an email' : 'sends a message';
196
+ }
197
+
198
+ const mentions = (t, node, names) => {
199
+ if (!node || !names.size) return false;
200
+ let hit = false;
201
+ t.traverseFast(node, (x) => { if (!hit && x.type === 'Identifier' && names.has(x.name)) hit = true; });
202
+ return hit;
203
+ };
204
+
205
+ /** Names a pattern declares: const { text } = ..., const [a] = ..., const reply = ... */
206
+ function namesOf(id, out) {
207
+ if (!id) return out;
208
+ if (id.type === 'Identifier') out.add(id.name);
209
+ else if (id.type === 'ObjectPattern') for (const pr of id.properties) namesOf(pr.type === 'RestElement' ? pr.argument : pr.value, out);
210
+ else if (id.type === 'ArrayPattern') for (const el of id.elements) namesOf(el, out);
211
+ else if (id.type === 'AssignmentPattern') namesOf(id.left, out);
212
+ return out;
213
+ }
214
+
215
+ /**
216
+ * One route's handler, read for AI: { calls: [{provider, file, line, code}], acts: [{what, file, line, code, tool}],
217
+ * limited: {file, line, code} | null, approval: bool }. Helpers of the app's own are followed two levels down.
218
+ */
219
+ function readHandler(ctx, H, fnRef, depth, seen) {
220
+ depth = depth || 0;
221
+ seen = seen || new Set();
222
+ const out = { calls: [], acts: [], limited: null, approval: false };
223
+ if (!fnRef || !fnRef.path || !fnRef.path.node || depth > 2) return out;
224
+ const t = ctx.t;
225
+ const mod = fnRef.mod;
226
+ const key = mod.abs + ':' + fnRef.path.node.start;
227
+ if (seen.has(key)) return out;
228
+ seen.add(key);
229
+ const text = mod.source.slice(fnRef.path.node.start, fnRef.path.node.end);
230
+ if (APPROVAL.test(text)) out.approval = true;
231
+ const at = (n) => ({ file: mod.rel, line: n.loc.start.line, code: H.snippet(mod, n.loc.start.line) });
232
+ if (LIMIT.test(text)) {
233
+ const i = text.search(LIMIT);
234
+ const line = fnRef.path.node.loc.start.line + text.slice(0, i).split('\n').length - 1;
235
+ out.limited = { file: mod.rel, line, code: H.snippet(mod, line) };
236
+ }
237
+ const aiNodes = [];
238
+ const calls = [];
239
+ fnRef.path.traverse({
240
+ CallExpression(p) { calls.push(p); },
241
+ });
242
+ for (const p of calls) {
243
+ const provider = aiCallOf(ctx, H, mod, p);
244
+ if (provider) {
245
+ out.calls.push(Object.assign({ provider }, at(p.node)));
246
+ aiNodes.push(p);
247
+ continue;
248
+ }
249
+ // a helper of the app's own: an AI answer it returns is an AI answer here
250
+ const chain = H.memberChain(p.node.callee);
251
+ if (!chain || FETCHERS.test(chain[0]) || chain[0] === 'require') continue;
252
+ let r = null;
253
+ try { r = H.resolveRef(ctx, mod, p.get('callee')); } catch (e) { r = null; }
254
+ if ((!r || r.kind !== 'fn') && chain.length === 1) r = ownFunction(ctx, mod, chain[0]);
255
+ if (!r || r.kind !== 'fn' || !r.path || r.path.node === fnRef.path.node) continue;
256
+ const inner = readHandler(ctx, H, r, depth + 1, seen);
257
+ if (inner.approval) out.approval = true;
258
+ if (inner.limited && !out.limited) out.limited = inner.limited;
259
+ for (const a of inner.acts) out.acts.push(Object.assign({}, a, { via: chain.join('.') + '() at ' + mod.rel + ':' + p.node.loc.start.line }));
260
+ if (inner.calls.length) {
261
+ for (const c of inner.calls) out.calls.push(Object.assign({}, c, { via: chain.join('.') + '() at ' + mod.rel + ':' + p.node.loc.start.line }));
262
+ aiNodes.push(p);
263
+ }
264
+ }
265
+ if (!aiNodes.length) return out;
266
+ // what holds the AI's answer: the names it is put in, and the names made from those
267
+ const held = new Set();
268
+ for (const p of aiNodes) {
269
+ // const reply = (await openai.chat.completions.create(...)).choices[0].message.content - the nearest name above it
270
+ const holder = p.findParent((x) => x.isVariableDeclarator() || x.isAssignmentExpression() || x.isStatement() || x.isFunction());
271
+ if (holder && holder.isVariableDeclarator()) namesOf(holder.node.id, held);
272
+ else if (holder && holder.isAssignmentExpression()) namesOf(holder.node.left, held);
273
+ }
274
+ for (let round = 0; round < 4; round++) {
275
+ const before = held.size;
276
+ fnRef.path.traverse({
277
+ VariableDeclarator(p) { if (p.node.init && mentions(t, p.node.init, held)) namesOf(p.node.id, held); },
278
+ AssignmentExpression(p) { if (mentions(t, p.node.right, held)) namesOf(p.node.left, held); },
279
+ ForOfStatement(p) { if (mentions(t, p.node.right, held) && p.node.left.type === 'VariableDeclaration') for (const d of p.node.left.declarations) namesOf(d.id, held); },
280
+ });
281
+ if (held.size === before) break;
282
+ }
283
+ const insideAi = (p) => aiNodes.some((a) => a.node !== p.node && p.node.start >= a.node.start && p.node.end <= a.node.end);
284
+ for (const p of calls) {
285
+ if (aiNodes.includes(p)) continue;
286
+ const chain = H.memberChain(p.node.callee);
287
+ const send = sendOf(ctx, H, mod, p);
288
+ const fetchesChosen = chain && chain.length <= 2 && FETCHERS.test(chain[0]) && p.node.arguments[0] && mentions(t, p.node.arguments[0], held);
289
+ if (!send && !fetchesChosen) continue;
290
+ // the AI's own tool: tools: { sendEmail: tool({ execute: (...) => sendMail(...) }) } - the model decides
291
+ const tool = insideAi(p);
292
+ const fed = p.node.arguments.some((a) => mentions(t, a, held) || aiNodes.some((n) => a.start <= n.node.start && a.end >= n.node.end));
293
+ if (!tool && !fed) continue;
294
+ out.acts.push(Object.assign({ what: fetchesChosen ? 'calls an address the AI chose' : send, tool }, at(p.node)));
295
+ }
296
+ return out;
297
+ }
298
+
299
+ /** The route's whole AI reading, or null when it asks no AI. */
300
+ function routeAi(ctx, H, fnRef, route) {
301
+ let r;
302
+ try { r = readHandler(ctx, H, fnRef); } catch (e) { return null; }
303
+ if (!r.calls.length) return null;
304
+ const mw = (route && route.middleware) || [];
305
+ const lim = mw.find((m) => LIMIT.test(m.name || '') || (m.source && LIMIT_PKG.test(m.source)));
306
+ if (lim && !r.limited) r.limited = { file: lim.usedFile || lim.file, line: lim.usedLine || lim.line, code: lim.name };
307
+ if (route && route.path && APPROVAL.test(route.path)) r.approval = true;
308
+ return {
309
+ calls: r.calls.slice(0, 5),
310
+ acts: r.acts.slice(0, 5),
311
+ limited: r.limited,
312
+ approval: r.approval,
313
+ };
314
+ }
315
+
316
+ // --- answers of the running app -----------------------------------------------------
317
+
318
+ // Keys and tokens that are only ever the server's: shapes no other value has.
319
+ const KEY_SHAPES = [
320
+ { re: /^sk-ant-(api|admin)\d{2}-[\w-]{20,}$/, label: 'an Anthropic API key' },
321
+ { re: /^sk-(proj-|svcacct-|admin-)?[\w-]{20,}$/, label: 'an OpenAI API key' },
322
+ { re: /^AIza[\w-]{35}$/, label: 'a Google API key' },
323
+ { re: /^gsk_[\w]{20,}$/, label: 'a Groq API key' },
324
+ { re: /^r8_[\w]{20,}$/, label: 'a Replicate API token' },
325
+ { re: /^hf_[\w]{20,}$/, label: 'a Hugging Face token' },
326
+ { re: /^sk-or-v1-[\w]{20,}$/, label: 'an OpenRouter API key' },
327
+ { re: /^xai-[\w]{20,}$/, label: 'an xAI API key' },
328
+ { re: /^(sk|rk)_live_[\w]{16,}$/, label: 'a Stripe live secret key' },
329
+ { re: /^re_[A-Za-z0-9]{8,}_[\w]{16,}$/, label: 'a Resend API key' },
330
+ { re: /^SG\.[\w-]{16,}\.[\w-]{16,}$/, label: 'a SendGrid API key' },
331
+ { re: /^xox[bpas]-[\w-]{20,}$/, label: 'a Slack token' },
332
+ { re: /^gh[pousr]_[\w]{30,}$/, label: 'a GitHub token' },
333
+ { re: /^1\/\/0[\w-]{30,}$/, label: 'a Google refresh token' },
334
+ ];
335
+ // A field that holds a key or a stored token by its name (a value too short or empty is not one).
336
+ const SECRET_FIELD = /^(api[_-]?key|apikey|secret[_-]?key|(openai|anthropic|gemini|google|groq|mistral|cohere|replicate|openrouter|claude|gpt|llm|ai|model|provider)[_-]?(api[_-]?)?(key|token|secret)|refresh[_-]?token|(gmail|google|outlook|slack|oauth|smtp|imap)[_-]?(refresh[_-]?)?(token|password|secret)|client[_-]?secret|private[_-]?key|smtp[_-]?pass(word)?|app[_-]?password)$/i;
337
+ const MASKED_VALUE = /^[•*x.\-_ ]*$|\*{3,}|•{3,}|\.{3}/i;
338
+
339
+ // A quiz item: a question and, beside it, which answer is right.
340
+ const QUESTION_FIELD = /^(question|question[_-]?text|prompt|stem|q|text|title|body)$/i;
341
+ const ANSWER_FIELD = /^(correct[_-]?(answer|answers|option|options|choice|choices|index|idx|key)|answer[_-]?(key|index|idx)?|right[_-]?answer|solution|is[_-]?correct|isCorrect|correct)$/i;
342
+ const OPTIONS_FIELD = /^(options|choices|answers|alternatives)$/i;
343
+
344
+ /**
345
+ * Every key-shaped value and secret-named field in an answer, and every quiz item that carries its answer.
346
+ * { secrets: [{ path, field, label, value }], quiz: [{ path, field }] } - values are kept only to compare, never shown.
347
+ */
348
+ function scanAnswer(json) {
349
+ const secrets = [];
350
+ const quiz = [];
351
+ const walk = (v, at, field, depth) => {
352
+ if (depth > 8 || v === null || v === undefined) return;
353
+ if (typeof v === 'string') {
354
+ const s = v.trim();
355
+ if (s.length < 16 || s.length > 400 || /\s/.test(s)) {
356
+ if (field && SECRET_FIELD.test(field) && s.length >= 12 && !/\s/.test(s) && !MASKED_VALUE.test(s)) secrets.push({ path: at, field, label: 'a stored ' + field.replace(/[_-]/g, ' '), value: s });
357
+ return;
358
+ }
359
+ const shape = KEY_SHAPES.find((k) => k.re.test(s));
360
+ if (shape) secrets.push({ path: at, field, label: shape.label, value: s });
361
+ else if (field && SECRET_FIELD.test(field) && !MASKED_VALUE.test(s)) secrets.push({ path: at, field, label: 'a stored ' + field.replace(/[_-]/g, ' '), value: s });
362
+ return;
363
+ }
364
+ if (Array.isArray(v)) {
365
+ v.slice(0, 200).forEach((x, i) => walk(x, at + '[' + i + ']', field, depth + 1));
366
+ return;
367
+ }
368
+ if (typeof v === 'object') {
369
+ const keys = Object.keys(v);
370
+ const q = keys.find((k) => QUESTION_FIELD.test(k) && typeof v[k] === 'string');
371
+ const opts = keys.find((k) => OPTIONS_FIELD.test(k) && Array.isArray(v[k]));
372
+ const ans = keys.find((k) => ANSWER_FIELD.test(k) && v[k] !== null && v[k] !== undefined && v[k] !== '');
373
+ // a question is asked here: a key named for one, not a title or a body on its own
374
+ const asksQ = keys.some((k) => /question|prompt|stem/i.test(k) || /^q$/i.test(k));
375
+ // "answer" beside a question is the right answer only when there are options to choose from or it says "correct"
376
+ const isQuiz = q && ans && (opts || /correct|solution|right|key|index|idx/i.test(ans)) && asksQ;
377
+ if (isQuiz) quiz.push({ path: at, field: ans });
378
+ // options that each say whether they are the right one
379
+ if (q && opts && asksQ) {
380
+ const flagged = v[opts].find((o) => o && typeof o === 'object' && Object.keys(o).some((k) => /^(is[_-]?correct|isCorrect|correct|is[_-]?answer|right)$/i.test(k)));
381
+ if (flagged && !isQuiz) quiz.push({ path: at, field: opts + '[].' + Object.keys(flagged).find((k) => /^(is[_-]?correct|isCorrect|correct|is[_-]?answer|right)$/i.test(k)) });
382
+ }
383
+ for (const k of keys.slice(0, 200)) walk(v[k], at + '.' + k, k, depth + 1);
384
+ }
385
+ };
386
+ walk(json, '$', null, 0);
387
+ return { secrets, quiz };
388
+ }
389
+
390
+ /** A path that is about results, answers given or a teacher's view: answers there are meant to be seen. */
391
+ const ANSWERS_MEANT = /result|attempt|submission|review|grade|graded|score|answer[-_]?key|teacher|instructor|admin|solution|explain|feedback|history|report/i;
392
+ /** A path where a person's own token is the point: signing in, a session, connecting an account. */
393
+ const TOKEN_MEANT = /auth|login|signin|sign-in|session|token|oauth|callback|connect/i;
394
+
395
+ /** A provider as a person knows it: 'openai' -> OpenAI, 'api.anthropic.com' -> Anthropic (Claude). */
396
+ function providerName(p) {
397
+ const s = String(p || '');
398
+ if (/openai/.test(s) && !/openrouter/.test(s)) return 'OpenAI';
399
+ if (/anthropic/.test(s)) return 'Anthropic (Claude)';
400
+ if (/google|gemini|generativelanguage|aiplatform|vertex/.test(s)) return 'Google Gemini';
401
+ if (/groq/.test(s)) return 'Groq';
402
+ if (/mistral/.test(s)) return 'Mistral';
403
+ if (/cohere/.test(s)) return 'Cohere';
404
+ if (/replicate/.test(s)) return 'Replicate';
405
+ if (/openrouter/.test(s)) return 'OpenRouter';
406
+ if (/huggingface/.test(s)) return 'Hugging Face';
407
+ if (/bedrock/.test(s)) return 'AWS Bedrock';
408
+ if (/deepseek/.test(s)) return 'DeepSeek';
409
+ return 'an AI provider';
410
+ }
411
+
412
+ module.exports = {
413
+ providerName,
414
+ AI_PKG, AI_HOST, LIMIT, LIMIT_PKG, APPROVAL, ANSWERS_MEANT, TOKEN_MEANT,
415
+ readHandler, routeAi, scanAnswer, aiCallOf,
416
+ };