@andorra-labs/code 0.1.6 → 0.1.7
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/src/agent-execution.js +404 -25
- package/dist/src/agent-mcp-catalog.d.ts +21 -0
- package/dist/src/agent-mcp-catalog.js +40 -0
- package/dist/src/agent-mcp.d.ts +19 -3
- package/dist/src/agent-mcp.js +18 -44
- package/dist/src/app-server/protocol.d.ts +25 -3
- package/dist/src/app-server/protocol.js +5 -1
- package/dist/src/app-server/workspace.d.ts +8 -1
- package/dist/src/app-server/workspace.js +43 -2
- package/dist/src/app-server.js +88 -3
- package/dist/src/auth/AuthManager.d.ts +33 -1
- package/dist/src/auth/AuthManager.js +138 -10
- package/dist/src/auth/callback-page.d.ts +4 -0
- package/dist/src/auth/callback-page.js +70 -0
- package/dist/src/auth/callback.d.ts +39 -0
- package/dist/src/auth/callback.js +146 -22
- package/dist/src/auth/index.d.ts +10 -6
- package/dist/src/auth/index.js +2 -2
- package/dist/src/auth/store.d.ts +142 -3
- package/dist/src/auth/store.js +334 -13
- package/dist/src/auth/types.d.ts +17 -1
- package/dist/src/auth-commands.d.ts +11 -2
- package/dist/src/auth-commands.js +14 -7
- package/dist/src/automation-tool.js +10 -2
- package/dist/src/automations.d.ts +5 -0
- package/dist/src/automations.js +10 -0
- package/dist/src/capabilities.d.ts +9 -3
- package/dist/src/capabilities.js +7 -3
- package/dist/src/cli.js +31 -4
- package/dist/src/codex-provider.js +12 -0
- package/dist/src/coding-tools.d.ts +5 -0
- package/dist/src/coding-tools.js +54 -48
- package/dist/src/commands.d.ts +5 -1
- package/dist/src/commands.js +7 -6
- package/dist/src/completion.js +46 -0
- package/dist/src/config.d.ts +48 -0
- package/dist/src/config.js +248 -10
- package/dist/src/context-budget.d.ts +7 -0
- package/dist/src/context-budget.js +18 -1
- package/dist/src/decision/FactContinuations.d.ts +41 -6
- package/dist/src/decision/FactContinuations.js +211 -64
- package/dist/src/decision/PreparedSteps.js +3 -1
- package/dist/src/decision/checks.d.ts +25 -0
- package/dist/src/decision/checks.js +77 -6
- package/dist/src/delegation-changes.d.ts +109 -0
- package/dist/src/delegation-changes.js +431 -0
- package/dist/src/graph-server.d.ts +1 -0
- package/dist/src/graph-server.js +15 -3
- package/dist/src/graph-sync.d.ts +15 -0
- package/dist/src/graph-sync.js +50 -1
- package/dist/src/graph-tool.d.ts +52 -0
- package/dist/src/graph-tool.js +136 -0
- package/dist/src/graph-ui/app.js +212 -43
- package/dist/src/graph-ui/controls.js +6 -0
- package/dist/src/graph-ui/drafts.js +39 -0
- package/dist/src/graph-ui/embed.js +1 -1
- package/dist/src/graph-ui/index.html +2 -2
- package/dist/src/graph-ui/studio.css +7 -5
- package/dist/src/graph-ui/style.css +46 -12
- package/dist/src/graphs.d.ts +15 -2
- package/dist/src/graphs.js +42 -13
- package/dist/src/hardened-runtime.d.ts +4 -4
- package/dist/src/hardened-runtime.js +109 -9
- package/dist/src/powershell-pool.d.ts +9 -0
- package/dist/src/powershell-pool.js +16 -0
- package/dist/src/provider-keys.d.ts +48 -0
- package/dist/src/provider-keys.js +121 -0
- package/dist/src/pull-requests.d.ts +14 -5
- package/dist/src/pull-requests.js +28 -10
- package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
- package/dist/src/qa/runtime/ProcessManager.js +16 -0
- package/dist/src/react-runtime.js +30 -2
- package/dist/src/read-image.d.ts +30 -0
- package/dist/src/read-image.js +97 -0
- package/dist/src/secret-redaction.d.ts +13 -0
- package/dist/src/secret-redaction.js +71 -0
- package/dist/src/session-summary.d.ts +10 -4
- package/dist/src/session-summary.js +14 -7
- package/dist/src/sessions.js +4 -1
- package/dist/src/skills/bundled/graph-manager/SKILL.md +14 -11
- package/dist/src/skills/bundled/provenance.json +1 -1
- package/dist/src/telemetry/schema.d.ts +1 -1
- package/dist/src/telemetry/schema.js +1 -1
- package/dist/src/terminal-ui.d.ts +9 -0
- package/dist/src/terminal-ui.js +14 -0
- package/dist/src/tool-dependencies.js +4 -0
- package/dist/src/tools.d.ts +9 -0
- package/dist/src/tools.js +116 -11
- package/dist/src/transcript.js +5 -0
- package/dist/src/types.d.ts +13 -0
- package/dist/src/web-search.d.ts +59 -0
- package/dist/src/web-search.js +216 -0
- package/docs/agents/README.md +2 -2
- package/docs/agents/mcp-server.md +15 -2
- package/docs/concepts/README.md +1 -1
- package/docs/concepts/security.md +2 -2
- package/docs/getting-started/accounts.md +15 -4
- package/docs/getting-started/configure-providers.md +1 -1
- package/docs/guides/README.md +1 -0
- package/docs/guides/desktop-app.md +1 -1
- package/docs/guides/graph-builder.md +1 -1
- package/docs/guides/web-search.md +47 -0
- package/docs/reference/cli.md +4 -3
- package/docs/reference/config.md +3 -3
- package/docs/reference/slash-commands.md +2 -1
- package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
- package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
- package/package.json +1 -1
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saved provider API keys, kept in the OS credential store rather than in `config.json`.
|
|
3
|
+
*
|
|
4
|
+
* Each provider's key lives in its own vault entry, scoped by the configuration directory and the
|
|
5
|
+
* provider id, under its own service so `andorra logout --all` (which clears sign-ins) never touches
|
|
6
|
+
* them. One entry per key keeps each within the store's per-entry bound however many providers are
|
|
7
|
+
* configured, and lets a save write only the keys that changed. The configuration file keeps a
|
|
8
|
+
* `providerKeys: "keyring"` marker in their place; the keys are read back into memory when the
|
|
9
|
+
* configuration loads, so everything downstream of `loadConfig` sees exactly the provider objects it
|
|
10
|
+
* always did.
|
|
11
|
+
*
|
|
12
|
+
* Where the machine has no OS store (Linux without Secret Service), or the user chose
|
|
13
|
+
* `ANDORRA_CREDENTIAL_STORE=file`, keys stay in the owner-only `config.json` as before: that is
|
|
14
|
+
* the same fallback a sign-in takes. On Windows and macOS a failing store is reported instead.
|
|
15
|
+
*/
|
|
16
|
+
export declare const PROVIDER_KEY_SERVICE = "Andorra Code provider keys";
|
|
17
|
+
/** The value `config.json` holds in `providerKeys` while its keys are in the OS store. */
|
|
18
|
+
export declare const PROVIDER_KEYS_IN_KEYRING = "keyring";
|
|
19
|
+
export interface ProviderKeyVault {
|
|
20
|
+
read(): Promise<string | undefined>;
|
|
21
|
+
write(value: string): Promise<void>;
|
|
22
|
+
remove(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
type VaultFactory = (directory: string, provider: string) => ProviderKeyVault;
|
|
25
|
+
/** Tests replace the OS store (and the platform's fallback rule); the returned function restores both. */
|
|
26
|
+
export declare function setProviderKeyVaultForTesting(factory: VaultFactory | undefined, options?: {
|
|
27
|
+
fallback?: boolean;
|
|
28
|
+
}): () => void;
|
|
29
|
+
/** The keys a configuration directory saved for these providers, by provider id. */
|
|
30
|
+
export declare function readProviderKeys(directory: string, providers: readonly string[]): Promise<Map<string, string>>;
|
|
31
|
+
/**
|
|
32
|
+
* Save the keys in the OS store: each key that differs from `current` (what the vault already
|
|
33
|
+
* holds, when known) is written, so an unchanged key is not rewritten on every save. Keys that
|
|
34
|
+
* are no longer configured are left for the caller to remove once the configuration that drops
|
|
35
|
+
* them is published. Returns false, having saved nothing, when the keys belong in `config.json`
|
|
36
|
+
* instead: `ANDORRA_CREDENTIAL_STORE=file`, or no OS store on a platform where that falls back.
|
|
37
|
+
*/
|
|
38
|
+
export declare function storeProviderKeys(directory: string, keys: Map<string, string>, current?: Map<string, string>, environment?: NodeJS.ProcessEnv): Promise<boolean>;
|
|
39
|
+
/**
|
|
40
|
+
* Put the vault back the way `current` describes it for these providers, after a save that wrote
|
|
41
|
+
* them could not publish its configuration. Best-effort: the save's own failure is what is reported.
|
|
42
|
+
*/
|
|
43
|
+
export declare function restoreProviderKeys(directory: string, providers: Iterable<string>, current: Map<string, string>): Promise<void>;
|
|
44
|
+
/** Delete the keys a configuration directory saved for these providers. A machine without an OS store holds none. */
|
|
45
|
+
export declare function removeProviderKeys(directory: string, providers: Iterable<string>): Promise<void>;
|
|
46
|
+
/** Whether saving should move plaintext keys out of `config.json` on this machine. */
|
|
47
|
+
export declare function providerKeysBelongInKeyring(environment?: NodeJS.ProcessEnv): boolean;
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { credentialStoreMode, KeyringAbsentError, KeyringCredentialStore } from './auth/store.js';
|
|
3
|
+
/**
|
|
4
|
+
* Saved provider API keys, kept in the OS credential store rather than in `config.json`.
|
|
5
|
+
*
|
|
6
|
+
* Each provider's key lives in its own vault entry, scoped by the configuration directory and the
|
|
7
|
+
* provider id, under its own service so `andorra logout --all` (which clears sign-ins) never touches
|
|
8
|
+
* them. One entry per key keeps each within the store's per-entry bound however many providers are
|
|
9
|
+
* configured, and lets a save write only the keys that changed. The configuration file keeps a
|
|
10
|
+
* `providerKeys: "keyring"` marker in their place; the keys are read back into memory when the
|
|
11
|
+
* configuration loads, so everything downstream of `loadConfig` sees exactly the provider objects it
|
|
12
|
+
* always did.
|
|
13
|
+
*
|
|
14
|
+
* Where the machine has no OS store (Linux without Secret Service), or the user chose
|
|
15
|
+
* `ANDORRA_CREDENTIAL_STORE=file`, keys stay in the owner-only `config.json` as before: that is
|
|
16
|
+
* the same fallback a sign-in takes. On Windows and macOS a failing store is reported instead.
|
|
17
|
+
*/
|
|
18
|
+
export const PROVIDER_KEY_SERVICE = 'Andorra Code provider keys';
|
|
19
|
+
/** The value `config.json` holds in `providerKeys` while its keys are in the OS store. */
|
|
20
|
+
export const PROVIDER_KEYS_IN_KEYRING = 'keyring';
|
|
21
|
+
const keyringVault = (directory, provider) => new KeyringCredentialStore(`provider-keys|${resolve(directory)}|${provider}`, undefined, { service: PROVIDER_KEY_SERVICE });
|
|
22
|
+
let vaultFor = keyringVault;
|
|
23
|
+
let fallbackPlatform = process.platform !== 'win32' && process.platform !== 'darwin';
|
|
24
|
+
/** Tests replace the OS store (and the platform's fallback rule); the returned function restores both. */
|
|
25
|
+
export function setProviderKeyVaultForTesting(factory, options = {}) {
|
|
26
|
+
const previous = vaultFor, previousFallback = fallbackPlatform;
|
|
27
|
+
vaultFor = factory ?? keyringVault;
|
|
28
|
+
if (options.fallback !== undefined)
|
|
29
|
+
fallbackPlatform = options.fallback;
|
|
30
|
+
return () => { vaultFor = previous; fallbackPlatform = previousFallback; };
|
|
31
|
+
}
|
|
32
|
+
const UNLOCK = 'Unlock it and retry, or set ANDORRA_CREDENTIAL_STORE=file to keep provider API keys in config.json instead.';
|
|
33
|
+
/** Reads of one key made before one is reported as failing. */
|
|
34
|
+
const READ_ATTEMPTS = 3;
|
|
35
|
+
/**
|
|
36
|
+
* One provider's saved key. A read takes no lock, so it can fetch a manifest that a concurrent
|
|
37
|
+
* save then replaces, deleting the chunks it names; a later read sees the finished save, and only
|
|
38
|
+
* a failure that repeats is reported.
|
|
39
|
+
*/
|
|
40
|
+
async function readKey(directory, provider) {
|
|
41
|
+
for (let attempt = 1;; attempt++) {
|
|
42
|
+
try {
|
|
43
|
+
return (await vaultFor(directory, provider).read()) || undefined;
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (attempt >= READ_ATTEMPTS)
|
|
47
|
+
throw new Error(`Unable to read saved provider API keys from the OS credential store. ${UNLOCK}`, { cause: error });
|
|
48
|
+
await new Promise(done => setTimeout(done, 25 * attempt));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** The keys a configuration directory saved for these providers, by provider id. */
|
|
53
|
+
export async function readProviderKeys(directory, providers) {
|
|
54
|
+
const keys = new Map();
|
|
55
|
+
for (const provider of new Set(providers)) {
|
|
56
|
+
const key = await readKey(directory, provider);
|
|
57
|
+
if (key !== undefined)
|
|
58
|
+
keys.set(provider, key);
|
|
59
|
+
}
|
|
60
|
+
return keys;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Save the keys in the OS store: each key that differs from `current` (what the vault already
|
|
64
|
+
* holds, when known) is written, so an unchanged key is not rewritten on every save. Keys that
|
|
65
|
+
* are no longer configured are left for the caller to remove once the configuration that drops
|
|
66
|
+
* them is published. Returns false, having saved nothing, when the keys belong in `config.json`
|
|
67
|
+
* instead: `ANDORRA_CREDENTIAL_STORE=file`, or no OS store on a platform where that falls back.
|
|
68
|
+
*/
|
|
69
|
+
export async function storeProviderKeys(directory, keys, current, environment = process.env) {
|
|
70
|
+
const mode = credentialStoreMode(environment);
|
|
71
|
+
if (mode === 'file')
|
|
72
|
+
return false;
|
|
73
|
+
const written = [];
|
|
74
|
+
try {
|
|
75
|
+
for (const [provider, key] of keys) {
|
|
76
|
+
if (current?.get(provider) === key)
|
|
77
|
+
continue;
|
|
78
|
+
// Recorded before the write: one that fails partway can leave chunks holding the key, and
|
|
79
|
+
// the rollback below removes them.
|
|
80
|
+
written.push(provider);
|
|
81
|
+
await vaultFor(directory, provider).write(key);
|
|
82
|
+
}
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// A save that stops partway puts back the keys it already replaced, so the configuration still
|
|
87
|
+
// on disk keeps the keys it names.
|
|
88
|
+
if (current)
|
|
89
|
+
await restoreProviderKeys(directory, written, current);
|
|
90
|
+
if (mode === 'auto' && fallbackPlatform && error instanceof KeyringAbsentError)
|
|
91
|
+
return false;
|
|
92
|
+
throw new Error(`Unable to save provider API keys in the OS credential store. ${UNLOCK}`, { cause: error });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Put the vault back the way `current` describes it for these providers, after a save that wrote
|
|
97
|
+
* them could not publish its configuration. Best-effort: the save's own failure is what is reported.
|
|
98
|
+
*/
|
|
99
|
+
export async function restoreProviderKeys(directory, providers, current) {
|
|
100
|
+
for (const provider of providers) {
|
|
101
|
+
const key = current.get(provider);
|
|
102
|
+
await (key === undefined ? vaultFor(directory, provider).remove() : vaultFor(directory, provider).write(key)).catch(() => { });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** Delete the keys a configuration directory saved for these providers. A machine without an OS store holds none. */
|
|
106
|
+
export async function removeProviderKeys(directory, providers) {
|
|
107
|
+
for (const provider of new Set(providers)) {
|
|
108
|
+
try {
|
|
109
|
+
await vaultFor(directory, provider).remove();
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (error instanceof KeyringAbsentError)
|
|
113
|
+
return;
|
|
114
|
+
throw new Error('Unable to remove saved provider API keys from the OS credential store. Unlock it and retry.', { cause: error });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Whether saving should move plaintext keys out of `config.json` on this machine. */
|
|
119
|
+
export function providerKeysBelongInKeyring(environment = process.env) {
|
|
120
|
+
return credentialStoreMode(environment) !== 'file';
|
|
121
|
+
}
|
|
@@ -13,7 +13,7 @@ export interface SessionPullRequest {
|
|
|
13
13
|
number: number;
|
|
14
14
|
title?: string;
|
|
15
15
|
state: PullRequestState;
|
|
16
|
-
/** Wake the session when review comments
|
|
16
|
+
/** Wake the session when a code-review bot comments. Never on for a merged or closed PR: it switches itself off. */
|
|
17
17
|
autoFix: boolean;
|
|
18
18
|
mergeWhenReady: boolean;
|
|
19
19
|
/** When the PR was attached: a top-level comment older than this was never the session's to answer. */
|
|
@@ -183,10 +183,19 @@ export declare class PullRequestCreateDetector {
|
|
|
183
183
|
}): PullRequestRef | undefined;
|
|
184
184
|
}
|
|
185
185
|
/**
|
|
186
|
-
* The review
|
|
186
|
+
* The code-review bots whose comments Auto-fix answers, by GitHub login (GraphQL reports a bot's login without the
|
|
187
|
+
* `[bot]` suffix the REST API adds; both spellings match). Nobody else wakes the agent: not CI or deployment bots,
|
|
188
|
+
* not the agent's own replies and `@codex review` requests (posted as whichever signed-in account it ran `gh` as,
|
|
189
|
+
* which need not be the account the watcher reads with), and not people.
|
|
190
|
+
*/
|
|
191
|
+
export declare const CODE_REVIEWER_LOGINS: readonly string[];
|
|
192
|
+
/** Whether `login` is one of the code-review bots Auto-fix answers. */
|
|
193
|
+
export declare function isCodeReviewer(login: string | undefined): boolean;
|
|
194
|
+
/**
|
|
195
|
+
* The code reviewers' comments that arrived since Auto-fix last woke the agent.
|
|
187
196
|
*
|
|
188
|
-
* Counted: comments in unresolved review threads, and top-level
|
|
189
|
-
*
|
|
197
|
+
* Counted: comments by a code-review bot (`CODE_REVIEWER_LOGINS`) in unresolved review threads, and its top-level
|
|
198
|
+
* PR comments posted after the PR was attached. Any other author's comment is never a reason to wake the agent.
|
|
190
199
|
*/
|
|
191
200
|
export declare function newReviewComments(gh: GhRunner, pullRequest: SessionPullRequest): Promise<{
|
|
192
201
|
threads: number;
|
|
@@ -238,7 +247,7 @@ export interface PullRequestWatcherOptions {
|
|
|
238
247
|
*/
|
|
239
248
|
export declare function pullRequestNeedsWatch(pullRequest: SessionPullRequest): boolean;
|
|
240
249
|
/**
|
|
241
|
-
* Polls every unfinished PR, and wakes the agent for new
|
|
250
|
+
* Polls every unfinished PR, and wakes the agent for new code-reviewer comments on the ones with Auto-fix on.
|
|
242
251
|
*
|
|
243
252
|
* The timer is unref'd and every poll is serialized: a slow `gh` never stacks a second poll on the first.
|
|
244
253
|
*/
|
|
@@ -419,14 +419,33 @@ export class PullRequestCreateDetector {
|
|
|
419
419
|
return typeof event.data.output === 'string' ? parsePullRequestUrl(event.data.output) : undefined;
|
|
420
420
|
}
|
|
421
421
|
}
|
|
422
|
-
const REVIEW_QUERY = 'query($owner: String!, $name: String!, $number: Int!, $after: String) {
|
|
422
|
+
const REVIEW_QUERY = 'query($owner: String!, $name: String!, $number: Int!, $after: String) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviewThreads(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { isResolved comments(last: 20) { nodes { author { login } createdAt } } } } comments(last: 50) { nodes { author { login } createdAt } } } } }';
|
|
423
423
|
/** A bound on pages read per poll, so a pathological PR cannot keep one poll going indefinitely. */
|
|
424
424
|
const MAX_THREAD_PAGES = 50;
|
|
425
425
|
/**
|
|
426
|
-
* The review
|
|
426
|
+
* The code-review bots whose comments Auto-fix answers, by GitHub login (GraphQL reports a bot's login without the
|
|
427
|
+
* `[bot]` suffix the REST API adds; both spellings match). Nobody else wakes the agent: not CI or deployment bots,
|
|
428
|
+
* not the agent's own replies and `@codex review` requests (posted as whichever signed-in account it ran `gh` as,
|
|
429
|
+
* which need not be the account the watcher reads with), and not people.
|
|
430
|
+
*/
|
|
431
|
+
export const CODE_REVIEWER_LOGINS = [
|
|
432
|
+
'chatgpt-codex-connector', // Codex
|
|
433
|
+
'coderabbitai', // CodeRabbit
|
|
434
|
+
'greptile-apps', // Greptile
|
|
435
|
+
'copilot-pull-request-reviewer', // GitHub Copilot code review
|
|
436
|
+
];
|
|
437
|
+
/** Whether `login` is one of the code-review bots Auto-fix answers. */
|
|
438
|
+
export function isCodeReviewer(login) {
|
|
439
|
+
if (typeof login !== 'string')
|
|
440
|
+
return false;
|
|
441
|
+
const name = login.toLowerCase().replace(/\[bot\]$/, '');
|
|
442
|
+
return CODE_REVIEWER_LOGINS.includes(name);
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* The code reviewers' comments that arrived since Auto-fix last woke the agent.
|
|
427
446
|
*
|
|
428
|
-
* Counted: comments in unresolved review threads, and top-level
|
|
429
|
-
*
|
|
447
|
+
* Counted: comments by a code-review bot (`CODE_REVIEWER_LOGINS`) in unresolved review threads, and its top-level
|
|
448
|
+
* PR comments posted after the PR was attached. Any other author's comment is never a reason to wake the agent.
|
|
430
449
|
*/
|
|
431
450
|
export async function newReviewComments(gh, pullRequest) {
|
|
432
451
|
// Every page of threads: a new unresolved thread past the first hundred must still be seen.
|
|
@@ -444,10 +463,9 @@ export async function newReviewComments(gh, pullRequest) {
|
|
|
444
463
|
break;
|
|
445
464
|
cursor = threads.pageInfo.endCursor;
|
|
446
465
|
}
|
|
447
|
-
const viewer = first?.viewer?.login;
|
|
448
466
|
const pull = first?.repository?.pullRequest;
|
|
449
467
|
const after = (stamp, floor) => stamp !== undefined && (floor === undefined || Date.parse(stamp) > Date.parse(floor));
|
|
450
|
-
const
|
|
468
|
+
const byReviewer = (node) => typeof node.createdAt === 'string' && isCodeReviewer(node.author?.login);
|
|
451
469
|
let newest;
|
|
452
470
|
const note = (stamp) => { if (newest === undefined || Date.parse(stamp) > Date.parse(newest))
|
|
453
471
|
newest = stamp; };
|
|
@@ -455,7 +473,7 @@ export async function newReviewComments(gh, pullRequest) {
|
|
|
455
473
|
for (const thread of threadNodes) {
|
|
456
474
|
if (thread.isResolved)
|
|
457
475
|
continue;
|
|
458
|
-
const fresh = (thread.comments?.nodes ?? []).filter(node =>
|
|
476
|
+
const fresh = (thread.comments?.nodes ?? []).filter(node => byReviewer(node) && after(node.createdAt, pullRequest.handledThrough));
|
|
459
477
|
if (!fresh.length)
|
|
460
478
|
continue;
|
|
461
479
|
threads++;
|
|
@@ -465,7 +483,7 @@ export async function newReviewComments(gh, pullRequest) {
|
|
|
465
483
|
const floor = pullRequest.handledThrough !== undefined && Date.parse(pullRequest.handledThrough) > Date.parse(pullRequest.attachedAt) ? pullRequest.handledThrough : pullRequest.attachedAt;
|
|
466
484
|
let comments = 0;
|
|
467
485
|
for (const node of pull?.comments?.nodes ?? []) {
|
|
468
|
-
if (!
|
|
486
|
+
if (!byReviewer(node) || !after(node.createdAt, floor))
|
|
469
487
|
continue;
|
|
470
488
|
comments++;
|
|
471
489
|
note(node.createdAt);
|
|
@@ -532,7 +550,7 @@ export function pullRequestNeedsWatch(pullRequest) {
|
|
|
532
550
|
return !isFinishedPullRequest(pullRequest.state);
|
|
533
551
|
}
|
|
534
552
|
/**
|
|
535
|
-
* Polls every unfinished PR, and wakes the agent for new
|
|
553
|
+
* Polls every unfinished PR, and wakes the agent for new code-reviewer comments on the ones with Auto-fix on.
|
|
536
554
|
*
|
|
537
555
|
* The timer is unref'd and every poll is serialized: a slow `gh` never stacks a second poll on the first.
|
|
538
556
|
*/
|
|
@@ -645,7 +663,7 @@ export class PullRequestWatcher {
|
|
|
645
663
|
return undefined;
|
|
646
664
|
// The detected account replaces the one whose read failed, and only that one: another engine may have saved
|
|
647
665
|
// a different account while the re-detection was in flight, and that newer binding is what the comments
|
|
648
|
-
// below must be read as,
|
|
666
|
+
// below must be read as, since it is the account that can see the PR.
|
|
649
667
|
const rebind = (current.ghUser ?? null) === (stored.ghUser ?? null) ? account : undefined;
|
|
650
668
|
const accountChanged = rebind !== undefined && rebind !== (current.ghUser ?? null);
|
|
651
669
|
if (seen.state === current.state && seen.title === current.title && seen.autoMerge === current.mergeWhenReady
|
|
@@ -49,5 +49,11 @@ export declare class QaProcessManager {
|
|
|
49
49
|
export declare function defaultQaProcessesDir(workspace: string): string;
|
|
50
50
|
/** One process manager per workspace, retained for the life of the CLI. */
|
|
51
51
|
export declare function getQaProcessManager(workspace: string): QaProcessManager;
|
|
52
|
+
/**
|
|
53
|
+
* Stops every background process whose manager's workspace is `root` or a folder under it, and
|
|
54
|
+
* forgets those managers. For a workspace that is about to be deleted: a job left running there
|
|
55
|
+
* keeps its listeners, and on Windows keeps the folder from being removed. Never throws.
|
|
56
|
+
*/
|
|
57
|
+
export declare function stopQaProcessesUnder(root: string): Promise<void>;
|
|
52
58
|
/** CLI shutdown hook: kill every QA-owned background process. */
|
|
53
59
|
export declare function disposeAllQaProcesses(): Promise<void>;
|
|
@@ -217,6 +217,22 @@ export function getQaProcessManager(workspace) {
|
|
|
217
217
|
}
|
|
218
218
|
return manager;
|
|
219
219
|
}
|
|
220
|
+
/**
|
|
221
|
+
* Stops every background process whose manager's workspace is `root` or a folder under it, and
|
|
222
|
+
* forgets those managers. For a workspace that is about to be deleted: a job left running there
|
|
223
|
+
* keeps its listeners, and on Windows keeps the folder from being removed. Never throws.
|
|
224
|
+
*/
|
|
225
|
+
export async function stopQaProcessesUnder(root) {
|
|
226
|
+
const fold = (value) => process.platform === 'win32' ? value.toLowerCase() : value;
|
|
227
|
+
const base = fold(path.resolve(root));
|
|
228
|
+
const owned = [...managers].filter(([workspace]) => {
|
|
229
|
+
const inside = path.relative(base, fold(path.resolve(workspace)));
|
|
230
|
+
return inside === '' || (!inside.startsWith('..') && !path.isAbsolute(inside));
|
|
231
|
+
});
|
|
232
|
+
for (const [workspace] of owned)
|
|
233
|
+
managers.delete(workspace);
|
|
234
|
+
await Promise.all(owned.map(([, manager]) => manager.stopAll().catch(() => { })));
|
|
235
|
+
}
|
|
220
236
|
/** CLI shutdown hook: kill every QA-owned background process. */
|
|
221
237
|
export async function disposeAllQaProcesses() {
|
|
222
238
|
const managersSnapshot = [...managers.values()];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createGoalCompletionVerifier } from './goal-completion-verification.js';
|
|
2
2
|
import { validateExtendedToolSchema } from './tool-schema-compatibility.js';
|
|
3
3
|
import { canonicalToolName } from './tool-names.js';
|
|
4
|
-
import { ContextUsageAnchor, contextThreshold, microcompactToolResults, pruneHistoricalImages, serializeContext } from './context-budget.js';
|
|
4
|
+
import { ContextUsageAnchor, IMAGE_INPUT_REJECTED_NOTE, contextThreshold, dropRejectedImages, microcompactToolResults, pruneHistoricalImages, serializeContext } from './context-budget.js';
|
|
5
5
|
import { browserEventArguments, disposeBrowserSessions, isBrowserToolName } from './browser-session.js';
|
|
6
6
|
import { runRegularTurnLoop } from '../vendor/zcode/source/runtime/turn-loop.js';
|
|
7
7
|
import { validateInitialModelToolInput, getInitialInputValidationModelContent } from '../vendor/zcode/source/tool/executor/validation.js';
|
|
@@ -56,6 +56,17 @@ Use an empty tests array if no checks were run. Ordinary standalone answers may
|
|
|
56
56
|
${RESPONSE_STRUCTURE_GUIDANCE}
|
|
57
57
|
Never invent downstream review or verification.`;
|
|
58
58
|
const redactForDecision = (text) => redactSecrets(text).text;
|
|
59
|
+
/**
|
|
60
|
+
* Whether the provider answered with a client-error status that means "this request as written
|
|
61
|
+
* is not acceptable" (as opposed to credentials, rate limits or an outage). Endpoints without
|
|
62
|
+
* image input answer a request carrying one this way: 400/415/422 from the model server, 404
|
|
63
|
+
* from a router with no image-capable route.
|
|
64
|
+
*/
|
|
65
|
+
function refusedRequest(error) {
|
|
66
|
+
const direct = error?.status;
|
|
67
|
+
const status = typeof direct === 'number' ? direct : Number(/\(HTTP (\d{3})\)/.exec(error instanceof Error ? error.message : '')?.[1]);
|
|
68
|
+
return [400, 404, 415, 422].includes(status);
|
|
69
|
+
}
|
|
59
70
|
/** Canonical arguments prevent object-key order from disguising an identical side effect. */
|
|
60
71
|
function actionFingerprint(name, args) {
|
|
61
72
|
const canonical = (value) => Array.isArray(value) ? value.map(canonical)
|
|
@@ -741,6 +752,10 @@ export class AndorraAgentEngine {
|
|
|
741
752
|
const engineState = { stopHookContinuationCount: continuationState?.engineState?.stopHookContinuationCount ?? continuationState?.zcodeState?.stopHookContinuationCount ?? 0, outputTokenContinuationCount: continuationState?.engineState?.outputTokenContinuationCount ?? continuationState?.zcodeState?.outputTokenContinuationCount ?? 0 };
|
|
742
753
|
let outputPartials = [...(continuationState?.outputPartials ?? [])];
|
|
743
754
|
let overflowRecoveries = 0;
|
|
755
|
+
// Set once the provider refuses a request that carried images. Nothing declares whether an
|
|
756
|
+
// OpenAI-compatible endpoint accepts image input, so the first refusal is the capability
|
|
757
|
+
// probe: from then on this run sends text only, and one image can never brick the run.
|
|
758
|
+
let imageInputRejected = false;
|
|
744
759
|
let forceSequential = false;
|
|
745
760
|
let model = engineModel(options.model, options.provider, options.contextWindow);
|
|
746
761
|
const recoverCompaction = async (error) => {
|
|
@@ -965,6 +980,18 @@ export class AndorraAgentEngine {
|
|
|
965
980
|
signal.throwIfAborted();
|
|
966
981
|
if (!operationSignal.aborted) {
|
|
967
982
|
const contextOverflow = andorraIsContextOverflow({ ...toEngineResponse({ text: '', toolCalls: [] }, model), stopReason: 'error', errorMessage: error instanceof Error ? error.message : String(error) }, model.contextWindow);
|
|
983
|
+
if (!contextOverflow && refusedRequest(error) && requestMessages.some(message => message.images?.length)) {
|
|
984
|
+
// Retry only when an image actually left the conversation, so this can never loop:
|
|
985
|
+
// the repeated request has none to refuse. A user attachment that arrives after the
|
|
986
|
+
// first refusal takes this path again.
|
|
987
|
+
const dropped = dropRejectedImages(messages);
|
|
988
|
+
if (dropped) {
|
|
989
|
+
imageInputRejected = true;
|
|
990
|
+
await emit('agent.context.images_rejected', { images: dropped });
|
|
991
|
+
iteration--;
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
968
995
|
if (!contextOverflow || overflowRecoveries++ >= 1)
|
|
969
996
|
throw error;
|
|
970
997
|
let compacted;
|
|
@@ -1335,7 +1362,8 @@ export class AndorraAgentEngine {
|
|
|
1335
1362
|
if (!prepared.length)
|
|
1336
1363
|
return false;
|
|
1337
1364
|
for (const item of finalized) {
|
|
1338
|
-
const
|
|
1365
|
+
const withheld = imageInputRejected && !!item.images?.length;
|
|
1366
|
+
const observation = { role: 'tool', toolCallId: item.call.id, content: withheld ? `${item.output}\n${IMAGE_INPUT_REJECTED_NOTE}` : item.output, ...(item.images?.length && !withheld ? { images: item.images } : {}) };
|
|
1339
1367
|
messages.push(observation);
|
|
1340
1368
|
// Shell, metadata and failed/blocked calls do not prove implementation progress.
|
|
1341
1369
|
if (item.executionSucceeded === true && !item.isError
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ToolContext, ToolImage } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Image files through Read.
|
|
4
|
+
*
|
|
5
|
+
* A model can only judge a rendered frame, a plot or a screenshot by looking at it. Read hands a
|
|
6
|
+
* supported image file to the model as a native image through the same `resultImages` channel
|
|
7
|
+
* browser screenshots use, so retention, pruning and the provider boundary treat both alike.
|
|
8
|
+
*/
|
|
9
|
+
/** Largest image file Read will decode. */
|
|
10
|
+
export declare const READ_IMAGE_FILE_LIMIT: number;
|
|
11
|
+
/** Longest edge sent to the model; larger images are downscaled and the observation says so. */
|
|
12
|
+
export declare const READ_IMAGE_MAX_EDGE = 1568;
|
|
13
|
+
/** Encoded size of one image as sent, matching the browser screenshot allowance. */
|
|
14
|
+
export declare const READ_IMAGE_MAX_BYTES: number;
|
|
15
|
+
/** Images one model response's tool batch may read, across parallel Read calls. */
|
|
16
|
+
export declare const READ_IMAGE_BATCH_LIMIT = 6;
|
|
17
|
+
export declare const READ_IMAGE_BATCH_BYTES: number;
|
|
18
|
+
/**
|
|
19
|
+
* Hand over the image a Read observation carries. Identical observations (the same file read
|
|
20
|
+
* twice in one batch) queue under one key, so each claim receives exactly one image.
|
|
21
|
+
*/
|
|
22
|
+
export declare function claimReadImages(output: string): ToolImage[] | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Decode, downscale and stage one image file, returning the text observation that names it.
|
|
25
|
+
* The staged image is released by `claimReadImages` with that exact text.
|
|
26
|
+
*/
|
|
27
|
+
export declare function readImageObservation(context: ToolContext, shownPath: string, file: {
|
|
28
|
+
mimeType: string;
|
|
29
|
+
bytes: Buffer;
|
|
30
|
+
}): Promise<string>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { andorraConvertImageBytesToPng } from '../vendor/engine/runtime/coding-agent/utils/image-convert.js';
|
|
2
|
+
import { andorraResizeImage } from '../vendor/engine/runtime/coding-agent/utils/image-resize.js';
|
|
3
|
+
import { formatBytes } from './attachments.js';
|
|
4
|
+
/**
|
|
5
|
+
* Image files through Read.
|
|
6
|
+
*
|
|
7
|
+
* A model can only judge a rendered frame, a plot or a screenshot by looking at it. Read hands a
|
|
8
|
+
* supported image file to the model as a native image through the same `resultImages` channel
|
|
9
|
+
* browser screenshots use, so retention, pruning and the provider boundary treat both alike.
|
|
10
|
+
*/
|
|
11
|
+
/** Largest image file Read will decode. */
|
|
12
|
+
export const READ_IMAGE_FILE_LIMIT = 20 * 1024 * 1024;
|
|
13
|
+
/** Longest edge sent to the model; larger images are downscaled and the observation says so. */
|
|
14
|
+
export const READ_IMAGE_MAX_EDGE = 1568;
|
|
15
|
+
/** Encoded size of one image as sent, matching the browser screenshot allowance. */
|
|
16
|
+
export const READ_IMAGE_MAX_BYTES = 512 * 1024;
|
|
17
|
+
/** Images one model response's tool batch may read, across parallel Read calls. */
|
|
18
|
+
export const READ_IMAGE_BATCH_LIMIT = 6;
|
|
19
|
+
export const READ_IMAGE_BATCH_BYTES = 2 * 1024 * 1024;
|
|
20
|
+
/** Unclaimed images kept for `resultImages`; a caller that never claims cannot grow this. */
|
|
21
|
+
const PENDING_LIMIT = 16;
|
|
22
|
+
const budgets = new WeakMap();
|
|
23
|
+
const pending = new Map();
|
|
24
|
+
/**
|
|
25
|
+
* Hand over the image a Read observation carries. Identical observations (the same file read
|
|
26
|
+
* twice in one batch) queue under one key, so each claim receives exactly one image.
|
|
27
|
+
*/
|
|
28
|
+
export function claimReadImages(output) {
|
|
29
|
+
const queue = pending.get(output);
|
|
30
|
+
const image = queue?.shift();
|
|
31
|
+
if (queue && !queue.length)
|
|
32
|
+
pending.delete(output);
|
|
33
|
+
return image ? [image] : undefined;
|
|
34
|
+
}
|
|
35
|
+
function hold(output, image) {
|
|
36
|
+
const queue = pending.get(output);
|
|
37
|
+
if (queue)
|
|
38
|
+
queue.push(image);
|
|
39
|
+
else
|
|
40
|
+
pending.set(output, [image]);
|
|
41
|
+
while (pending.size > PENDING_LIMIT)
|
|
42
|
+
pending.delete(pending.keys().next().value);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Decode, downscale and stage one image file, returning the text observation that names it.
|
|
46
|
+
* The staged image is released by `claimReadImages` with that exact text.
|
|
47
|
+
*/
|
|
48
|
+
export async function readImageObservation(context, shownPath, file) {
|
|
49
|
+
// Embedders without a batch marker run unbudgeted: there is no response boundary to reset on.
|
|
50
|
+
const batch = context.browserToolBatch;
|
|
51
|
+
let budget;
|
|
52
|
+
if (batch) {
|
|
53
|
+
budget = budgets.get(batch);
|
|
54
|
+
if (!budget) {
|
|
55
|
+
budget = { count: 0, bytes: 0 };
|
|
56
|
+
budgets.set(batch, budget);
|
|
57
|
+
}
|
|
58
|
+
// Count before awaiting the decode so parallel reads share the cap.
|
|
59
|
+
if (budget.count >= READ_IMAGE_BATCH_LIMIT)
|
|
60
|
+
throw new Error(`Image read budget reached (${READ_IMAGE_BATCH_LIMIT} images per response); Read further images in a later turn.`);
|
|
61
|
+
budget.count++;
|
|
62
|
+
}
|
|
63
|
+
let staged = false;
|
|
64
|
+
try {
|
|
65
|
+
const undecodable = () => new Error(`Image file could not be decoded (${file.mimeType}, ${formatBytes(file.bytes.length)}); inspect it with a script instead.`);
|
|
66
|
+
// Providers accept PNG and JPEG everywhere; GIF, WebP and BMP are re-encoded as PNG first.
|
|
67
|
+
const native = file.mimeType === 'image/png' || file.mimeType === 'image/jpeg';
|
|
68
|
+
const source = native ? file.bytes : await andorraConvertImageBytesToPng(file.bytes);
|
|
69
|
+
if (!source)
|
|
70
|
+
throw undecodable();
|
|
71
|
+
const resized = await andorraResizeImage(source, native ? file.mimeType : 'image/png', {
|
|
72
|
+
maxWidth: READ_IMAGE_MAX_EDGE, maxHeight: READ_IMAGE_MAX_EDGE,
|
|
73
|
+
// The resize bound is on base64 length.
|
|
74
|
+
maxBytes: Math.floor(READ_IMAGE_MAX_BYTES / 3) * 4,
|
|
75
|
+
});
|
|
76
|
+
context.signal.throwIfAborted();
|
|
77
|
+
if (!resized || (resized.mimeType !== 'image/png' && resized.mimeType !== 'image/jpeg'))
|
|
78
|
+
throw undecodable();
|
|
79
|
+
const sentBytes = Math.floor(resized.data.length * 3 / 4);
|
|
80
|
+
if (budget && budget.bytes + sentBytes > READ_IMAGE_BATCH_BYTES)
|
|
81
|
+
throw new Error(`Image read budget reached (${formatBytes(READ_IMAGE_BATCH_BYTES)} of images per response); Read further images in a later turn.`);
|
|
82
|
+
if (budget)
|
|
83
|
+
budget.bytes += sentBytes;
|
|
84
|
+
const lines = [`Image file ${shownPath} (${file.mimeType}, ${resized.originalWidth}x${resized.originalHeight}, ${formatBytes(file.bytes.length)}) is attached to this result as an image.`];
|
|
85
|
+
if (resized.wasResized)
|
|
86
|
+
lines.push(`[Shown at ${resized.width}x${resized.height}; multiply coordinates by ${(resized.originalWidth / resized.width).toFixed(2)} to map them to the original.]`);
|
|
87
|
+
const output = lines.join('\n');
|
|
88
|
+
hold(output, { mimeType: resized.mimeType, data: resized.data });
|
|
89
|
+
staged = true;
|
|
90
|
+
return output;
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
// A read that produced no image hands its place back; bytes were never added for it.
|
|
94
|
+
if (!staged && budget)
|
|
95
|
+
budget.count--;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential material a user pastes beside a task is work order, not a label: it must never reach
|
|
3
|
+
* a naming model or a rail row. Redaction replaces a value a secret label introduces (`password is
|
|
4
|
+
* "x"`, `token: x`), a recognizable token shape, and a long unbroken run of key material with a
|
|
5
|
+
* placeholder — the label itself stays, so the text still reads as a summary of the ask. Model
|
|
6
|
+
* names, paths, and ordinary prose survive: they carry separators a key run does not.
|
|
7
|
+
*
|
|
8
|
+
* A labeled value is consumed in full regardless of its length: a three-character password is
|
|
9
|
+
* still a credential, and a tail left behind a length cap is still a leak. The cost of that is a
|
|
10
|
+
* garbled word in rare prose that uses the connector ("password is the problem"), which is
|
|
11
|
+
* preferable to the leak.
|
|
12
|
+
*/
|
|
13
|
+
export declare const redactSecrets: (text: string) => string;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential material a user pastes beside a task is work order, not a label: it must never reach
|
|
3
|
+
* a naming model or a rail row. Redaction replaces a value a secret label introduces (`password is
|
|
4
|
+
* "x"`, `token: x`), a recognizable token shape, and a long unbroken run of key material with a
|
|
5
|
+
* placeholder — the label itself stays, so the text still reads as a summary of the ask. Model
|
|
6
|
+
* names, paths, and ordinary prose survive: they carry separators a key run does not.
|
|
7
|
+
*
|
|
8
|
+
* A labeled value is consumed in full regardless of its length: a three-character password is
|
|
9
|
+
* still a credential, and a tail left behind a length cap is still a leak. The cost of that is a
|
|
10
|
+
* garbled word in rare prose that uses the connector ("password is the problem"), which is
|
|
11
|
+
* preferable to the leak.
|
|
12
|
+
*/
|
|
13
|
+
/** Words whose next value is treated as the secret itself. */
|
|
14
|
+
const SECRET_LABELS = String.raw `password|passwd|pwd|passcode|pass\s?phrase|secret|api[\s_-]?key|apikey|access[\s_-]?token|auth[\s_-]?token|client[\s_-]?secret|private[\s_-]?key|refresh[\s_-]?token|token`;
|
|
15
|
+
/** A value wrapped in any quote style the codebase sees pasted, with no length cap. A backslash
|
|
16
|
+
* inside the value escapes the next character, so an escaped quote (JSON's `\"`) is part of the
|
|
17
|
+
* value and does not end it: the whole credential is consumed, never a head alone. */
|
|
18
|
+
// A value may span lines (YAML and dotenv allow multiline quoted values), so it runs to its closing
|
|
19
|
+
// delimiter, and an escape may precede a line break. A doubled apostrophe inside a single-quoted
|
|
20
|
+
// value is YAML's escaped apostrophe, not the closing delimiter.
|
|
21
|
+
const SECRET_QUOTED = '"(?:[^"\\\\]|\\\\[^])*"|\'(?:[^\'\\\\]|\\\\[^]|\'\')*\'|`(?:[^`\\\\]|\\\\[^])*`|\u201c(?:[^\u201d\\\\]|\\\\[^])*\u201d|\u2018(?:[^\u2019\\\\]|\\\\[^])*\u2019';
|
|
22
|
+
// A credential whose key itself is quoted (`"password": "x"`, `'api_key': 'y'`, TOML `"token" = "x"`):
|
|
23
|
+
// the key and its separator stay so pasted JSON keeps its shape, and only the value is replaced. The
|
|
24
|
+
// unquoted alternative also covers a bare value after a quoted key (`"password": hunter2`).
|
|
25
|
+
const QUOTED_KEY = new RegExp('(["\'\u201c\u2018])([A-Za-z0-9_-]*?(?:' + SECRET_LABELS + '))(["\'\u201d\u2019])(\\s*[:=]\\s*)(' + SECRET_QUOTED + '|[^\\s,;}\\]]+)', 'gi');
|
|
26
|
+
// A label directly inside quotes is a quoted key the rule above owns — never a prose label — so the
|
|
27
|
+
// label rules below refuse labels that a quote character precedes; without that, the quoted-value
|
|
28
|
+
// pattern would mistake a JSON key's closing quote for the start of a quoted secret and leave the
|
|
29
|
+
// value behind (`{"password": "hunter2"}` redacted to `{"password[redacted]hunter2"}`). A backtick
|
|
30
|
+
// is not a key quote: Markdown inline code (`` `password=hunter2` ``) wraps an assignment, so it stays a label.
|
|
31
|
+
// A label backticked on its own (`` `password` and `foo` ``) is still a mentioned word, though: the
|
|
32
|
+
// second lookbehind refuses it so the span between two inline-code wrappers is never taken as a value.
|
|
33
|
+
const IN_QUOTE = '(?<!["\'\u201c\u2018])(?<!`(?=(?:' + SECRET_LABELS + ')`))';
|
|
34
|
+
// A connector is optional only in front of a quoted value: `password is "x"`, `token: x`, and
|
|
35
|
+
// `pass "x"` all redact, while `the access token used by the client` stays whole — a label with
|
|
36
|
+
// no value after it is prose about credentials, not credentials. Whitespace after the label is consumed
|
|
37
|
+
// once, then the connector and its own trailing whitespace: two adjacent `\s*` around an optional
|
|
38
|
+
// connector would repartition a long whitespace run quadratically.
|
|
39
|
+
// A label may end an environment-style name (`DB_PASSWORD=x`, `STRIPE_API_KEY: x`): an underscore or
|
|
40
|
+
// hyphen before it is a name prefix, not part of a longer word, so only a letter or digit refuses it.
|
|
41
|
+
const LABEL_START = '(?<![A-Za-z0-9])';
|
|
42
|
+
// A label a quote closes is a quoted key (`"db_password": "x"`) that QUOTED_KEY owns.
|
|
43
|
+
const KEY_CLOSE = '(?!["\'”’])';
|
|
44
|
+
const QUOTED_AFTER_LABEL = new RegExp(IN_QUOTE + LABEL_START + '(' + SECRET_LABELS + ')\\b' + KEY_CLOSE + '(\\s*(?:(?:is|are|=|:|\u2014|\u2013)\\s*)?)(' + SECRET_QUOTED + ')', 'gi');
|
|
45
|
+
// A YAML literal or folded block scalar (`password: |` / `token: >-`) carries the credential on the
|
|
46
|
+
// indented lines below the indicator; the whole indented block is the value, not the indicator alone.
|
|
47
|
+
// A header comment may follow the indicator (`password: | # deploy secret`).
|
|
48
|
+
const BLOCK_SCALAR_AFTER_LABEL = new RegExp(IN_QUOTE + LABEL_START + '(' + SECRET_LABELS + ')\\b' + KEY_CLOSE + '[ \\t]*:[ \\t]*[|>][+-]?[0-9]?[+-]?[ \\t]*(?:#[^\\r\\n]*)?(?:\\r?\\n[ \\t]+[^\\r\\n]*)+', 'gi');
|
|
49
|
+
const VALUE_AFTER_LABEL = new RegExp(IN_QUOTE + LABEL_START + '(' + SECRET_LABELS + ')\\b' + KEY_CLOSE + '\\s*(?:is|are|=|:)\\s*([^\\s"\'`\u201c\u201d\u2018\u2019]+)', 'gi');
|
|
50
|
+
/** Token shapes that are credentials even with no label around them. */
|
|
51
|
+
const TOKEN_SHAPES = /\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[0-9A-Z]{12,}|ASIA[0-9A-Z]{12,}|xox[baprs]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,})\b/g;
|
|
52
|
+
const BEARER = /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi;
|
|
53
|
+
// A long unbroken run of key material (hex or base64, no separators) is a secret even unlabeled;
|
|
54
|
+
// model names and paths carry separators, so they survive this cut.
|
|
55
|
+
const KEY_RUN = /[A-Za-z0-9+/=]{32,}/g;
|
|
56
|
+
export const redactSecrets = (text) => text
|
|
57
|
+
.replace(QUOTED_KEY, (_all, open, label, close, sep, value) => {
|
|
58
|
+
// In a code paste the value's quotes are syntax, not wrapping prose: keep them so the JSON
|
|
59
|
+
// (or TOML/YAML) still parses as a quoted string, with only the credential inside replaced.
|
|
60
|
+
const first = value.slice(0, 1), last = value.slice(-1);
|
|
61
|
+
const wrapped = value.length >= 2
|
|
62
|
+
&& ((first === '"' && last === '"') || (first === "'" && last === "'") || (first === '`' && last === '`')
|
|
63
|
+
|| (first === '\u201c' && last === '\u201d') || (first === '\u2018' && last === '\u2019'));
|
|
64
|
+
return `${open}${label}${close}${sep}${wrapped ? `${first}[redacted]${last}` : '[redacted]'}`;
|
|
65
|
+
})
|
|
66
|
+
.replace(QUOTED_AFTER_LABEL, (_all, label, gap) => `${label}${gap}[redacted]`)
|
|
67
|
+
.replace(BLOCK_SCALAR_AFTER_LABEL, (_all, label) => `${label}: [redacted]`)
|
|
68
|
+
.replace(VALUE_AFTER_LABEL, (_all, label) => `${label}: [redacted]`)
|
|
69
|
+
.replace(TOKEN_SHAPES, '[redacted]')
|
|
70
|
+
.replace(BEARER, 'Bearer [redacted]')
|
|
71
|
+
.replace(KEY_RUN, '[redacted]');
|