@runcanary/cli 0.1.27 → 0.1.29
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/canary.js +224 -194
- package/package.json +1 -1
package/dist/canary.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __canaryCreateRequire } from 'node:module';
|
|
3
3
|
const require = __canaryCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
4
|
+
var v6=Object.create;var _r=Object.defineProperty;var g6=Object.getOwnPropertyDescriptor;var y6=Object.getOwnPropertyNames;var w6=Object.getPrototypeOf,b6=Object.prototype.hasOwnProperty;var B2=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Z=(e,t)=>()=>(e&&(t=e(e=0)),t);var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ur=(e,t)=>{for(var n in t)_r(e,n,{get:t[n],enumerable:!0})},k6=(e,t,n,q)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of y6(t))!b6.call(e,r)&&r!==n&&_r(e,r,{get:()=>t[r],enumerable:!(q=g6(t,r))||q.enumerable});return e};var z6=(e,t,n)=>(n=e!=null?v6(w6(e)):{},k6(t||!e||!e.__esModule?_r(n,"default",{value:e,enumerable:!0}):n,e));var O,g=Z(()=>{O={".claude-plugin/marketplace.json":`{
|
|
5
5
|
"name": "runcanary",
|
|
6
6
|
"owner": { "name": "Canary", "url": "https://www.runcanary.ai" },
|
|
7
7
|
"description": "Canary's plugins for coding agents.",
|
|
@@ -15,7 +15,7 @@ var f6=Object.create;var _r=Object.defineProperty;var v6=Object.getOwnPropertyDe
|
|
|
15
15
|
}
|
|
16
16
|
`,"canary/.claude-plugin/plugin.json":`{
|
|
17
17
|
"name": "canary",
|
|
18
|
-
"version": "0.1.
|
|
18
|
+
"version": "0.1.29",
|
|
19
19
|
"description": "Runs Canary's checks that need your machine: a skill for your coding agent and a verifier that works in its own copy of the code.",
|
|
20
20
|
"author": {
|
|
21
21
|
"name": "Canary",
|
|
@@ -207,7 +207,8 @@ export function finalOf(report: Report): Final {
|
|
|
207
207
|
headline: report.verdict.startsWith('on ') ? \`Canary report \${report.verdict}\` : \`Canary report: \${report.verdict}\`,
|
|
208
208
|
pips: report.score?.pips ?? [],
|
|
209
209
|
score: report.score?.value ?? '',
|
|
210
|
-
|
|
210
|
+
// Why the score is what it is: the line under it; on a report from before that line, the caption beside it.
|
|
211
|
+
caption: report.score?.reading ?? report.score?.caption ?? null,
|
|
211
212
|
tally: tally?.kind === 'tally' ? tally.items.map(item => ({ mark: item.mark, text: item.text })) : [],
|
|
212
213
|
next: next?.kind === 'next' ? \`Next\${next.gain === null ? '' : \` \${next.gain}\`}: \${next.action}\` : null,
|
|
213
214
|
}
|
|
@@ -1323,12 +1324,15 @@ export function cardOf(report: Report, width: number): Card {
|
|
|
1323
1324
|
y += 18
|
|
1324
1325
|
const x = left + 15
|
|
1325
1326
|
const head = y + 13
|
|
1326
|
-
|
|
1327
|
+
// The steps to a 5 are numbered under their own label; Next alone is the one step.
|
|
1328
|
+
const numbered = next.label !== 'Next'
|
|
1329
|
+
const parts = [textAt(\`status \${five ? 'g' : 'y'}\`, T.status, x, head, next.label, LABEL)]
|
|
1327
1330
|
if (next.gain !== null) parts.push(textAt(\`ngain\${five ? ' win' : ''}\`, T.count, left + inner - 15, head, next.gain, { end: true, bold: true, base: baseline(T.status, head) }))
|
|
1328
|
-
const pieces: [Token[], Style, string][] = [[tokens(runs(next.action), T.next), T.next, 'nact']]
|
|
1331
|
+
const pieces: [Token[], Style, string][] = [[tokens(numbered ? [{ text: '1. ' }, ...runs(next.action)] : runs(next.action), T.next), T.next, 'nact']]
|
|
1329
1332
|
if (next.agent !== null) pieces.push([tokens([{ text: '\u21B3 ' }, ...runs(next.agent)], T.agent), T.agent, 'nagent'])
|
|
1330
1333
|
if (next.cost !== null) pieces.push([tokens(runs(next.cost), T.how), T.how, 'ncost'])
|
|
1331
|
-
if (then !== null) pieces.push([tokens([{ text:
|
|
1334
|
+
if (then !== null && numbered) then.steps.forEach((step, index) => pieces.push([tokens([{ text: \`\${index + 2}. \` }, ...runs(step)], T.how), T.how, 'nthen']))
|
|
1335
|
+
else if (then !== null) pieces.push([tokens([{ text: 'then: ' }, ...joined(then.steps.map(step => runs(step)))], T.how), T.how, 'nthen'])
|
|
1332
1336
|
let at = head + T.status.line + 6
|
|
1333
1337
|
pieces.forEach(([line, style, cls], index) => {
|
|
1334
1338
|
if (index > 0) at += 4
|
|
@@ -1672,10 +1676,9 @@ function capOf(score: Score, state: State, reach: number | null, inner: number,
|
|
|
1672
1676
|
const scored = score.pips.filter(pip => pip !== '\u26AA').length
|
|
1673
1677
|
const unscored = scored === 0 && !/\\d/.test(value ?? '')
|
|
1674
1678
|
const gainTo = reach === null ? scored : Math.max(scored, Math.min(count, reach))
|
|
1675
|
-
// Only a red score was held down by something, so only a red one leaves its stop behind on a re-check.
|
|
1676
|
-
const before = score.before === null || !score.before.includes('\u{1F534}') ? null : score.before.filter(pip => pip !== '\u26AA').length
|
|
1677
1679
|
const labeled = score.caption === null ? null : /^([^:*\`]{1,24}):\\s+(.+)$/.exec(score.caption)
|
|
1678
|
-
|
|
1680
|
+
// What holds the score down is hung from where it stops: what is left to fix ("capped by" on a report from before).
|
|
1681
|
+
const capped = (labeled?.[1] === 'capped by' || /^\\d+ things? left to fix\\b/.test(score.reading ?? '')) && scored < count
|
|
1679
1682
|
const width = inner - NUMBER - 14
|
|
1680
1683
|
const cell = (width - (count - 1) * BAR.gap) / count
|
|
1681
1684
|
const at = (index: number) => index * (cell + BAR.gap)
|
|
@@ -1706,14 +1709,6 @@ function capOf(score: Score, state: State, reach: number | null, inner: number,
|
|
|
1706
1709
|
const stop = stopAt(scored)
|
|
1707
1710
|
parts.push(line(\`M\${px(stop + 2)} -4C\${px(stop + 3)} 14 \${px(stop - 2)} 32 \${px(stop - 0.5)} \${BAR.row + 3}\`, ' draw', fillEnd.toFixed(2)))
|
|
1708
1711
|
}
|
|
1709
|
-
if (before !== null && before < scored) {
|
|
1710
|
-
const stop = stopAt(before)
|
|
1711
|
-
parts.push(
|
|
1712
|
-
line(\`M\${px(stop + 3)} -2C\${px(stop + 3.5)} 5 \${px(stop + 1)} 11 \${px(stop + 1.6)} 17\`, ' old'),
|
|
1713
|
-
line(\`M\${px(stop - 0.5)} 32C\${px(stop - 1)} 38 \${px(stop - 3)} 43 \${px(stop - 4)} \${BAR.row + 1}\`, ' old'),
|
|
1714
|
-
)
|
|
1715
|
-
}
|
|
1716
|
-
|
|
1717
1712
|
const bar = x + NUMBER + 14
|
|
1718
1713
|
// 40 is the baseline that centers the 44px digits on the cells.
|
|
1719
1714
|
const svg = [
|
|
@@ -1722,7 +1717,8 @@ function capOf(score: Score, state: State, reach: number | null, inner: number,
|
|
|
1722
1717
|
]
|
|
1723
1718
|
let below = top + BAR.row
|
|
1724
1719
|
if (score.caption !== null) {
|
|
1725
|
-
|
|
1720
|
+
// Only what capped the score hangs from its stop; what else the score's line says ("1 skipped by you") starts under the bar.
|
|
1721
|
+
const hung = capped && labeled?.[1] === 'capped by' ? Math.max(0, Math.min(stopAt(scored) - 2, width - HANG_ROOM)) : 0
|
|
1726
1722
|
// Hung from its line while it reads in two lines there; a longer one starts under the bar's start instead.
|
|
1727
1723
|
const hang = labeled !== null && hung > 0 && lay(tokens(runs(labeled[2]!), T.whyBold), width - hung).length > 2 ? 0 : hung
|
|
1728
1724
|
below += 3
|
|
@@ -1747,10 +1743,9 @@ function capOf(score: Score, state: State, reach: number | null, inner: number,
|
|
|
1747
1743
|
below += T.note.line
|
|
1748
1744
|
}
|
|
1749
1745
|
if (score.reading !== null) {
|
|
1750
|
-
//
|
|
1751
|
-
const end = gainTo > scored ? width - (at(gainTo - 1) + cell) : null
|
|
1746
|
+
// Why the score is what it is, from the card's left edge under the score, the whole width to read in.
|
|
1752
1747
|
below += 4
|
|
1753
|
-
const reading = para(tokens(runs(score.reading), T.reading), T.reading, 'pen reading write',
|
|
1748
|
+
const reading = para(tokens(runs(score.reading), T.reading), T.reading, 'pen reading write', x, below, inner)
|
|
1754
1749
|
svg.push(reading.svg)
|
|
1755
1750
|
below += reading.lines * T.reading.line
|
|
1756
1751
|
}
|
|
@@ -1786,8 +1781,9 @@ function altOf(report: Report, groups: Group[], recheckDetails: (string | undefi
|
|
|
1786
1781
|
for (const block of report.blocks) if (block.kind === 'list') lines.push(\`\${block.label}: \${block.items.map(wordsOf).join(' \xB7 ')}\`)
|
|
1787
1782
|
for (const block of report.blocks) if (block.kind === 'text') lines.push(...block.lines.filter(line => !/^\\s*\\|?\\s*:?-{3,}/.test(line)).map(line => wordsOf(line.replace(/\\|/g, ' ').replace(/^\\s*[-*]\\s+/, '').trim())).filter(line => line !== ''))
|
|
1788
1783
|
for (const block of report.blocks) {
|
|
1789
|
-
if (block.kind === 'next') lines.push(
|
|
1790
|
-
if (block.kind === '
|
|
1784
|
+
if (block.kind === 'next' && block.label !== 'Next') lines.push(\`\${block.label}: 1. \${wordsOf(block.action)}\${block.gain === null ? '' : \` \${block.gain}\`}\`)
|
|
1785
|
+
else if (block.kind === 'next') lines.push([\`Next\${block.gain === null ? '' : \` \${block.gain}\`}: \${wordsOf(block.action)}\`, block.agent, block.cost].filter(piece => piece !== null).map(piece => wordsOf(piece!)).join(' \xB7 '))
|
|
1786
|
+
if (block.kind === 'then') lines.push(report.blocks.some(other => other.kind === 'next' && other.label !== 'Next') ? block.steps.map((step, index) => \`\${index + 2}. \${wordsOf(step)}\`).join(' \xB7 ') : \`then: \${block.steps.map(wordsOf).join(' \xB7 ')}\`)
|
|
1791
1787
|
}
|
|
1792
1788
|
for (const block of report.blocks) {
|
|
1793
1789
|
if (block.kind === 'note') {
|
|
@@ -2343,9 +2339,9 @@ export interface Score {
|
|
|
2343
2339
|
pips: Pip[]
|
|
2344
2340
|
/** "2/5", "\u2013/5". */
|
|
2345
2341
|
value: string
|
|
2346
|
-
/** What
|
|
2342
|
+
/** What the score's own line says beside it: an area's health, how many must-fixes the person skipped ("capped by: \u2026" on a report from before the line under it). */
|
|
2347
2343
|
caption: string | null
|
|
2348
|
-
/**
|
|
2344
|
+
/** The line under the score that says why it is what it is ("1 thing left to fix: \u2026"). */
|
|
2349
2345
|
reading: string | null
|
|
2350
2346
|
}
|
|
2351
2347
|
|
|
@@ -2368,8 +2364,8 @@ export type Block =
|
|
|
2368
2364
|
| { kind: 'shown'; items: { title: string; text: string }[] }
|
|
2369
2365
|
| { kind: 'open'; text: string }
|
|
2370
2366
|
| { kind: 'list'; mark: Pip | null; label: string; items: string[] }
|
|
2371
|
-
/** Next (D6): the step, where it lands, what the agent does, and what the other way costs. */
|
|
2372
|
-
| { kind: 'next'; mark: Pip | null; gain: string | null; action: string; agent: string | null; cost: string | null }
|
|
2367
|
+
/** Next (D6): the step, where it lands, what the agent does, and what the other way costs. Under "To reach a 5/5" it is the first of the numbered steps. */
|
|
2368
|
+
| { kind: 'next'; mark: Pip | null; gain: string | null; action: string; agent: string | null; cost: string | null; label: string }
|
|
2373
2369
|
/** The steps after Next (D9). */
|
|
2374
2370
|
| { kind: 'then'; steps: string[] }
|
|
2375
2371
|
| { kind: 'note'; pieces: string[] }
|
|
@@ -2391,8 +2387,9 @@ export interface Split {
|
|
|
2391
2387
|
|
|
2392
2388
|
// A change's report; an area's, which names the area; and an area's section after a change's report (AREAS.md, D28).
|
|
2393
2389
|
const HEADING = /^## (?:Canary report(?: on (.+?))?|In (.+?)):\\s*(.+?)\\s*$/
|
|
2394
|
-
// The caption after " \xB7 " may still be arriving: it is read as far as it has come.
|
|
2395
|
-
|
|
2390
|
+
// The caption after " \xB7 " may still be arriving: it is read as far as it has come. It is in italics on a report from
|
|
2391
|
+
// before the score's own line said why, and plain since ("1 skipped by you").
|
|
2392
|
+
const SCORE = /^###\\s+([\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA\uFE0F]+)(?:\\s+\u2192\\s+([\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA\uFE0F]+))?\\s+\\*\\*\\*(.+?)\\*\\*\\*(?:\\s+([^\xB7*\\s][^\xB7*]*?))?(?:\\s+\xB7(?:\\s+\\*?(.*?)\\*?)?)?\\s*$/u
|
|
2396
2393
|
const ITALIC_LINE = /^\\*(?!\\*)(.+)(?<!\\*)\\*$/
|
|
2397
2394
|
const LABELED = /^(?:([\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA\u{1F535}])\\s+)?\\*\\*([^*]+?):\\*\\*\\s+(.+)$/u
|
|
2398
2395
|
const SHARE = /^\`(Canary \xB7 [^\`]+)\`$/
|
|
@@ -2412,16 +2409,20 @@ const REVIEWED = /^\\*\\*(Reviewed(?: [\\d,]+ files?| the change| the area)?)(?:
|
|
|
2412
2409
|
*/
|
|
2413
2410
|
const NEXT = /^([\u{1F7E1}\u{1F7E2}])\\s+\\*\\*Next(?:\\s+(\u2192 [^:*]+?))?:\\*\\*\\s+(.+)$/u
|
|
2414
2411
|
const THEN = /^then:\\s+(.+)$/
|
|
2412
|
+
/** The steps to a 5, each with the score it gets to: "**To reach a 5/5:**", then "1. Fix both must-fixes \u2192 4/5". */
|
|
2413
|
+
export const TO_FIVE_LABEL = 'To reach a 5/5'
|
|
2414
|
+
const TO_FIVE = /^\\*\\*To reach a 5\\/5:\\*\\*$/
|
|
2415
|
+
const STEP = /^\\d+\\.\\s+(.+?)\\s+(\u2192 \\d\\/5)$/
|
|
2415
2416
|
/** A table's last row past its first three: "| **+2 more** | | In \`canary show 4d3c2b1a\` |". */
|
|
2416
2417
|
const MORE = /^\\*\\*\\+\\d+ more\\*\\*$/
|
|
2417
2418
|
/** One line under the findings (D31, D51): "- *<title>* \xB7 It failed when Canary ran it with \u2026". */
|
|
2418
2419
|
const SHOWN = /^- \\*(.+?)\\* \xB7 (.+)$/
|
|
2419
2420
|
|
|
2420
2421
|
/** Where each block sits in the report, in the order the server writes them. */
|
|
2421
|
-
const PLACE = { score: 1, reading: 2, reviewed: 3, tally: 4, read: 5, recheck: 6, findings: 7, shown: 8, open: 9, outside: 10, skipped: 10.5, next: 11, then: 12, footer: 13, share: 14 }
|
|
2422
|
+
const PLACE = { score: 1, reading: 2, reviewed: 3, tally: 4, read: 5, recheck: 6, findings: 7, shown: 8, open: 9, outside: 10, skipped: 10.5, next: 11, then: 12, climb: 12.5, footer: 13, share: 14 }
|
|
2422
2423
|
|
|
2423
2424
|
/** The server's own lists, by their labels, and where each sits: what a 5 proved sits where the findings would, and what the person skipped under what checks did outside them. */
|
|
2424
|
-
const LISTS: Record<string, number> = { Read: PLACE.read, 'Proven by running': PLACE.findings, 'Outside the checks': PLACE.outside, 'Skipped by you': PLACE.skipped }
|
|
2425
|
+
const LISTS: Record<string, number> = { Read: PLACE.read, 'Proven by running': PLACE.findings, 'Outside the checks': PLACE.outside, 'Skipped by you': PLACE.skipped, 'So far': PLACE.climb }
|
|
2425
2426
|
|
|
2426
2427
|
/** The line under a score one proof from 5, naming what is left (D10). */
|
|
2427
2428
|
const READING = /^one proof from \\d\\/5(?:: .+)?$/
|
|
@@ -2458,12 +2459,12 @@ const markedOf = (cell: string): Marked => {
|
|
|
2458
2459
|
}
|
|
2459
2460
|
|
|
2460
2461
|
/** Next's words: the action first, then what the agent does, and the other way's cost when it is set in italics. */
|
|
2461
|
-
function nextOf(mark: string, gain: string | undefined, said: string): Extract<Block, { kind: 'next' }> {
|
|
2462
|
+
function nextOf(mark: string, gain: string | undefined, said: string, label = 'Next'): Extract<Block, { kind: 'next' }> {
|
|
2462
2463
|
const pieces = said.split(' \xB7 ')
|
|
2463
2464
|
const last = pieces[pieces.length - 1]!
|
|
2464
2465
|
const cost = pieces.length > 1 && ITALIC_LINE.test(last) ? ITALIC_LINE.exec(last)![1]! : null
|
|
2465
2466
|
const middle = pieces.slice(1, cost === null ? undefined : -1)
|
|
2466
|
-
return { kind: 'next', mark: mark as Pip, gain: gain ?? null, action: pieces[0]!, agent: middle.length > 0 ? middle.join(' \xB7 ') : null, cost }
|
|
2467
|
+
return { kind: 'next', mark: mark as Pip, gain: gain ?? null, action: pieces[0]!, agent: middle.length > 0 ? middle.join(' \xB7 ') : null, cost, label }
|
|
2467
2468
|
}
|
|
2468
2469
|
|
|
2469
2470
|
/**
|
|
@@ -2540,6 +2541,20 @@ function read(block: string[], report: Report, place: number): number | null {
|
|
|
2540
2541
|
report.blocks.push({ kind: 'shown', items: shown.flatMap(line => (line === null ? [] : [{ title: line[1]!, text: line[2]! }])) })
|
|
2541
2542
|
return PLACE.shown
|
|
2542
2543
|
}
|
|
2544
|
+
if (TO_FIVE.test(first)) {
|
|
2545
|
+
// The first step is the one to take now, drawn as Next with the score it gets to; the rest follow it.
|
|
2546
|
+
// A last step still arriving is read as far as it has come; every one before it has to be whole.
|
|
2547
|
+
const lines = block.slice(1).map(line => line.trim())
|
|
2548
|
+
const read = lines.map((line, index) => STEP.exec(line) ?? (index === lines.length - 1 ? /^\\d+\\.\\s+(.+)$/.exec(line) : null))
|
|
2549
|
+
// Its number alone has nothing to draw yet.
|
|
2550
|
+
const steps = read[read.length - 1] === null ? read.slice(0, -1) : read
|
|
2551
|
+
if (place >= PLACE.next || steps.length === 0 || steps.some(step => step === null)) return null
|
|
2552
|
+
const [now, ...rest] = steps as RegExpExecArray[]
|
|
2553
|
+
report.blocks.push(nextOf('\u{1F7E1}', now![2], now![1]!, TO_FIVE_LABEL))
|
|
2554
|
+
if (rest.length === 0) return PLACE.next
|
|
2555
|
+
report.blocks.push({ kind: 'then', steps: rest.map(step => (step[2] === undefined ? step[1]! : \`\${step[1]!} \${step[2]}\`)) })
|
|
2556
|
+
return PLACE.then
|
|
2557
|
+
}
|
|
2543
2558
|
if (block.length !== 1) return null
|
|
2544
2559
|
const reviewed = REVIEWED.exec(first)
|
|
2545
2560
|
if (reviewed !== null) {
|
|
@@ -2607,6 +2622,11 @@ function read(block: string[], report: Report, place: number): number | null {
|
|
|
2607
2622
|
report.blocks.push({ kind: 'open', text: first })
|
|
2608
2623
|
return PLACE.open
|
|
2609
2624
|
}
|
|
2625
|
+
// The one plain line under the score says why it is what it is.
|
|
2626
|
+
if (place === PLACE.score && block.length === 1) {
|
|
2627
|
+
report.score!.reading = first
|
|
2628
|
+
return PLACE.reading
|
|
2629
|
+
}
|
|
2610
2630
|
return null
|
|
2611
2631
|
}
|
|
2612
2632
|
|
|
@@ -2821,52 +2841,52 @@ declare module 'claude-code' {
|
|
|
2821
2841
|
}
|
|
2822
2842
|
}
|
|
2823
2843
|
}
|
|
2824
|
-
`}});var
|
|
2844
|
+
`}});var _2=ft(Vr=>{g();var eq=class extends Error{constructor(t,n,q){super(q),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=t,this.nestedError=void 0}},Gr=class extends eq{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Vr.CommanderError=eq;Vr.InvalidArgumentError=Gr});var tq=ft(Yr=>{g();var{InvalidArgumentError:S6}=_2(),Jr=class{constructor(t,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,q)=>{if(!this.argChoices.includes(n))throw new S6(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,q):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function C6(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Yr.Argument=Jr;Yr.humanReadableArgName=C6});var Xr=ft(yi=>{g();var{humanReadableArgName:A6}=tq(),Kr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(t){let n=t.commands.filter(r=>!r._hidden),q=t._getHelpCommand();return q&&!q._hidden&&n.push(q),this.sortSubcommands&&n.sort((r,s)=>r.name().localeCompare(s.name())),n}compareOptions(t,n){let q=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return q(t).localeCompare(q(n))}visibleOptions(t){let n=t.options.filter(r=>!r.hidden),q=t._getHelpOption();if(q&&!q.hidden){let r=q.short&&t._findOption(q.short),s=q.long&&t._findOption(q.long);!r&&!s?n.push(q):q.long&&!s?n.push(t.createOption(q.long,q.description)):q.short&&!r&&n.push(t.createOption(q.short,q.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let n=[];for(let q=t.parent;q;q=q.parent){let r=q.options.filter(s=>!s.hidden);n.push(...r)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(n=>{n.description=n.description||t._argsDescription[n.name()]||""}),t.registeredArguments.find(n=>n.description)?t.registeredArguments:[]}subcommandTerm(t){let n=t.registeredArguments.map(q=>A6(q)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,n){return n.visibleCommands(t).reduce((q,r)=>Math.max(q,n.subcommandTerm(r).length),0)}longestOptionTermLength(t,n){return n.visibleOptions(t).reduce((q,r)=>Math.max(q,n.optionTerm(r).length),0)}longestGlobalOptionTermLength(t,n){return n.visibleGlobalOptions(t).reduce((q,r)=>Math.max(q,n.optionTerm(r).length),0)}longestArgumentTermLength(t,n){return n.visibleArguments(t).reduce((q,r)=>Math.max(q,n.argumentTerm(r).length),0)}commandUsage(t){let n=t._name;t._aliases[0]&&(n=n+"|"+t._aliases[0]);let q="";for(let r=t.parent;r;r=r.parent)q=r.name()+" "+q;return q+n+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let n=[];return t.argChoices&&n.push(`choices: ${t.argChoices.map(q=>JSON.stringify(q)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&n.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&n.push(`env: ${t.envVar}`),n.length>0?`${t.description} (${n.join(", ")})`:t.description}argumentDescription(t){let n=[];if(t.argChoices&&n.push(`choices: ${t.argChoices.map(q=>JSON.stringify(q)).join(", ")}`),t.defaultValue!==void 0&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),n.length>0){let q=`(${n.join(", ")})`;return t.description?`${t.description} ${q}`:q}return t.description}formatHelp(t,n){let q=n.padWidth(t,n),r=n.helpWidth||80,s=2,o=2;function i(u,p){if(p){let f=`${u.padEnd(q+o)}${p}`;return n.wrap(f,r-s,q+o)}return u}function a(u){return u.join(`
|
|
2825
2845
|
`).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${n.commandUsage(t)}`,""],c=n.commandDescription(t);c.length>0&&(l=l.concat([n.wrap(c,r,0),""]));let h=n.visibleArguments(t).map(u=>i(n.argumentTerm(u),n.argumentDescription(u)));h.length>0&&(l=l.concat(["Arguments:",a(h),""]));let d=n.visibleOptions(t).map(u=>i(n.optionTerm(u),n.optionDescription(u)));if(d.length>0&&(l=l.concat(["Options:",a(d),""])),this.showGlobalOptions){let u=n.visibleGlobalOptions(t).map(p=>i(n.optionTerm(p),n.optionDescription(p)));u.length>0&&(l=l.concat(["Global Options:",a(u),""]))}let m=n.visibleCommands(t).map(u=>i(n.subcommandTerm(u),n.subcommandDescription(u)));return m.length>0&&(l=l.concat(["Commands:",a(m),""])),l.join(`
|
|
2826
2846
|
`)}padWidth(t,n){return Math.max(n.longestOptionTermLength(t,n),n.longestGlobalOptionTermLength(t,n),n.longestSubcommandTermLength(t,n),n.longestArgumentTermLength(t,n))}wrap(t,n,q,r=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${s}]+`);if(t.match(o))return t;let i=n-q;if(i<r)return t;let a=t.slice(0,q),l=t.slice(q).replace(`\r
|
|
2827
2847
|
`,`
|
|
2828
2848
|
`),c=" ".repeat(q),d="\\s\u200B",m=new RegExp(`
|
|
2829
2849
|
|.{1,${i-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),u=l.match(m)||[];return a+u.map((p,f)=>p===`
|
|
2830
2850
|
`?"":(f>0?c:"")+p.trimEnd()).join(`
|
|
2831
|
-
`)}};
|
|
2851
|
+
`)}};yi.Help=Kr});var ts=ft(es=>{g();var{InvalidArgumentError:I6}=_2(),Qr=class{constructor(t,n){this.flags=t,this.description=n||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let q=T6(t);this.short=q.shortFlag,this.long=q.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(t,n){return this.defaultValue=t,this.defaultValueDescription=n,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let n=t;return typeof t=="string"&&(n={[t]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,n){return n===this.defaultValue||!Array.isArray(n)?[t]:n.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(n,q)=>{if(!this.argChoices.includes(n))throw new I6(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,q):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return R6(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Zr=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,q)=>{this.positiveOptions.has(q)&&this.dualOptions.add(q)})}valueFromOption(t,n){let q=n.attributeName();if(!this.dualOptions.has(q))return!0;let r=this.negativeOptions.get(q).presetArg,s=r!==void 0?r:!1;return n.negate===(s===t)}};function R6(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function T6(e){let t,n,q=e.split(/[ |,]+/);return q.length>1&&!/^[[<]/.test(q[1])&&(t=q.shift()),n=q.shift(),!t&&/^-[^-]$/.test(n)&&(t=n,n=void 0),{shortFlag:t,longFlag:n}}es.Option=Qr;es.DualOptions=Zr});var bi=ft(wi=>{g();function O6(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let q=0;q<=e.length;q++)n[q]=[q];for(let q=0;q<=t.length;q++)n[0][q]=q;for(let q=1;q<=t.length;q++)for(let r=1;r<=e.length;r++){let s=1;e[r-1]===t[q-1]?s=0:s=1,n[r][q]=Math.min(n[r-1][q]+1,n[r][q-1]+1,n[r-1][q-1]+s),r>1&&q>1&&e[r-1]===t[q-2]&&e[r-2]===t[q-1]&&(n[r][q]=Math.min(n[r][q],n[r-2][q-2]+1))}return n[e.length][t.length]}function E6(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");n&&(e=e.slice(2),t=t.map(o=>o.slice(2)));let q=[],r=3,s=.4;return t.forEach(o=>{if(o.length<=1)return;let i=O6(e,o),a=Math.max(e.length,o.length);(a-i)/a>s&&(i<r?(r=i,q=[o]):i===r&&q.push(o))}),q.sort((o,i)=>o.localeCompare(i)),n&&(q=q.map(o=>`--${o}`)),q.length>1?`
|
|
2832
2852
|
(Did you mean one of ${q.join(", ")}?)`:q.length===1?`
|
|
2833
|
-
(Did you mean ${q[0]}?)`:""}
|
|
2834
|
-
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=t._name),(n.noHelp||n.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,n){return new
|
|
2835
|
-
Expecting one of '${q.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(n):this._lifeCycleHooks[t]=[n],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(t,n,q){this._exitCallback&&this._exitCallback(new rs(t,n,q)),m1.exit(t)}action(t){let n=q=>{let r=this.registeredArguments.length,s=q.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),t.apply(this,s)};return this._actionHandler=n,this}createOption(t,n){return new
|
|
2836
|
-
- already used by option '${n.flags}'`)}this.options.push(t)}_registerCommand(t){let n=r=>[r.name()].concat(r.aliases()),q=n(t).find(r=>this._findCommand(r));if(q){let r=n(this._findCommand(q)).join("|"),s=n(t).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),q=t.attributeName();if(t.negate){let s=t.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(q,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(q,t.defaultValue,"default");let r=(s,o,i)=>{s==null&&t.presetArg!==void 0&&(s=t.presetArg);let a=this.getOptionValue(q);s!==null&&t.parseArg?s=this._callParseArg(t,s,a,o):s!==null&&t.variadic&&(s=t._concatValue(s,a)),s==null&&(t.negate?s=!1:t.isBoolean()||t.optional?s=!0:s=""),this.setOptionValueWithSource(q,s,i)};return this.on("option:"+n,s=>{let o=`error: option '${t.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),t.envVar&&this.on("optionEnv:"+n,s=>{let o=`error: option '${t.flags}' value '${s}' from env '${t.envVar}' is invalid.`;r(s,o,"env")}),this}_optionEx(t,n,q,r,s){if(typeof n=="object"&&n instanceof
|
|
2853
|
+
(Did you mean ${q[0]}?)`:""}wi.suggestSimilar=E6});var Ci=ft(Si=>{g();var N6=B2("node:events").EventEmitter,ns=B2("node:child_process"),Te=B2("node:path"),qs=B2("node:fs"),m1=B2("node:process"),{Argument:P6,humanReadableArgName:j6}=tq(),{CommanderError:rs}=_2(),{Help:M6}=Xr(),{Option:ki,DualOptions:L6}=ts(),{suggestSimilar:zi}=bi(),ss=class e extends N6{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:n=>m1.stdout.write(n),writeErr:n=>m1.stderr.write(n),getOutHelpWidth:()=>m1.stdout.isTTY?m1.stdout.columns:void 0,getErrHelpWidth:()=>m1.stderr.isTTY?m1.stderr.columns:void 0,outputError:(n,q)=>q(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let n=this;n;n=n.parent)t.push(n);return t}command(t,n,q){let r=n,s=q;typeof r=="object"&&r!==null&&(s=r,r=null),s=s||{};let[,o,i]=t.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return r&&(a.description(r),a._executableHandler=!0),s.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(s.noHelp||s.hidden),a._executableFile=s.executableFile||null,i&&a.arguments(i),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),r?this:a}createCommand(t){return new e(t)}createHelp(){return Object.assign(new M6,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,n){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
2854
|
+
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=t._name),(n.noHelp||n.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,n){return new P6(t,n)}argument(t,n,q,r){let s=this.createArgument(t,n);return typeof q=="function"?s.default(r).argParser(q):s.default(q),this.addArgument(s),this}arguments(t){return t.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(t){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,n){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,q,r]=t.match(/([^ ]+) *(.*)/),s=n??"display help for command",o=this.createCommand(q);return o.helpOption(!1),r&&o.arguments(r),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(t,n){return typeof t!="object"?(this.helpCommand(t,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,n){let q=["preSubcommand","preAction","postAction"];if(!q.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
2855
|
+
Expecting one of '${q.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(n):this._lifeCycleHooks[t]=[n],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(t,n,q){this._exitCallback&&this._exitCallback(new rs(t,n,q)),m1.exit(t)}action(t){let n=q=>{let r=this.registeredArguments.length,s=q.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),t.apply(this,s)};return this._actionHandler=n,this}createOption(t,n){return new ki(t,n)}_callParseArg(t,n,q,r){try{return t.parseArg(n,q)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${r} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(t){let n=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(n){let q=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${q}'
|
|
2856
|
+
- already used by option '${n.flags}'`)}this.options.push(t)}_registerCommand(t){let n=r=>[r.name()].concat(r.aliases()),q=n(t).find(r=>this._findCommand(r));if(q){let r=n(this._findCommand(q)).join("|"),s=n(t).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),q=t.attributeName();if(t.negate){let s=t.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(q,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(q,t.defaultValue,"default");let r=(s,o,i)=>{s==null&&t.presetArg!==void 0&&(s=t.presetArg);let a=this.getOptionValue(q);s!==null&&t.parseArg?s=this._callParseArg(t,s,a,o):s!==null&&t.variadic&&(s=t._concatValue(s,a)),s==null&&(t.negate?s=!1:t.isBoolean()||t.optional?s=!0:s=""),this.setOptionValueWithSource(q,s,i)};return this.on("option:"+n,s=>{let o=`error: option '${t.flags}' argument '${s}' is invalid.`;r(s,o,"cli")}),t.envVar&&this.on("optionEnv:"+n,s=>{let o=`error: option '${t.flags}' value '${s}' from env '${t.envVar}' is invalid.`;r(s,o,"env")}),this}_optionEx(t,n,q,r,s){if(typeof n=="object"&&n instanceof ki)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,q);if(o.makeOptionMandatory(!!t.mandatory),typeof r=="function")o.default(s).argParser(r);else if(r instanceof RegExp){let i=r;r=(a,l)=>{let c=i.exec(a);return c?c[0]:l},o.default(s).argParser(r)}else o.default(r);return this.addOption(o)}option(t,n,q,r){return this._optionEx({},t,n,q,r)}requiredOption(t,n,q,r){return this._optionEx({mandatory:!0},t,n,q,r)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,n){return this.setOptionValueWithSource(t,n,void 0)}setOptionValueWithSource(t,n,q){return this._storeOptionsAsProperties?this[t]=n:this._optionValues[t]=n,this._optionValueSources[t]=q,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let n;return this._getCommandAndAncestors().forEach(q=>{q.getOptionValueSource(t)!==void 0&&(n=q.getOptionValueSource(t))}),n}_prepareUserArgs(t,n){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},t===void 0&&n.from===void 0){m1.versions?.electron&&(n.from="electron");let r=m1.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(n.from="eval")}t===void 0&&(t=m1.argv),this.rawArgs=t.slice();let q;switch(n.from){case void 0:case"node":this._scriptPath=t[1],q=t.slice(2);break;case"electron":m1.defaultApp?(this._scriptPath=t[1],q=t.slice(2)):q=t.slice(1);break;case"user":q=t.slice(0);break;case"eval":q=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",q}parse(t,n){let q=this._prepareUserArgs(t,n);return this._parseCommand([],q),this}async parseAsync(t,n){let q=this._prepareUserArgs(t,n);return await this._parseCommand([],q),this}_executeSubCommand(t,n){n=n.slice();let q=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(c,h){let d=Te.resolve(c,h);if(qs.existsSync(d))return d;if(r.includes(Te.extname(h)))return;let m=r.find(u=>qs.existsSync(`${d}${u}`));if(m)return`${d}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,i=this._executableDir||"";if(this._scriptPath){let c;try{c=qs.realpathSync(this._scriptPath)}catch{c=this._scriptPath}i=Te.resolve(Te.dirname(c),i)}if(i){let c=s(i,o);if(!c&&!t._executableFile&&this._scriptPath){let h=Te.basename(this._scriptPath,Te.extname(this._scriptPath));h!==this._name&&(c=s(i,`${h}-${t._name}`))}o=c||o}q=r.includes(Te.extname(o));let a;m1.platform!=="win32"?q?(n.unshift(o),n=xi(m1.execArgv).concat(n),a=ns.spawn(m1.argv[0],n,{stdio:"inherit"})):a=ns.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=xi(m1.execArgv).concat(n),a=ns.spawn(m1.execPath,n,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{m1.on(h,()=>{a.killed===!1&&a.exitCode===null&&a.kill(h)})});let l=this._exitCallback;a.on("close",c=>{c=c??1,l?l(new rs(c,"commander.executeSubCommandAsync","(close)")):m1.exit(c)}),a.on("error",c=>{if(c.code==="ENOENT"){let h=i?`searched for local subcommand relative to directory '${i}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${o}' does not exist
|
|
2837
2857
|
- if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2838
2858
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2839
2859
|
- ${h}`;throw new Error(d)}else if(c.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)m1.exit(1);else{let h=new rs(1,"commander.executeSubCommandAsync","(error)");h.nestedError=c,l(h)}}),this.runningCommand=a}_dispatchSubcommand(t,n,q){let r=this._findCommand(t);r||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,n.concat(q));else return r._parseCommand(n,q)}),s}_dispatchHelpCommand(t){t||this.help();let n=this._findCommand(t);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,n)=>{t.required&&this.args[n]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(q,r,s)=>{let o=r;if(r!==null&&q.parseArg){let i=`error: command-argument value '${r}' is invalid for argument '${q.name()}'.`;o=this._callParseArg(q,r,s,i)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((q,r)=>{let s=q.defaultValue;q.variadic?r<this.args.length?(s=this.args.slice(r),q.parseArg&&(s=s.reduce((o,i)=>t(q,i,o),q.defaultValue))):s===void 0&&(s=[]):r<this.args.length&&(s=this.args[r],q.parseArg&&(s=t(q,s,q.defaultValue))),n[r]=s}),this.processedArgs=n}_chainOrCall(t,n){return t&&t.then&&typeof t.then=="function"?t.then(()=>n()):n()}_chainOrCallHooks(t,n){let q=t,r=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[n]!==void 0).forEach(s=>{s._lifeCycleHooks[n].forEach(o=>{r.push({hookedCommand:s,callback:o})})}),n==="postAction"&&r.reverse(),r.forEach(s=>{q=this._chainOrCall(q,()=>s.callback(s.hookedCommand,this))}),q}_chainOrCallSubCommandHook(t,n,q){let r=t;return this._lifeCycleHooks[q]!==void 0&&this._lifeCycleHooks[q].forEach(s=>{r=this._chainOrCall(r,()=>s(this,n))}),r}_parseCommand(t,n){let q=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(q.operands),n=q.unknown,this.args=t.concat(n),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),n);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,t,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(q.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{q.unknown.length>0&&this.unknownOption(q.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,t,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))r(),this._processArguments(),this.parent.emit(s,t,n);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,n);this.listenerCount("command:*")?this.emit("command:*",t,n):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(n=>n._name===t||n._aliases.includes(t))}_findOption(t){return this.options.find(n=>n.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(n=>{n.mandatory&&t.getOptionValue(n.attributeName())===void 0&&t.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(q=>{let r=q.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});t.filter(q=>q.conflictsWith.length>0).forEach(q=>{let r=t.find(s=>q.conflictsWith.includes(s.attributeName()));r&&this._conflictingOption(q,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let n=[],q=[],r=n,s=t.slice();function o(a){return a.length>1&&a[0]==="-"}let i=null;for(;s.length;){let a=s.shift();if(a==="--"){r===q&&r.push(a),r.push(...s);break}if(i&&!o(a)){this.emit(`option:${i.name()}`,a);continue}if(i=null,o(a)){let l=this._findOption(a);if(l){if(l.required){let c=s.shift();c===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,c)}else if(l.optional){let c=null;s.length>0&&!o(s[0])&&(c=s.shift()),this.emit(`option:${l.name()}`,c)}else this.emit(`option:${l.name()}`);i=l.variadic?l:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let l=this._findOption(`-${a[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,a.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let l=a.indexOf("="),c=this._findOption(a.slice(0,l));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,a.slice(l+1));continue}}if(o(a)&&(r=q),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&q.length===0){if(this._findCommand(a)){n.push(a),s.length>0&&q.push(...s);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){n.push(a),s.length>0&&n.push(...s);break}else if(this._defaultCommandName){q.push(a),s.length>0&&q.push(...s);break}}if(this._passThroughOptions){r.push(a),s.length>0&&r.push(...s);break}r.push(a)}return{operands:n,unknown:q}}opts(){if(this._storeOptionsAsProperties){let t={},n=this.options.length;for(let q=0;q<n;q++){let r=this.options[q].attributeName();t[r]=r===this._versionOptionName?this._version:this[r]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,n)=>Object.assign(t,n.opts()),{})}error(t,n){this._outputConfiguration.outputError(`${t}
|
|
2840
2860
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2841
2861
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
2842
|
-
`),this.outputHelp({error:!0}));let q=n||{},r=q.exitCode||1,s=q.code||"commander.error";this._exit(r,s,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m1.env){let n=t.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m1.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new
|
|
2843
|
-
`),this._exit(0,"commander.version",t)}),this}description(t,n){return t===void 0&&n===void 0?this._description:(this._description=t,n&&(this._argsDescription=n),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),t===n._name)throw new Error("Command alias can't be the same as its name");let q=this.parent?._findCommand(t);if(q){let r=[q.name()].concat(q.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${r}'`)}return n._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(n=>this.alias(n)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(q=>
|
|
2862
|
+
`),this.outputHelp({error:!0}));let q=n||{},r=q.exitCode||1,s=q.code||"commander.error";this._exit(r,s,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m1.env){let n=t.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m1.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new L6(this.options),n=q=>this.getOptionValue(q)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(q));this.options.filter(q=>q.implied!==void 0&&n(q.attributeName())&&t.valueFromOption(this.getOptionValue(q.attributeName()),q)).forEach(q=>{Object.keys(q.implied).filter(r=>!n(r)).forEach(r=>{this.setOptionValueWithSource(r,q.implied[r],"implied")})})}missingArgument(t){let n=`error: missing required argument '${t}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(t){let n=`error: option '${t.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let n=`error: required option '${t.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,n){let q=o=>{let i=o.attributeName(),a=this.getOptionValue(i),l=this.options.find(h=>h.negate&&i===h.attributeName()),c=this.options.find(h=>!h.negate&&i===h.attributeName());return l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg)?l:c||o},r=o=>{let i=q(o),a=i.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${i.envVar}'`:`option '${i.flags}'`},s=`error: ${r(t)} cannot be used with ${r(n)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let n="";if(t.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(i=>i.long).map(i=>i.long);r=r.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);n=zi(t,r)}let q=`error: unknown option '${t}'${n}`;this.error(q,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,q=n===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${q} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],n="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(s=>{r.push(s.name()),s.alias()&&r.push(s.alias())}),n=zi(t,r)}let q=`error: unknown command '${t}'${n}`;this.error(q,{code:"commander.unknownCommand"})}version(t,n,q){if(t===void 0)return this._version;this._version=t,n=n||"-V, --version",q=q||"output the version number";let r=this.createOption(n,q);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
2863
|
+
`),this._exit(0,"commander.version",t)}),this}description(t,n){return t===void 0&&n===void 0?this._description:(this._description=t,n&&(this._argsDescription=n),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),t===n._name)throw new Error("Command alias can't be the same as its name");let q=this.parent?._findCommand(t);if(q){let r=[q.name()].concat(q.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${r}'`)}return n._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(n=>this.alias(n)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(q=>j6(q));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=Te.basename(t,Te.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(t){t=t||{};let n={error:!!t.error},q;return n.error?q=r=>this._outputConfiguration.writeErr(r):q=r=>this._outputConfiguration.writeOut(r),n.write=t.write||q,n.command=this,n}outputHelp(t){let n;typeof t=="function"&&(n=t,t=void 0);let q=this._getHelpContext(t);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",q)),this.emit("beforeHelp",q);let r=this.helpInformation(q);if(n&&(r=n(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");q.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",q),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",q))}helpOption(t,n){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(t,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let n=m1.exitCode||0;n===0&&t&&typeof t!="function"&&t.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(t,n){let q=["beforeAll","before","after","afterAll"];if(!q.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
2844
2864
|
Expecting one of '${q.join("', '")}'`);let r=`${t}Help`;return this.on(r,s=>{let o;typeof n=="function"?o=n({error:s.error,command:s.command}):o=n,o&&s.write(`${o}
|
|
2845
|
-
`)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(r=>n.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
2846
|
-
`,{flag:"wx"}),()=>{
|
|
2847
|
-
`,{mode:384}),
|
|
2865
|
+
`)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(r=>n.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function xi(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let n,q="127.0.0.1",r="9229",s;return(s=t.match(/^(--inspect(-brk)?)$/))!==null?n=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=s[1],/^\d+$/.test(s[3])?r=s[3]:q=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=s[1],q=s[3],r=s[4]),n&&r!=="0"?`${n}=${q}:${parseInt(r)+1}`:t})}Si.Command=ss});var Ti=ft(oe=>{g();var{Argument:Ai}=tq(),{Command:os}=Ci(),{CommanderError:F6,InvalidArgumentError:Ii}=_2(),{Help:$6}=Xr(),{Option:Ri}=ts();oe.program=new os;oe.createCommand=e=>new os(e);oe.createOption=(e,t)=>new Ri(e,t);oe.createArgument=(e,t)=>new Ai(e,t);oe.Command=os;oe.Option=Ri;oe.Argument=Ai;oe.Help=$6;oe.CommanderError=F6;oe.InvalidArgumentError=Ii;oe.InvalidOptionArgumentError=Ii});import{execFileSync as D6}from"node:child_process";import{randomUUID as W6}from"node:crypto";import{chmodSync as H6,mkdirSync as ls,readFileSync as hs,renameSync as B6,rmSync as Mi,statSync as _6,writeFileSync as Li}from"node:fs";import{homedir as U6}from"node:os";import{dirname as Fi,join as cs}from"node:path";function G(){return process.env.CANARY_HOME||cs(U6(),".canary")}function ds(){return cs(G(),"config.json")}function $i(){let{config:e}=ms();if(e.installId&&Pi.test(e.installId))return e.installId;ji??=W6();let t=ji;try{P1(n=>n.installId&&Pi.test(n.installId)?n:{...n,installId:t})}catch{}return t}function K(){return ms().config}function Di(e){return K().repoFingerprints?.[e]}function Wi(e,t){try{P1(n=>({...n,repoFingerprints:{...n.repoFingerprints,[e]:t}}))}catch{}}function Bi(e){Hi=e}function _i(){return`${ds()}.lock`}function Q6(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Oe(e){try{let t=D6("ps",["-o","lstart=","-p",String(e)],{env:{...process.env,LC_ALL:"C"},encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=Date.parse(t);return Number.isFinite(n)?n:null}catch{return null}}function t7(e){let t;try{t=hs(us(e),"utf8").trim()}catch{return"unknown"}let[n,q]=t.split(" ").map(Number);if(!Number.isInteger(n)||n<=0||!Number.isFinite(q))return"unknown";try{process.kill(n,0)}catch(s){if(s.code==="ESRCH")return!1}let r=Oe(n);return r===null?!0:Math.abs(r-q)<=e7}function Gi(e){try{return hs(us(e),"utf8").trim()===Ui}catch{return!1}}function is(e){try{Mi(e,{recursive:!0,force:!0})}catch{}}function U2(e=_i(),t="the config lock"){let n=Date.now()+X6();for(;;)try{return ls(Fi(e),{recursive:!0,mode:448}),ls(e),Li(us(e),`${Ui}
|
|
2866
|
+
`,{flag:"wx"}),()=>{Gi(e)&&is(e)}}catch(q){if(q.code!=="EEXIST")throw q;let r=t7(e);if(r===!1){is(e);continue}if(r==="unknown")try{if(Date.now()-_6(e).mtimeMs>Y6){is(e);continue}}catch{}if(Date.now()>=n)throw new vt(`another canary process is holding ${t}`);Q6(K6)}}function G2(e,t,n){let q=U2(e,t);try{return n()}finally{q()}}function P1(e,t={}){let n=()=>{let{config:r,unreadable:s}=ms();if(s&&!t.overwriteUnreadable)return!1;let o=e(s?{}:r);if(!Gi(_i()))throw new vt("the config lock changed hands during the write");return n7(o),!0};if(as>0)return n();let q=U2();as+=1;try{return n()}finally{as-=1,q()}}function ms(){let e;try{e=hs(ds(),"utf8")}catch(t){return{config:{},unreadable:t.code!=="ENOENT"}}try{let t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?{config:{},unreadable:!0}:{config:t,unreadable:!1}}catch{return{config:{},unreadable:!0}}}function n7(e){let t=ds();ls(Fi(t),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;try{Li(n,JSON.stringify(e,null,2)+`
|
|
2867
|
+
`,{mode:384}),H6(n,384),B6(n,t)}catch(q){throw Mi(n,{force:!0}),q}}function Vi(){P1(({apiUrl:e,webUrl:t,installId:n,agentSkills:q,repoFingerprints:r,gate:s,hooks:o})=>({...e?{apiUrl:e}:{},...t?{webUrl:t}:{},...n?{installId:n}:{},...q!==void 0?{agentSkills:q}:{},...r?{repoFingerprints:r}:{},...s?{gate:s}:{},...o?{hooks:o}:{}}))}function Q(){return process.env.CANARY_TOKEN||K().token}function a1(){return process.env.CANARY_API_URL||K().apiUrl||G6}function Ee(){let e=process.env.CANARY_WEB_URL||K().webUrl;if(e)return e;let t=process.env.CANARY_API_URL||K().apiUrl;return t?t.replace("//api.","//www."):V6}var G6,V6,Pi,ji,vt,J6,Y6,K6,Hi,X6,us,Z6,Ui,e7,as,e1=Z(()=>{"use strict";g();G6="https://api.runcanary.ai",V6="https://www.runcanary.ai";Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ji=null;vt=class extends Error{constructor(t="another canary process is holding the config lock"){super(`${t}; run the command again`),this.name="ConfigLockError"}},J6=15e3,Y6=1e4,K6=20;X6=()=>Hi??(Number(process.env.CANARY_CONFIG_LOCK_WAIT_MS)||J6);us=e=>cs(e,"owner");Z6=Math.round(Date.now()-process.uptime()*1e3),Ui=`${process.pid} ${Z6}`,e7=3e3;as=0});function q7(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function r7(e,t,n){let q=e.split(/\r?\n/),r="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let i=q[o-1];i&&(r+=o.toString().padEnd(s," "),r+=": ",r+=i,r+=`
|
|
2848
2868
|
`,o===t&&(r+=" ".repeat(s+n+2),r+=`^
|
|
2849
|
-
`))}return r}var H,gt=Z(()=>{g();H=class e extends Error{line;column;codeblock;constructor(t,n){let[q,r]=
|
|
2869
|
+
`))}return r}var H,gt=Z(()=>{g();H=class e extends Error{line;column;codeblock;constructor(t,n){let[q,r]=q7(n.toml,n.ptr),s=r7(n.toml,q,r);super(`Invalid TOML document: ${t}
|
|
2850
2870
|
|
|
2851
|
-
${s}`,n),this.line=q,this.column=r,this.codeblock=s}static x(t,n,q){throw new e(t,{toml:n.s,ptr:q??n.p})}}});function
|
|
2852
|
-
`:n===102?o+="\f":n===114?o+="\r":n===101?o+="\x1B":n===34?o+='"':n===92?o+="\\":H.x("unrecognised escape sequence",e),i=e.p+1,a=0);else n!==32&&n!==9&&(a===2&&H.x("invalid escape: only line-ending whitespace may be escaped",e,i),a=!r&&n===92?1:0,i=e.p);H.x("unfinished string",e,t)}var ps=Z(()=>{g();gt();});var r7,G2,fs=Z(()=>{g();r7=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,G2=class e extends Date{#t=!1;#n=!1;#e=null;constructor(t,n,q){let r=!0,s=!0,o="Z",i;if(typeof t=="string")if(n)e:{if(n<3){if(+t.slice(11,13)>23){t="";break e}n===2?(o=null,t+="Z"):(i=t.charCodeAt(t.length-1))!==90&&i!==122&&(o=t.slice(t.length-6)),q&&(t=t.slice(0,10)+"T"+t.slice(11))}else n===4&&(t=+t.slice(0,2)>23?"":`0000-01-01T${t}Z`);r=n!==4,s=n!==3}else{let a=t.match(r7);a?(a[1]||(r=!1,t=`0000-01-01T${t}`),s=!!a[2],s&&t[10]===" "&&(t=t.replace(" ","T")),a[2]&&+a[2]>23?t="":(o=a[3]||null,!o&&s&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=r,this.#n=s,this.#e=o)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#e===null)return t.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return t;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(t,n="Z"){let q=new e(t);return q.#e=n,q}static wrapAsLocalDateTime(t){let n=new e(t);return n.#e=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#t=!1,n.#e=null,n}}});function X1(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function gs(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function J2(e,t){let n=e.p,q=e.s.charCodeAt(e.p);if(q===91||q===123){e.d--||H.x("document contains excessively nested structures. aborting.",e);let r=q===91?Ji(e):Vi(e);return e.d++,r}return q===34||q===39?tq(e):q===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&H.x("invalid value",e,n),e.p++,!0):q===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&H.x("invalid value",e,n),e.p++,!1):q===43||q===45?nq(e,e.p,e.s.charCodeAt(++e.p),44-q,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?s7(e,q,t):e.s.charCodeAt(e.p+2)===58?o7(e,q,t):nq(e,e.p,q,0,t)}function nq(e,t,n,q,r){let s=n,o=0,i=!1;if(s===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&H.x("invalid value",e,t),e.p++,(q||1)/0;if(s===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&H.x("invalid value",e,t),e.p++,NaN;if(s===48){if(++e.p>=e.s.length||gs(s=e.s.charCodeAt(e.p),r))return e.bi===!0?0n:0;if(!q){if(s===120)return vs(e,t,16,r);if(s===98)return vs(e,t,2,r);if(s===111)return vs(e,t,8,r)}s===46?o=2:s===101||s===69?o=4:H.x("illegal leading zero",e,t)}else X1(s)||H.x("invalid value",e,t);for(;++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!gs(s,r));)o||(o=1),s===95?(o&1||H.x("illegal underscore",e),o+=11,i=!0):o===1&&s===46?o=2:(o===1||o===3)&&(s===101||s===69)?o=4:o===4&&(s===43||s===45)||(X1(s)?o>9?o-=11:o&1||o++:H.x("illegal character in numeric literal",e));if(!o){let l=(n-48)*(q||1);return e.bi===!0?BigInt(l):l}o&1||H.x("unfinished numeric value",e,t);let a=e.s.slice(t,e.p);return i&&(a=a.replaceAll("_","")),o>1?parseFloat(a):Gi(e,a,10,t)}function vs(e,t,n,q){let r,s=1;for(;++e.p<e.s.length&&(r=e.s.charCodeAt(e.p),!gs(r,q));)r===95?(s&1&&H.x("illegal underscore",e),s=3):X1(r,n)?s&1&&s--:H.x("illegal character in numeric literal",e);s&1&&H.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);return s&&(o=o.replaceAll("_","")),Gi(e,o,n,t)}function Gi(e,t,n,q){if(e.bi!==!0)e:{let r=parseInt(t,n);if(!Number.isSafeInteger(r)){if(e.bi)break e;H.x("integer value cannot be represented losslessly",e,q)}return r}return BigInt(n===10?t:(n===2?"0b":n===8?"0o":"0x")+t)}function s7(e,t,n){let q=e.p++,r;if(!X1(t)||!X1(e.s.charCodeAt(e.p++))||!X1(e.s.charCodeAt(e.p++))||!X1(e.s.charCodeAt(e.p++)))return nq(e,e.p=q,t,0,n);if(e.p+=5,X1(e.s.charCodeAt(e.p++))||H.x("invalid date-time: date part is malformed",e,q),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(r=!0,!X1(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(q,e.p);return V2(e,o,3,!1,q)}if(e.s.charCodeAt(e.p+=3)!==58&&H.x("invalid date-time: time part is malformed",e,q),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;X1(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(q,++e.p);return V2(e,o,1,r,q,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(q,e.p+=6);return V2(e,o,1,r,q,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(q,e.p);return V2(e,s,2,r,q)}function o7(e,t,n){let q=e.p;if(!X1(t)||!X1(e.s.charCodeAt(++e.p)))return nq(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;X1(e.s.charCodeAt(++e.p)););let r=e.s.slice(q,e.p);return V2(e,r,4,!1,q)}function V2(e,t,n,q,r,s){if(e.ld){let o=new G2(t,n,q);return o.isValid()||H.x("invalid date",e,r),o}try{switch(s&&(t+=s),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){H.x(o instanceof Error?o.message:""+o,e,r)}}var ys=Z(()=>{g();ps();ws();gt();fs();});function i7(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&H.x("control characters are not allowed in comments",e)}}function me(e,t,n){let q;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((q=e.s.charCodeAt(e.p))===32||q===9||!t&&(q===10||q===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||q!==35)break;i7(e)}}var bs=Z(()=>{g();gt();});function qq(e,t=61){let n,q=0,r=[],s,o=e.s.charCodeAt(n=e.p);do{if(o===t)return q||H.x("unexpected end of key",e),q===1&&r.push(e.s.slice(s,e.p)),e.p++,r;o===46?(q||H.x("illegal empty bare key",e),q===1&&r.push(e.s.slice(s,e.p)),q=0):!q&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&H.x("illegal quoted key: multiline strings are not allowed",e),r.push(tq(e)),q=2,e.p--):o===32||o===9?q===1&&(r.push(e.s.slice(s,e.p)),q=2):q===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?H.x("illegal character in key",e):q||(q=1,s=e.p)}while(o=e.s.charCodeAt(++e.p));H.x("incomplete key-value: cannot find end of key",e,n)}function Vi(e){let t=e.p++,n=Object.create(null),q=new Set,r;for(;e.p<e.s.length;){if(me(e),(r=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,i=!1,a=e.p,l=qq(e);for(let h=0;h<l.length;h++){h&&(o=i?o[s]:o[s]=Object.create(null)),s=l[h],(i=Object.hasOwn(o,s))&&(typeof o[s]!="object"||q.has(o[s]))&&H.x("trying to redefine an already defined value",e,a);let d=s==="__proto__";if(e.uk&&(d||s==="constructor")){o=e.uk!==1&&H.x("document contains an unsafe property",e,a);break}!i&&d&&Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}i&&H.x("trying to redefine an already defined value",e,a),me(e,!0,!0);let c=J2(e,125);if(o&&typeof(o[s]=c)=="object"&&q.add(c),me(e),(r=e.s.charCodeAt(e.p++))===125)return n;r!==44&&H.x("expected comma or end of structure",e,e.p-1)}H.x("unfinished table",e,t)}function Ji(e){let t=e.p++,n=[],q;for(;e.p<e.s.length;){if(me(e),(q=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(J2(e,93)),me(e),(q=e.s.charCodeAt(e.p++))===93)return n;q!==44&&H.x("expected comma or end of structure",e,e.p-1)}H.x("unfinished array",e,t)}var ws=Z(()=>{g();ps();ys();bs();gt();});function Yi(e,t,n,q,r){let s=n,o=q,i,a=!1,l;for(let c=0;c<t.length;c++){if(c){if(s=a?s[i]:s[i]=Object.create(null),o=(l=o[i]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let h=s.length-1;s=s[h],o=o[h].c}}if(i=t[c],(a=Object.hasOwn(s,i))&&o[i]?.t===0&&o[i]?.d)return null;if(!a){let h=i==="__proto__";if(e.uk&&(h||i==="constructor"))return!1;h&&(Object.defineProperty(s,i,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,i,{enumerable:!0,configurable:!0,writable:!0})),o[i]={t:c<t.length-1&&r===2?3:r,d:!1,i:0,c:Object.create(null)}}}if(l=o[i],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,s[i]=[]),s[i].push(s=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,r===1)s=a?s[i]:s[i]=Object.create(null);else if(r===0&&a)return null;return[i,s,l.c]}function Ki(e,t,n){(t===null||e.uk===2)&&H.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function ks(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},q=Object.create(null),r=Object.create(null),s,o=!1,i=q,a=r;for(e.charCodeAt(0)===65279&&n.p++,me(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let l=e.charCodeAt(++n.p)===91;s=n.p+=+l,o=!1;let c=qq(n,93);l&&(e.charCodeAt(n.p)!==93&&H.x("expected end of table array declaration",n),n.p++);let h=Yi(n,c,q,r,l?2:1);h?(a=h[2],i=h[1]):(Ki(n,h,s),o=!0)}else{s=n.p;let l=qq(n),c=Yi(n,l,i,a,0);!c&&!o&&Ki(n,c,s),me(n,!0,!0);let h=J2(n,void 0);c&&!o&&(c[1][c[0]]=h)}me(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10)&&H.x("each key-value declaration must be followed by an end-of-line",n),me(n)}return q}var Xi=Z(()=>{g();ws();ys();bs();gt();});var gb,Qi=Z(()=>{g();gb=!!"".isWellFormed});var Zi=Z(()=>{g();Xi();Qi();fs();gt();});import{spawnSync as a7}from"node:child_process";import{createHash as l7,randomBytes as h7,randomUUID as c7}from"node:crypto";import{accessSync as xs,chmodSync as d7,chownSync as u7,closeSync as m7,constants as Ss,existsSync as p7,fstatSync as f7,lstatSync as r3,mkdirSync as v7,mkdtempSync as g7,openSync as y7,readFileSync as s3,readlinkSync as w7,realpathSync as e3,renameSync as b7,rmSync as Ue,statSync as rq,writeFileSync as Cs}from"node:fs";import{tmpdir as k7}from"node:os";import{basename as z7,delimiter as x7,dirname as sq,join as Yt,resolve as S7}from"node:path";function Kt(e){try{return{doc:ks(e,{integersAsBigInt:"asNeeded"})}}catch(t){let n=(t instanceof Error?t.message:String(t)).split(`
|
|
2853
|
-
`)[0].replace(/^Invalid TOML document:\s*/,"");return{problem:{line:t instanceof H?t.line:0,message:n}}}}function
|
|
2871
|
+
${s}`,n),this.line=q,this.column=r,this.codeblock=s}static x(t,n,q){throw new e(t,{toml:n.s,ptr:q??n.p})}}});function nq(e){let t=e.p,n=e.s.charCodeAt(e.p++),q=n,r=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);s&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o="",i=e.p,a=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))a=a&&3;else if(n<32&&n!==9||n===127)H.x("control characters are not allowed in strings",e);else if((!a||a===3)&&n===q&&(!s||e.s.charCodeAt(e.p+1)===q&&e.s.charCodeAt(e.p+2)===q)){if(s&&(e.s.charCodeAt(e.p+3)===q&&e.p++,e.s.charCodeAt(e.p+3)===q&&e.p++),!a){let l=e.s.slice(i,e.p);o=o?o+l:l}return e.p+=s?3:1,o}else if(!a)!r&&n===92&&(o+=e.s.slice(i,i=e.p),a=1);else if(a===1)if(n===120||n===117||n===85){let l=e.p++-1,c=0,h=n===120?2:n===117?4:8;for(let d=0;d<h;d++,e.p++){let m=e.s.charCodeAt(e.p),u=m>=48&&m<=57?m-48:m>=65&&m<=70?m-65+10:m>=97&&m<=102?m-97+10:-1;u<0&&H.x("invalid non-hex character in unicode escape",e),c=c<<4|u}(c<0||c>1114111||c>=55296&&c<=57343)&&H.x("invalid unicode escape",e,l),o+=String.fromCodePoint(c),i=e.p--,a=0}else s&&(n===32||n===9)?a=2:(n===98?o+="\b":n===116?o+=" ":n===110?o+=`
|
|
2872
|
+
`:n===102?o+="\f":n===114?o+="\r":n===101?o+="\x1B":n===34?o+='"':n===92?o+="\\":H.x("unrecognised escape sequence",e),i=e.p+1,a=0);else n!==32&&n!==9&&(a===2&&H.x("invalid escape: only line-ending whitespace may be escaped",e,i),a=!r&&n===92?1:0,i=e.p);H.x("unfinished string",e,t)}var ps=Z(()=>{g();gt();});var s7,V2,fs=Z(()=>{g();s7=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,V2=class e extends Date{#t=!1;#n=!1;#e=null;constructor(t,n,q){let r=!0,s=!0,o="Z",i;if(typeof t=="string")if(n)e:{if(n<3){if(+t.slice(11,13)>23){t="";break e}n===2?(o=null,t+="Z"):(i=t.charCodeAt(t.length-1))!==90&&i!==122&&(o=t.slice(t.length-6)),q&&(t=t.slice(0,10)+"T"+t.slice(11))}else n===4&&(t=+t.slice(0,2)>23?"":`0000-01-01T${t}Z`);r=n!==4,s=n!==3}else{let a=t.match(s7);a?(a[1]||(r=!1,t=`0000-01-01T${t}`),s=!!a[2],s&&t[10]===" "&&(t=t.replace(" ","T")),a[2]&&+a[2]>23?t="":(o=a[3]||null,!o&&s&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=r,this.#n=s,this.#e=o)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#e===null)return t.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return t;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(t,n="Z"){let q=new e(t);return q.#e=n,q}static wrapAsLocalDateTime(t){let n=new e(t);return n.#e=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#t=!1,n.#e=null,n}}});function X1(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function gs(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Y2(e,t){let n=e.p,q=e.s.charCodeAt(e.p);if(q===91||q===123){e.d--||H.x("document contains excessively nested structures. aborting.",e);let r=q===91?Ki(e):Yi(e);return e.d++,r}return q===34||q===39?nq(e):q===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&H.x("invalid value",e,n),e.p++,!0):q===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&H.x("invalid value",e,n),e.p++,!1):q===43||q===45?qq(e,e.p,e.s.charCodeAt(++e.p),44-q,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?o7(e,q,t):e.s.charCodeAt(e.p+2)===58?i7(e,q,t):qq(e,e.p,q,0,t)}function qq(e,t,n,q,r){let s=n,o=0,i=!1;if(s===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&H.x("invalid value",e,t),e.p++,(q||1)/0;if(s===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&H.x("invalid value",e,t),e.p++,NaN;if(s===48){if(++e.p>=e.s.length||gs(s=e.s.charCodeAt(e.p),r))return e.bi===!0?0n:0;if(!q){if(s===120)return vs(e,t,16,r);if(s===98)return vs(e,t,2,r);if(s===111)return vs(e,t,8,r)}s===46?o=2:s===101||s===69?o=4:H.x("illegal leading zero",e,t)}else X1(s)||H.x("invalid value",e,t);for(;++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!gs(s,r));)o||(o=1),s===95?(o&1||H.x("illegal underscore",e),o+=11,i=!0):o===1&&s===46?o=2:(o===1||o===3)&&(s===101||s===69)?o=4:o===4&&(s===43||s===45)||(X1(s)?o>9?o-=11:o&1||o++:H.x("illegal character in numeric literal",e));if(!o){let l=(n-48)*(q||1);return e.bi===!0?BigInt(l):l}o&1||H.x("unfinished numeric value",e,t);let a=e.s.slice(t,e.p);return i&&(a=a.replaceAll("_","")),o>1?parseFloat(a):Ji(e,a,10,t)}function vs(e,t,n,q){let r,s=1;for(;++e.p<e.s.length&&(r=e.s.charCodeAt(e.p),!gs(r,q));)r===95?(s&1&&H.x("illegal underscore",e),s=3):X1(r,n)?s&1&&s--:H.x("illegal character in numeric literal",e);s&1&&H.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);return s&&(o=o.replaceAll("_","")),Ji(e,o,n,t)}function Ji(e,t,n,q){if(e.bi!==!0)e:{let r=parseInt(t,n);if(!Number.isSafeInteger(r)){if(e.bi)break e;H.x("integer value cannot be represented losslessly",e,q)}return r}return BigInt(n===10?t:(n===2?"0b":n===8?"0o":"0x")+t)}function o7(e,t,n){let q=e.p++,r;if(!X1(t)||!X1(e.s.charCodeAt(e.p++))||!X1(e.s.charCodeAt(e.p++))||!X1(e.s.charCodeAt(e.p++)))return qq(e,e.p=q,t,0,n);if(e.p+=5,X1(e.s.charCodeAt(e.p++))||H.x("invalid date-time: date part is malformed",e,q),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(r=!0,!X1(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(q,e.p);return J2(e,o,3,!1,q)}if(e.s.charCodeAt(e.p+=3)!==58&&H.x("invalid date-time: time part is malformed",e,q),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;X1(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(q,++e.p);return J2(e,o,1,r,q,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(q,e.p+=6);return J2(e,o,1,r,q,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(q,e.p);return J2(e,s,2,r,q)}function i7(e,t,n){let q=e.p;if(!X1(t)||!X1(e.s.charCodeAt(++e.p)))return qq(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;X1(e.s.charCodeAt(++e.p)););let r=e.s.slice(q,e.p);return J2(e,r,4,!1,q)}function J2(e,t,n,q,r,s){if(e.ld){let o=new V2(t,n,q);return o.isValid()||H.x("invalid date",e,r),o}try{switch(s&&(t+=s),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){H.x(o instanceof Error?o.message:""+o,e,r)}}var ys=Z(()=>{g();ps();ws();gt();fs();});function a7(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&H.x("control characters are not allowed in comments",e)}}function me(e,t,n){let q;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((q=e.s.charCodeAt(e.p))===32||q===9||!t&&(q===10||q===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||q!==35)break;a7(e)}}var bs=Z(()=>{g();gt();});function rq(e,t=61){let n,q=0,r=[],s,o=e.s.charCodeAt(n=e.p);do{if(o===t)return q||H.x("unexpected end of key",e),q===1&&r.push(e.s.slice(s,e.p)),e.p++,r;o===46?(q||H.x("illegal empty bare key",e),q===1&&r.push(e.s.slice(s,e.p)),q=0):!q&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&H.x("illegal quoted key: multiline strings are not allowed",e),r.push(nq(e)),q=2,e.p--):o===32||o===9?q===1&&(r.push(e.s.slice(s,e.p)),q=2):q===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?H.x("illegal character in key",e):q||(q=1,s=e.p)}while(o=e.s.charCodeAt(++e.p));H.x("incomplete key-value: cannot find end of key",e,n)}function Yi(e){let t=e.p++,n=Object.create(null),q=new Set,r;for(;e.p<e.s.length;){if(me(e),(r=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,i=!1,a=e.p,l=rq(e);for(let h=0;h<l.length;h++){h&&(o=i?o[s]:o[s]=Object.create(null)),s=l[h],(i=Object.hasOwn(o,s))&&(typeof o[s]!="object"||q.has(o[s]))&&H.x("trying to redefine an already defined value",e,a);let d=s==="__proto__";if(e.uk&&(d||s==="constructor")){o=e.uk!==1&&H.x("document contains an unsafe property",e,a);break}!i&&d&&Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}i&&H.x("trying to redefine an already defined value",e,a),me(e,!0,!0);let c=Y2(e,125);if(o&&typeof(o[s]=c)=="object"&&q.add(c),me(e),(r=e.s.charCodeAt(e.p++))===125)return n;r!==44&&H.x("expected comma or end of structure",e,e.p-1)}H.x("unfinished table",e,t)}function Ki(e){let t=e.p++,n=[],q;for(;e.p<e.s.length;){if(me(e),(q=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Y2(e,93)),me(e),(q=e.s.charCodeAt(e.p++))===93)return n;q!==44&&H.x("expected comma or end of structure",e,e.p-1)}H.x("unfinished array",e,t)}var ws=Z(()=>{g();ps();ys();bs();gt();});function Xi(e,t,n,q,r){let s=n,o=q,i,a=!1,l;for(let c=0;c<t.length;c++){if(c){if(s=a?s[i]:s[i]=Object.create(null),o=(l=o[i]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let h=s.length-1;s=s[h],o=o[h].c}}if(i=t[c],(a=Object.hasOwn(s,i))&&o[i]?.t===0&&o[i]?.d)return null;if(!a){let h=i==="__proto__";if(e.uk&&(h||i==="constructor"))return!1;h&&(Object.defineProperty(s,i,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,i,{enumerable:!0,configurable:!0,writable:!0})),o[i]={t:c<t.length-1&&r===2?3:r,d:!1,i:0,c:Object.create(null)}}}if(l=o[i],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,s[i]=[]),s[i].push(s=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,r===1)s=a?s[i]:s[i]=Object.create(null);else if(r===0&&a)return null;return[i,s,l.c]}function Qi(e,t,n){(t===null||e.uk===2)&&H.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function ks(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},q=Object.create(null),r=Object.create(null),s,o=!1,i=q,a=r;for(e.charCodeAt(0)===65279&&n.p++,me(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let l=e.charCodeAt(++n.p)===91;s=n.p+=+l,o=!1;let c=rq(n,93);l&&(e.charCodeAt(n.p)!==93&&H.x("expected end of table array declaration",n),n.p++);let h=Xi(n,c,q,r,l?2:1);h?(a=h[2],i=h[1]):(Qi(n,h,s),o=!0)}else{s=n.p;let l=rq(n),c=Xi(n,l,i,a,0);!c&&!o&&Qi(n,c,s),me(n,!0,!0);let h=Y2(n,void 0);c&&!o&&(c[1][c[0]]=h)}me(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10)&&H.x("each key-value declaration must be followed by an end-of-line",n),me(n)}return q}var Zi=Z(()=>{g();ws();ys();bs();gt();});var wb,e3=Z(()=>{g();wb=!!"".isWellFormed});var t3=Z(()=>{g();Zi();e3();fs();gt();});import{spawnSync as l7}from"node:child_process";import{createHash as h7,randomBytes as c7,randomUUID as d7}from"node:crypto";import{accessSync as xs,chmodSync as u7,chownSync as m7,closeSync as p7,constants as Ss,existsSync as f7,fstatSync as v7,lstatSync as o3,mkdirSync as g7,mkdtempSync as y7,openSync as w7,readFileSync as i3,readlinkSync as b7,realpathSync as n3,renameSync as k7,rmSync as Ue,statSync as sq,writeFileSync as Cs}from"node:fs";import{tmpdir as z7}from"node:os";import{basename as x7,delimiter as S7,dirname as oq,join as Yt,resolve as C7}from"node:path";function Kt(e){try{return{doc:ks(e,{integersAsBigInt:"asNeeded"})}}catch(t){let n=(t instanceof Error?t.message:String(t)).split(`
|
|
2873
|
+
`)[0].replace(/^Invalid TOML document:\s*/,"");return{problem:{line:t instanceof H?t.line:0,message:n}}}}function I7(e){let t=e;for(let n=0;n<16;n++){let q;try{if(!o3(t).isSymbolicLink())return t;q=b7(t)}catch{return t}t=C7(oq(t),q)}throw new Error("its symlinks do not end anywhere")}function iq(e){let t;try{t=I7(e)}catch(c){return{unreadable:c.message}}let n=null,q=null;try{let c=w7(t,"r");try{q=A7(v7(c,{bigint:!0})),n=i3(c)}finally{p7(c)}}catch(c){let h=c.code;if(h!=="ENOENT")return{unreadable:`it cannot be read (${h??"error"})`};n=null,q=null}let r="";if(n)try{r=R7.decode(n)}catch{return{unreadable:"it is not UTF-8 text, which TOML requires"}}let s=r.startsWith("\uFEFF"),o=s?r.slice(1):r,i=o.indexOf(`
|
|
2854
2874
|
`),a=i>0&&o[i-1]==="\r"?`\r
|
|
2855
2875
|
`:`
|
|
2856
|
-
`,l=n?Kt(o):{doc:{}};return{path:e,target:t,raw:n,identity:q,dangling:!n&&t!==e,text:o,bom:s,eol:a,doc:"doc"in l?l.doc:null,problem:"problem"in l?l.problem:null}}function pe(e){return e===void 0?"undefined":e instanceof Date?`{"$date":${JSON.stringify(e.toISOString())}}`:typeof e=="bigint"?`{"$int":"${e}"}`:typeof e=="number"&&(!Number.isFinite(e)||Object.is(e,-0))?`{"$num":"${Object.is(e,-0)?"-0":String(e)}"}`:Array.isArray(e)?`[${e.map(pe).join(",")}]`:E1(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${pe(e[t])}`).join(",")}}`:JSON.stringify(e)}function
|
|
2876
|
+
`,l=n?Kt(o):{doc:{}};return{path:e,target:t,raw:n,identity:q,dangling:!n&&t!==e,text:o,bom:s,eol:a,doc:"doc"in l?l.doc:null,problem:"problem"in l?l.problem:null}}function pe(e){return e===void 0?"undefined":e instanceof Date?`{"$date":${JSON.stringify(e.toISOString())}}`:typeof e=="bigint"?`{"$int":"${e}"}`:typeof e=="number"&&(!Number.isFinite(e)||Object.is(e,-0))?`{"$num":"${Object.is(e,-0)?"-0":String(e)}"}`:Array.isArray(e)?`[${e.map(pe).join(",")}]`:E1(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${pe(e[t])}`).join(",")}}`:JSON.stringify(e)}function l3(e,t,n=[]){return E1(e)&&E1(t)?[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(q=>l3(e[q],t[q],[...n,q])):pe(e)===pe(t)?[]:[{path:n,a:e,b:t}]}function K2(e){let t=[],n=0;for(;n<e.length;){let q=e.indexOf(`
|
|
2857
2877
|
`,n);if(q<0){t.push({content:e.slice(n),eol:""});break}let r=q>n&&e[q-1]==="\r";t.push({content:e.slice(n,r?q-1:q),eol:r?`\r
|
|
2858
2878
|
`:`
|
|
2859
|
-
`}),n=q+1}return t}function
|
|
2879
|
+
`}),n=q+1}return t}function h3(e,t){let n=e.filter((q,r)=>r!==t);return t===e.length-1&&!e[t].eol&&t>0&&(n[t-1]={...n[t-1],eol:""}),As(n)}function j7(e,t){if(!e.doc)return null;let n=t[t.length-1],q=new RegExp(`(?:^|[\\s.{,])${aq(n)}[ \\t]*=`),r=pe(q3(e.doc,t)),s=K2(e.text);for(let[o,i]of s.entries()){if(!q.test(i.content))continue;let a=Kt(h3(s,o));if("doc"in a&&pe(q3(a.doc,t))!==r)return o+1}return null}function q3(e,t){let n=e;for(let q of t){if(!E1(n))return;n=n[q]}return n}function M7(e){let t=e.doc;if(!t)return[];let n=[],q=(r,s,o)=>{if(E1(r))for(let i of["hooks","codex_hooks"])i in r&&n.push({key:i,value:r[i],profile:o,line:j7(e,[...s,i])})};if(q(t.features,["features"],null),E1(t.profiles))for(let[r,s]of Object.entries(t.profiles))E1(s)&&q(s.features,["profiles",r,"features"],r);return n}function L7(e){if(!e.doc)return{refused:"it does not parse as TOML"};if(!e.raw)return{text:`[features]
|
|
2860
2880
|
${j1}
|
|
2861
2881
|
`,line:2,added:`[features]
|
|
2862
2882
|
${j1}
|
|
2863
|
-
`,shape:"new_file"};let t=pe(
|
|
2864
|
-
`)?`${i}[features]${i}${j1}${i}`:`${i}${i}[features]${i}${j1}`:`[features]${i}${j1}${i}`;s.push({text:o+a,line:
|
|
2865
|
-
`)[0]||`it exited ${a.status}`}:l?{key:l[1],on:l[2]==="true"}:{why:"it lists no hooks feature"}}catch(i){o={why:i.message}}finally{Ue(s,{recursive:!0,force:!0})}return
|
|
2866
|
-
`).length-1,
|
|
2867
|
-
`,{flag:"wx",mode:q===null?384:
|
|
2883
|
+
`,shape:"new_file"};let t=pe(T7(e.doc)),n=c=>{let h=Kt(c);return"doc"in h&&pe(h.doc)===t},q=K2(e.text),r=(c,h,d)=>{let m=As(q.slice(0,c+1)),u=As(q.slice(c+1)),p=q[c].eol?h+q[c].eol:e.eol+h;return{text:m+p+u,line:c+2,added:p,shape:d}},s=[];if(E1(e.doc.features)){for(let[c,h]of q.entries())E7.test(h.content)&&s.push(r(c,j1,"under_header"));for(let[c,h]of q.entries())N7.test(h.content)&&s.push(r(c,X2,"dotted"))}let o=e.text,i=e.eol,a=o?/\n\s*\n$/.test(o)?`[features]${i}${j1}${i}`:o.endsWith(`
|
|
2884
|
+
`)?`${i}[features]${i}${j1}${i}`:`${i}${i}[features]${i}${j1}`:`[features]${i}${j1}${i}`;s.push({text:o+a,line:O7(o+a.slice(0,a.indexOf(j1)))+1,added:a,shape:"new_table"});for(let c of s)if(n(c.text))return c;let l=q.findIndex(c=>P7.test(c.content));return l>=0?{inline:!0,refused:`Codex's features are an inline \`features = { \u2026 }\` table (line ${l+1}), which TOML does not let another line add to: add \`codex_hooks = true\` inside it yourself`}:{refused:"no place for the line keeps the rest of the file meaning what it means now: add `codex_hooks = true` under `[features]` yourself"}}function c3(e,t){if(!e.raw)return null;if(!e.doc)return K2(e.text).some(a=>[j1,X2].includes(a.content.trim()))?{refused:`Codex can't load it (line ${e.problem?.line??"?"}: ${e.problem?.message??"invalid TOML"}), so Canary cannot tell its own line apart`}:null;let n=t&&t.file===e.target?t:null,q=e.text,r=e.doc,s=K2(q),o=[];for(let a=s.length-1;a>=0;a--){let l=s[a].content.trim();if(l!==j1&&l!==X2)continue;let c=h3(s,a),h=Kt(c);if(!("doc"in h))continue;let d=l3(r,h.doc);d.length!==1||d[0].path.join("\0")!=="features\0codex_hooks"||d[0].a!==!0||d[0].b!==void 0||(o.push(a+1),q=c,r=h.doc,s=K2(q))}if(!o.length)return null;let i=!1;if(n?.added.includes("[features]")&&E1(r.features)){let a=new Set([pe(r),...Object.keys(r.features).length?[]:[pe(Object.fromEntries(Object.entries(r).filter(([d])=>d!=="features")))]]),l=e.text.lastIndexOf(n.added),c=l<0?null:e.text.slice(0,l)+e.text.slice(l+n.added.length),h=c===null?null:Kt(c);c!==null&&h&&"doc"in h&&a.has(pe(h.doc))&&(q=c,i=!0)}return{text:n?.created&&!q.trim()?null:q,lines:o.sort((a,l)=>a-l),header:i}}function u3(e){if(e.dangling)return"it is a symlink to a file that does not exist";if(e.raw){let t;try{t=sq(e.target)}catch(n){return`it cannot be read (${n.code??"error"})`}if(t.nlink>1)return`it has ${t.nlink} hard links, and replacing it would split them apart`;if(typeof process.getuid=="function"&&t.uid!==process.getuid())return"it belongs to another user";try{xs(e.target,Ss.W_OK)}catch{return"it is read-only"}}try{xs(oq(e.target),Ss.W_OK)}catch{return`its folder (${oq(e.target)}) is read-only`}return null}function F7(e){let t;try{t=o3(e.target,{bigint:!0})}catch(n){return n.code==="ENOENT"&&e.raw===null}if(e.raw===null||!e.identity||!t.isFile()||t.dev!==e.identity.dev||t.ino!==e.identity.ino||t.nlink!==1n)return!1;try{return i3(e.target).equals(e.raw)}catch{return!1}}function Is(e,t,n){let q=u3(e);if(q)return{refused:q};let r=e.identity?e.identity.mode&4095:384,s=null;if(e.raw)try{g7(n,{recursive:!0,mode:448}),s=Yt(n,`codex-config.toml.${new Date().toISOString().replace(/[:.]/g,"-")}.${c7(3).toString("hex")}.bak`),Cs(s,e.raw,{flag:"wx",mode:384})}catch(i){return{refused:`no backup of it could be kept in ${n} (${i.code??"error"})`}}let o=Yt(oq(e.target),`.${x7(e.target)}.${d7()}.canary.tmp`);try{if(t!==null){if(Cs(o,Buffer.from((e.bom?"\uFEFF":"")+t,"utf8"),{flag:"wx",mode:r}),e.identity&&sq(o).gid!==e.identity.gid)try{m7(o,-1,e.identity.gid)}catch{}u7(o,r);let i=sq(o);if(e.identity&&(i.gid!==e.identity.gid||(i.mode&4095)!==r))return Ue(o,{force:!0}),s&&Ue(s,{force:!0}),{refused:"its group or permissions could not be kept on a replacement"}}return F7(e)?(t===null?Ue(e.target):k7(o,e.target),{backup:s}):(Ue(o,{force:!0}),s&&Ue(s,{force:!0}),{refused:"it changed while Canary was editing it",changed:!0})}catch(i){Ue(o,{force:!0}),s&&Ue(s,{force:!0});let a=i.code;return{refused:a==="EACCES"||a==="EPERM"||a==="EROFS"?`its folder cannot be written (${a})`:`it cannot be written (${a??"error"})`}}}function Rs(e=process.env,t=process.platform){let n=[],q=t==="win32"?["codex.cmd","codex.exe","codex"]:["codex"];e:for(let r of(e.PATH??"").split(S7).filter(Boolean))for(let s of q){let o=Yt(r,s);try{if(xs(o,Ss.X_OK),sq(o).isFile()){n.push(o);break e}}catch{}}return t==="darwin"&&f7(zs)&&!n.some(r=>$7(r,zs))&&n.push(zs),n}function $7(e,t){try{return n3(e)===n3(t)}catch{return e===t}}function s3(e,t,n){let q=`${e}\0${t?h7("sha256").update(t).digest("hex"):"-"}`,r=r3.get(q);if(r)return r;let s=y7(Yt(z7(),"canary-codex-")),o;try{t&&Cs(Yt(s,"config.toml"),t,{mode:384});let i=process.platform==="win32"&&/\.(cmd|bat)$/i.test(e),a=l7(i?`"${e}"`:e,["features","list"],{cwd:s,env:{...process.env,CODEX_HOME:s},encoding:"utf8",timeout:n,stdio:["ignore","pipe","pipe"],windowsHide:!0,shell:i}),l=/^(hooks|codex_hooks)\s.*?\s(true|false)\s*$/m.exec(a.stdout??"");o=a.error?{why:a.error.code==="ETIMEDOUT"?"it did not answer in time":a.error.message}:a.status!==0?{why:(a.stderr??"").trim().split(`
|
|
2885
|
+
`)[0]||`it exited ${a.status}`}:l?{key:l[1],on:l[2]==="true"}:{why:"it lists no hooks feature"}}catch(i){o={why:i.message}}finally{Ue(s,{recursive:!0,force:!0})}return r3.set(q,o),o}function W7(e,t,n){let q=e,r=n&&typeof n.profile=="string"&&E1(n.profiles)?n.profiles[n.profile]:void 0;for(let s of[n?.features,E1(r)?r.features:void 0])E1(s)&&(typeof s.codex_hooks=="boolean"&&(q=s.codex_hooks),t==="hooks"&&typeof s.hooks=="boolean"&&(q=s.hooks));return q}function m3(e,t=D7){return({raw:n,doc:q})=>{let r={answers:[],unanswered:[]};for(let s of e){let o=s3(s,n,t);if("key"in o){r.answers.push({binary:s,...o,derived:!1});continue}let i=n?s3(s,null,t):o;"key"in i?r.answers.push({binary:s,key:i.key,on:W7(i.on,i.key,q),derived:!0}):r.unanswered.push({binary:s,why:o.why})}return r}}function Ts(e,t){if("unreadable"in e)return{kind:"unreadable",why:e.unreadable};if(!e.doc)return{kind:"broken",problem:e.problem??{line:0,message:"invalid TOML"}};let{answers:n,unanswered:q}=t({raw:e.raw,doc:e.doc});if(n.length&&!q.length&&n.every(i=>i.on))return{kind:"on",answers:n};let r=M7(e).filter(i=>i.profile!==null||i.key==="codex_hooks"||i.value!==!0);if(r.length)return{kind:"person",settings:r,answers:n,unanswered:q};let s=L7(e);if("refused"in s)return{kind:"cannot",why:s.refused,answers:n,unanswered:q,...s.inline?{inline:!0}:{}};let o=u3(e);if(o)return{kind:"cannot",why:o,answers:n,unanswered:q,edit:s};if(n.length){let i=Buffer.from((e.bom?"\uFEFF":"")+s.text,"utf8"),a=t({raw:i,doc:Kt(s.text).doc}),l=(h,d)=>d.binary===h.binary&&(h.derived||!d.derived),c=n.filter(h=>!a.answers.some(d=>l(h,d)&&d.on));if(c.length)return{kind:"cannot",answers:n,unanswered:q,edit:s,why:a.answers.some(h=>l(c[0],h))?`Codex (${c[0].binary}) still reports its hooks off with the line added, so something outside this file switches them off`:`Codex (${c[0].binary}) could not load the file with the line added`}}return{kind:"edit",edit:s,answers:n,unanswered:q}}var a3,j1,X2,A7,E1,R7,T7,As,O7,aq,E7,N7,P7,lq,d3,zs,D7,r3,p3=Z(()=>{"use strict";g();t3();a3="# added by canary",j1=`codex_hooks = true ${a3}`,X2=`features.codex_hooks = true ${a3}`,A7=e=>({dev:e.dev,ino:e.ino,mode:Number(e.mode),uid:Number(e.uid),gid:Number(e.gid)}),E1=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Date);R7=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});T7=e=>({...e,features:{...E1(e.features)?e.features:{},codex_hooks:!0}});As=e=>e.map(t=>t.content+t.eol).join("");O7=e=>e.split(`
|
|
2886
|
+
`).length-1,aq=e=>`(?:${e}|"${e}"|'${e}')`,E7=new RegExp(`^[ \\t]*\\[[ \\t]*${aq("features")}[ \\t]*\\][ \\t]*(?:#.*)?$`),N7=new RegExp(`^[ \\t]*${aq("features")}[ \\t]*\\.`),P7=new RegExp(`^[ \\t]*${aq("features")}[ \\t]*=[ \\t]*\\{`);lq=e=>`${e.line?`line ${e.line}`:"a line"}: \`${e.key} = ${typeof e.value=="string"?JSON.stringify(e.value):String(e.value)}\`${e.profile!==null?` (profile "${e.profile}")`:""}`;d3=e=>Yt(e,"backups");zs="/Applications/ChatGPT.app/Contents/Resources/codex";D7=3e3,r3=new Map});import{accessSync as H7,constants as B7,existsSync as en,lstatSync as _7,readFileSync as hq,readlinkSync as U7,renameSync as G7,rmSync as f3,statSync as k3,writeFileSync as V7}from"node:fs";import{randomUUID as J7}from"node:crypto";import{homedir as Ns}from"node:os";import{delimiter as Y7,dirname as Os,join as we,resolve as K7}from"node:path";function dq(e,t=process.env,n=process.platform){let q=n==="win32"?[e,...(t.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(r=>e+r.toLowerCase())]:[e];for(let r of(t.PATH??"").split(Y7).filter(Boolean))for(let s of q)try{if(H7(we(r,s),B7.X_OK),k3(we(r,s)).isFile())return!0}catch{}return!1}function X7(e){let t=e;for(let n=0;n<16;n++){let q;try{if(!_7(t).isSymbolicLink())return t;q=U7(t)}catch{return t}t=K7(Os(t),q)}throw new fe("its symlinks do not end anywhere")}function Xt(e,t){for(let n=0;n<3;n++){let q;try{q=hq(e,"utf8")}catch(a){if(a.code!=="ENOENT")return{result:"refused",detail:"the file cannot be read"};q=null}let r={};if(q!==null&&q.trim())try{r=JSON.parse(q)}catch{return{result:"refused",detail:"the file is not valid JSON"}}if(!be(r))return{result:"refused",detail:"the file does not hold a JSON object"};try{if(!t(r))return{result:"unchanged"}}catch(a){if(a instanceof fe)return{result:"refused",detail:a.message};throw a}let s=q?/^([ \t]+)"/m.exec(q)?.[1]??" ":" ",o;try{o=X7(e)}catch(a){return{result:"refused",detail:a.message}}if(o!==e&&!en(Os(o)))return{result:"refused",detail:"it is a symlink into a folder that does not exist"};let i=we(Os(o),`.${J7()}.canary.tmp`);try{V7(i,JSON.stringify(r,null,s)+`
|
|
2887
|
+
`,{flag:"wx",mode:q===null?384:k3(o).mode&511});let a;try{a=hq(e,"utf8")}catch{a=null}if(a!==q){f3(i,{force:!0});continue}return G7(i,o),{result:"written"}}catch(a){return f3(i,{force:!0}),{result:"refused",detail:`the file cannot be written (${a.code??"error"})`}}}return{result:"refused",detail:"the file kept changing while it was being edited"}}function Z7(e,t,n){for(let q of e){if(!be(q))throw new fe(`its \`hooks.${t}\` list holds an entry that is not an object`);if(n&&q[n]!==void 0&&!(Array.isArray(q[n])&&q[n].every(be)))throw new fe(`its \`hooks.${t}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Ge(e,t,n,q="hooks"){if(e.hooks===void 0){if(!n)return null;e.hooks={}}if(!be(e.hooks))throw new fe("its `hooks` entry is not an object");if(e.hooks[t]===void 0){if(!n)return null;e.hooks[t]=[]}if(!Array.isArray(e.hooks[t]))throw new fe(`its \`hooks.${t}\` entry is not a list`);return Z7(e.hooks[t],t,q),e.hooks[t]}function z3(e,t){be(e.hooks)&&(Array.isArray(e.hooks[t])&&!e.hooks[t].length&&delete e.hooks[t],Object.keys(e.hooks).length||delete e.hooks)}function x3(e){let t;try{t=JSON.parse(hq(e,"utf8"))}catch(n){return n.code==="ENOENT"?{state:"missing"}:{state:"unreadable",detail:"the file cannot be read as JSON"}}return be(t)?{doc:t}:{state:"unreadable",detail:"the file does not hold a JSON object"}}function S3(e){let t=Q7(e.harness),n=Ps(e.harness),q=()=>({matcher:e.matcher,hooks:[{type:"command",command:t,timeout:cq}]}),r=a=>be(a)&&Array.isArray(a.hooks)&&a.hooks.some(n),s=a=>{let l=a.filter(r);return l.length===1&&JSON.stringify(l[0])===JSON.stringify(q())},o=a=>{let l=Ge(a,"PreToolUse",!1);if(!l)return!1;let c=!1;for(let h=l.length-1;h>=0;h--){let d=l[h];if(!be(d)||!Array.isArray(d.hooks))continue;let m=d.hooks.filter(u=>!n(u));m.length!==d.hooks.length&&(c=!0,m.length?d.hooks=m:l.splice(h,1))}return c&&z3(a,"PreToolUse"),c},i={harness:e.harness,file:e.file,summary:`a PreToolUse hook that runs \`${t}\` before shell and MCP tool calls (${cq} s limit)`,snippet:JSON.stringify({hooks:{PreToolUse:[q()]}},null,2)};return{detected:()=>en(e.dir),plan:()=>[i],install:()=>[{...i,...Xt(e.file,a=>s(Ge(a,"PreToolUse",!0))?!1:(o(a),Ge(a,"PreToolUse",!0).push(q()),!0))}],uninstall:()=>{if(!en(e.file))return[{...i,result:"unchanged"}];let a=Xt(e.file,o);return[{...i,...a.result==="written"?{result:"removed"}:a}]},status:()=>{let a=x3(e.file);if(!("doc"in a))return[{harness:e.harness,file:e.file,...a}];let l;try{l=Ge(a.doc,"PreToolUse",!1)}catch(c){return[{harness:e.harness,file:e.file,state:"unreadable",detail:c.message}]}return l?.some(r)?e.disabledKey&&a.doc[e.disabledKey]===!0?[{harness:e.harness,file:e.file,state:"disabled",detail:`\`${e.disabledKey}\` is set, so no hooks run`}]:s(l)?[{harness:e.harness,file:e.file,state:"registered"}]:[{harness:e.harness,file:e.file,state:"modified",detail:"the entry differs from what `canary hooks install` writes; install again to restore it"}]:[{harness:e.harness,file:e.file,state:"missing"}]}}}function e8(e){let t=we(e,"hooks.json"),n=Ps("cursor"),q=()=>({command:"canary hook cursor",timeout:cq}),r=i=>Q2.every(a=>{let l=(Ge(i,a,!1,null)??[]).filter(n);return l.length===1&&JSON.stringify(l[0])===JSON.stringify(q())}),s=i=>{let a=!1;for(let l of Q2){let c=Ge(i,l,!1,null);if(!c)continue;let h=c.filter(d=>!n(d));h.length!==c.length&&(a=!0,i.hooks[l]=h,z3(i,l))}return a},o={harness:"cursor",file:t,summary:`a command that runs \`canary hook cursor\` before shell commands and MCP tool calls (${cq} s limit)`,snippet:JSON.stringify({version:1,hooks:Object.fromEntries(Q2.map(i=>[i,[q()]]))},null,2)};return{detected:()=>en(e),plan:()=>[o],install:()=>[{...o,...Xt(t,i=>{if(i.version!==void 0&&i.version!==1)throw new fe(`it is version ${JSON.stringify(i.version)} of Cursor's hooks file, which this CLI does not know`);if(r(i))return!1;s(i),i.version===void 0&&(i.version=1);for(let a of Q2)Ge(i,a,!0,null).push(q());return!0})}],uninstall:()=>{if(!en(t))return[{...o,result:"unchanged"}];let i=Xt(t,s);return[{...o,...i.result==="written"?{result:"removed"}:i}]},status:()=>{let i=x3(t);if(!("doc"in i))return[{harness:"cursor",file:t,...i}];try{return Q2.some(a=>(Ge(i.doc,a,!1,null)??[]).some(n))?[r(i.doc)?{harness:"cursor",file:t,state:"registered"}:{harness:"cursor",file:t,state:"modified",detail:"the entries differ from what `canary hooks install` writes; install again to restore them"}]:[{harness:"cursor",file:t,state:"missing"}]}catch(a){return[{harness:"cursor",file:t,state:"unreadable",detail:a.message}]}}}}function n8(e=process.env){let t=e.CLAUDE_CONFIG_DIR||we(Ns(),".claude");return{id:"claude",label:"Claude Code",byDefault:!0,...S3({harness:"claude",dir:t,file:we(t,"settings.json"),matcher:t8,disabledKey:"disableAllHooks"})}}function q8(e=process.env,t=process.platform){let[n]=Rs(e,t);return n===void 0?null:/[\s"']/.test(n)?`"${n}"`:n}function s8(e,t,n){if("unreadable"in e||!e.doc)return null;let q=e.doc.hooks,r=E1(q)&&E1(q.state)?q.state[`${t}:pre_tool_use:${n}:0`]:void 0;return E1(r)&&typeof r.trusted_hash=="string"}function b3(e){let t=e.settings.filter(n=>n.value!==!0);return t.length?`Codex's hooks are switched off in its config.toml (${t.map(lq).join("; ")}); the check runs once they are on`:e.settings.every(n=>n.profile!==null)?`Codex's hooks are set only in ${[...new Set(e.settings.map(n=>`profile "${n.profile}"`))].join(" and ")} of its config.toml (${e.settings.map(lq).join("; ")}); the check runs only where they are on`:e.answers.some(n=>!n.on)?`${C3(e.answers)} reports its hooks off although its config.toml switches them on (${e.settings.map(lq).join("; ")}), so a setting outside that file switches them off`:null}function a8(e=process.env,t={}){let n=e.CODEX_HOME||we(Ns(),".codex"),q=we(n,"hooks.json"),r=S3({harness:"codex",dir:n,file:q,matcher:".*"}),s=we(n,"config.toml"),o=r8(q8(e)),i=t.ask??m3(Rs(e)),a=Ps("codex"),l=()=>d3(G()),c=()=>{try{return JSON.parse(hq(q,"utf8")).hooks.PreToolUse.findIndex(z=>be(z)&&Array.isArray(z.hooks)&&z.hooks.some(a))}catch{return-1}},h=()=>{let b=iq(s);return{read:b,verdict:Ts(b,i)}},d=()=>{try{return K().hooks?.codex??null}catch{return null}},m=b=>{try{P1(z=>{let{codex:C,...I}=z.hooks??{};return{...z,hooks:b?{...I,codex:b}:I}})}catch{}},u=(b,z)=>({harness:"codex",file:s,summary:`the line \`${yt(b)}\` ${o8(b)}${z?`, because ${Z2(z)}`:""}`,snippet:b.shape==="new_table"||b.shape==="new_file"?`[features]
|
|
2868
2888
|
${j1}`:yt(b)}),p={harness:"codex",file:s,summary:`the line \`${j1}\` under \`[features]\``,snippet:`[features]
|
|
2869
|
-
${j1}`},f={harness:"codex",file:s,summary:"`codex_hooks = true` inside the inline `features = { \u2026 }` table",snippet:"features = { \u2026, codex_hooks = true }"},k=(b,z)=>z.kind==="cannot"?{...z.edit?u(z.edit):z.inline?f:p,result:"refused",detail:`${z.why}; ${
|
|
2889
|
+
${j1}`},f={harness:"codex",file:s,summary:"`codex_hooks = true` inside the inline `features = { \u2026 }` table",snippet:"features = { \u2026, codex_hooks = true }"},k=(b,z)=>z.kind==="cannot"?{...z.edit?u(z.edit):z.inline?f:p,result:"refused",detail:`${z.why}; ${Z2(z)}`}:z.kind==="broken"?{...p,result:"refused",detail:w3(b)}:z.kind==="unreadable"?{...p,result:"refused",detail:z.why}:null,x=()=>{for(let b=0;b<3;b++){let{read:z,verdict:C}=h();if(C.kind!=="edit")return k(z,C);let I=C.edit,S=Is(z,I.text,l());if("backup"in S)return m({file:z.target,added:I.added,line:yt(I),at:new Date().toISOString(),...I.shape==="new_file"?{created:!0}:{},...S.backup?{backup:S.backup}:{}}),{...u(I,C),result:"written",detail:`line ${I.line} now reads \`${yt(I)}\`, because ${Z2(C)}`,edit:{line:I.line,text:yt(I),backup:S.backup,created:I.shape==="new_file"}};if(!S.changed)return{...u(I),result:"refused",detail:`${S.refused}; ${Z2(C)}`}}return{...p,result:"refused",detail:"it kept changing while Canary was editing it"}},y=()=>{let b=d(),z=b?.line??j1;for(let C=0;C<3;C++){let I=iq(s);if("unreadable"in I)return b?{...p,result:"refused",detail:`${I.unreadable}: if it still holds \`${z}\`, take that line out yourself`}:null;let S=c3(I,b);if(!S)return b&&m(null),null;if("refused"in S)return{...p,result:"refused",detail:`${S.refused}: take \`${z}\` out of it yourself`};let v=Is(I,S.text,l());if("backup"in v){m(null);let w=S.text===null,P=w?"deleted it: Canary had created it, and nothing else was in it":`took out line${S.lines.length===1?"":"s"} ${S.lines.join(", ")} (\`${z}\`${S.header?" and the `[features]` header Canary added with it":""})`;return{...p,result:"removed",detail:P,removed:{lines:S.lines,header:S.header,deleted:w,backup:v.backup}}}if(!v.changed)return{...p,result:"refused",detail:`${v.refused}: take \`${z}\` out of it yourself`}}return{...p,result:"refused",detail:"it kept changing while Canary was editing it"}};return{id:"codex",label:"Codex",byDefault:!0,afterInstall:v3(o),detected:r.detected,plan:()=>{let{verdict:b}=h();return b.kind==="edit"?[...r.plan(),u(b.edit,b)]:r.plan()},install:()=>{let{verdict:b}=h(),[z]=r.install();if(z.result==="refused")return[z];let C=b.kind==="person"?b3(b):null,I=x();return[C?{...z,detail:z.detail?`${z.detail}; ${C}`:C}:z,...I?[I]:[]]},uninstall:()=>{let[b]=r.uninstall();if(b.result==="refused")return[b];let z=y();return z?[b,z]:[b]},status:()=>{let[b]=r.status();if(b.state!=="registered")return[b];let z=iq(s),C="unreadable"in z?null:Ts(z,i),I=C?C.kind==="broken"?w3(z):C.kind==="person"?b3(C):C.kind==="edit"&&g3(C)?`Codex's hooks feature is off: ${Z2(C)} (\`${yt(C.edit)}\` ${Es(C.edit)} in its config.toml); \`canary hooks install\` adds it`:C.kind==="cannot"&&g3(C)?`Codex's hooks feature is off, and Canary cannot switch it on: ${C.why}${y3(C)}`:null:null;if(I)return[{...b,state:"disabled",detail:I}];let S=C?.kind==="edit"?`Codex before 0.124 also runs no hooks until \`${yt(C.edit)}\` is ${Es(C.edit)} in its config.toml, and it is not there: \`canary hooks install\` adds it.`:C?.kind==="cannot"?`Codex before 0.124 also runs no hooks until \`codex_hooks = true\` is in its config.toml, and Canary cannot add it: ${C.why}${y3(C)}.`:null,v=c();if(v<0)return[S?{...b,detail:S}:b];let w=s8(z,q,v);if(w===!0)return[S?{...b,detail:S}:b];let P=[w===null?"Codex's config.toml could not be read, so whether the hook is trusted is unknown.":null,v3(o),S].filter(Boolean).join(" ");return[{...b,state:"untrusted",detail:P,pending:o}]}}}function l8(e=process.env){let t=e.CURSOR_CONFIG_DIR||we(Ns(),".cursor");return{id:"cursor",label:"Cursor",byDefault:!0,...e8(t)}}var be,fe,cq,Q7,Ps,Q2,t8,r8,v3,yt,C3,Z2,g3,o8,i8,Es,y3,w3,tn,js=Z(()=>{"use strict";g();p3();e1();be=e=>!!e&&typeof e=="object"&&!Array.isArray(e),fe=class extends Error{};cq=10,Q7=(e,t=process.platform)=>t==="win32"?`canary hook ${e}`:`command -v canary >/dev/null 2>&1 || exit 0; canary hook ${e}`,Ps=e=>t=>be(t)&&typeof t.command=="string"&&new RegExp(`^\\s*(?:command -v canary >/dev/null 2>&1 \\|\\| exit 0;\\s*)?(?:node\\s+)?["']?(?:[^"'\\s]*[\\\\/])?canary(?:\\.js)?["']?\\s+hook\\s+${e}\\s*$`).test(t.command);Q2=["beforeShellExecution","beforeMCPExecution"];t8="^(Bash|PowerShell|Monitor|mcp__.*)$";r8=e=>({why:"Canary's push check runs before your agent pushes code or opens a pull request: when its chat hasn't run /canary with nothing left to fix, the agent asks you whether to run Canary first. Codex runs a hook only after you have trusted it once, and Codex Desktop has no screen for that yet, so the check does nothing until then.",command:e??"npm i -g @openai/codex && codex",after:'In Codex, choose "Review hooks", accept the Canary entry, then quit.'}),v3=e=>`${e.why} Run \`${e.command}\` in a terminal. ${e.after}`;yt=e=>e.shape==="dotted"?X2:j1,C3=e=>{let t=e.find(n=>!n.on)??e[0];return t?`your Codex (${t.binary})`:"Codex"},Z2=e=>e.answers.some(t=>!t.on)?`${C3(e.answers)} runs no hooks without it`:e.unanswered?.length?`the Codex at ${e.unanswered[0].binary} could not be asked (${e.unanswered[0].why}), and Codex before 0.124 runs no hooks without it`:"no Codex CLI could be asked here, and Codex before 0.124 runs no hooks without it",g3=e=>e.answers.some(t=>!t.on),o8=e=>e.shape==="under_header"?`under \`[features]\`, line ${e.line}`:e.shape==="dotted"?`beside the other \`features.\` keys, line ${e.line}`:e.shape==="new_table"?`in a new \`[features]\` table at the end, line ${e.line}`:"in a new config.toml",i8=e=>e.shape==="dotted"?"features.codex_hooks = true":"codex_hooks = true",Es=e=>e.shape==="dotted"?"beside the other `features.` keys":e.shape==="under_header"?"under `[features]`":"in a `[features]` table",y3=e=>e.edit?`; add \`${i8(e.edit)}\` ${Es(e.edit)} yourself`:"",w3=e=>`Codex can't load its config.toml (line ${e.problem?.line??"?"}: ${e.problem?.message??"invalid TOML"}), so it runs no hooks at all; fix that line`;tn=(e=process.env)=>[n8(e),a8(e),l8(e)]});var R3={};Ur(R3,{installAgentPlugin:()=>Ds});import{existsSync as Fs,mkdirSync as h8,readFileSync as c8,renameSync as A3,rmSync as Ms,writeFileSync as d8}from"node:fs";import{homedir as u8}from"node:os";import{dirname as m8,join as Qt}from"node:path";function f8(e,t){return Object.entries(t).every(([n,q])=>{try{return c8(Qt(e,n),"utf8")===q}catch{return!1}})}function v8(e,t){let n=`${e}.next`,q=`${e}.old`;Ms(n,{recursive:!0,force:!0});for(let[r,s]of Object.entries(t))h8(m8(Qt(n,r)),{recursive:!0}),d8(Qt(n,r),s);Ms(q,{recursive:!0,force:!0}),Fs(e)&&A3(e,q),A3(n,e),Ms(q,{recursive:!0,force:!0})}function g8(e,t){for(let o of["extraKnownMarketplaces","enabledPlugins"])if(e[o]===void 0&&(e[o]={}),!p8(e[o]))throw new fe(`its \`${o}\` entry is not an object`);let n=e.extraKnownMarketplaces,q=e.enabledPlugins,r={source:{source:"directory",path:t}},s=!1;return JSON.stringify(n[$s])!==JSON.stringify(r)&&(n[$s]=r,s=!0),q[I3]===void 0&&(q[I3]=!0,s=!0),s}function Ds(e=process.env){if(!Ls||K().agentSkills===!1)return{result:"skipped"};let t=e.CLAUDE_CONFIG_DIR||Qt(u8(),".claude");if(!Fs(t))return{result:"skipped"};let n=Qt(G(),"plugins"),q=Qt(t,"settings.json");try{let r=!Fs(n),s=!f8(n,Ls);s&&v8(n,Ls);let o=Xt(q,i=>g8(i,n));return o.result==="refused"?{result:"refused",file:q,detail:o.detail}:r?{result:"added",file:q}:{result:s||o.result==="written"?"updated":"current",file:q}}catch(r){return{result:"refused",file:n,detail:`the folder couldn't be written (${r.code??"error"})`}}}var Ls,$s,I3,p8,Ws=Z(()=>{"use strict";g();e1();js();Ls=typeof O=="object"?O:null,$s="runcanary",I3=`canary@${$s}`,p8=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});var Hs,T3=Z(()=>{Hs=`---
|
|
2870
2890
|
name: canary
|
|
2871
2891
|
description: >-
|
|
2872
2892
|
Use whenever you finish a code change and are about to report it done, or whenever a change
|
|
@@ -2944,7 +2964,8 @@ It prints one JSON document:
|
|
|
2944
2964
|
such as fixing what Canary found. Never predict, judge or summarize what Canary found or will
|
|
2945
2965
|
find, and don't narrate that Canary is working: its own messages keep the user posted.
|
|
2946
2966
|
\`exitCode\` is 0 when Canary answered, whatever it answered, and 2 when it couldn't (\`say\` tells
|
|
2947
|
-
the user what to do).
|
|
2967
|
+
the user what to do). \`canaryMd\`, when present, is the file that keeps the user's instructions to
|
|
2968
|
+
Canary for this repository. With \`"ended": true\` that is the whole answer to this request. With
|
|
2948
2969
|
\`"ended": false\`, follow the request as below.
|
|
2949
2970
|
- \`"ok": false\`: something on this machine needs fixing first (exit 3), or Canary couldn't be
|
|
2950
2971
|
reached (exit 2). Show \`message\` and \`fix\` as written. If it says Canary needs a newer CLI,
|
|
@@ -2971,7 +2992,11 @@ the one above. Each time:
|
|
|
2971
2992
|
new checks.
|
|
2972
2993
|
- \`answer\`: a check asks \`question\`. Answer facts about this project yourself by running
|
|
2973
2994
|
\`command\` with your answer in place of \`<answer>\`; access and approvals come only from the
|
|
2974
|
-
user, so ask them first. When \`
|
|
2995
|
+
user, so ask them first. When \`question\` begins "Canary's must-fix review", answer it
|
|
2996
|
+
yourself from this chat, without asking the user: run \`command\` as written, with only the JSON
|
|
2997
|
+
it asks for on the line where \`<answer>\` is, between the heredoc's lines, naming for each
|
|
2998
|
+
must-fix you move the ground it asks for and quoting the user exactly. When unsure, leave it
|
|
2999
|
+
out: it stays a must-fix. Otherwise, when \`command\` starts with \`canary answer\`, the request asks which
|
|
2975
3000
|
part of the code to read instead: if what you know from this chat settles it, run \`command\`
|
|
2976
3001
|
with your answer. Otherwise ask the user \`question\` with your tool for asking a question with
|
|
2977
3002
|
options (in Claude Code, AskUserQuestion; header "Canary"), offering \`options\` in their order,
|
|
@@ -3025,6 +3050,11 @@ one fails, it is another must-fix, found on the code as it was when the user ask
|
|
|
3025
3050
|
fixing what Canary found, fix it too, unless your changes already did, and name it in your next
|
|
3026
3051
|
reply; otherwise tell the user in one line what failed.
|
|
3027
3052
|
|
|
3053
|
+
A finding under \`result.additional\` with \`moved\` is one you said can wait: leave it, and explain it
|
|
3054
|
+
if the user asks. When the user tells you a kind of finding isn't useful to them or can wait, add
|
|
3055
|
+
it, in their own words, under "## Your instructions to Canary" in \`canaryMd\` (add that heading if
|
|
3056
|
+
it's missing), and tell them you did: Canary reads it on every ask.
|
|
3057
|
+
|
|
3028
3058
|
\`canary show --json <requestId>\` prints everything the request has shown so far, with the ending's
|
|
3029
3059
|
\`fix\`, the \`ask\` that holds one, and \`pr_section\` again, as they stand now, once it has ended.
|
|
3030
3060
|
|
|
@@ -3071,38 +3101,38 @@ If \`canary\` is not installed: \`npm i -g @runcanary/cli\`, then start at step
|
|
|
3071
3101
|
"Getting started" section covers logging in.
|
|
3072
3102
|
Output that begins with \`OFFLINE COPY\` could not be refreshed and may be outdated \u2014 say so if
|
|
3073
3103
|
you act on it.
|
|
3074
|
-
`});var
|
|
3075
|
-
`,{flag:"wx",mode:384}),
|
|
3076
|
-
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${
|
|
3077
|
-
`);if(!n)return{};let s={worktreeId:
|
|
3078
|
-
`).filter(Boolean).sort()[0]:void 0;i
|
|
3104
|
+
`});var E3={};Ur(E3,{installAgentSkill:()=>nn});import{existsSync as _s,lstatSync as w8,mkdirSync as b8,readFileSync as O3,rmSync as k8,rmdirSync as z8,writeFileSync as x8}from"node:fs";import{homedir as Bs}from"node:os";import{join as wt}from"node:path";function A8(e){let t=wt(e,"skills",C8),n=wt(t,"SKILL.md");if(uq(t)||uq(n)||!_s(n))return;let q;try{q=O3(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(q)||!/runcanary\.ai|@runcanary\/cli/.test(q))){try{k8(n,{force:!1})}catch{return}try{z8(t)}catch{}}}function uq(e){try{return w8(e).isSymbolicLink()}catch{return!1}}function I8(){return[wt(Bs(),".claude"),wt(Bs(),".agents"),wt(Bs(),".codex")].filter(e=>_s(e))}function nn(){let e={installed:[],refreshed:[],current:[],skipped:[]};if(K().agentSkills===!1)return e;for(let t of I8()){A8(t);let n=wt(t,"skills",S8),q=wt(n,"SKILL.md");try{if(uq(n)||uq(q)){e.skipped.push(q);continue}let r=_s(q)?O3(q,"utf8"):null;if(r===Hs){e.current.push(q);continue}b8(n,{recursive:!0}),x8(q,Hs),(r===null?e.installed:e.refreshed).push(q)}catch{}}return e}var S8,C8,mq=Z(()=>{"use strict";g();e1();T3();S8="canary",C8="canary-setup"});import{createHash as R8,randomUUID as T8}from"node:crypto";import{mkdirSync as O8,readFileSync as E8,renameSync as N8,rmSync as N3,writeFileSync as P8}from"node:fs";import{dirname as Us,join as j8,resolve as P3}from"node:path";function L3(e,t,n=Date.now()){try{let q=M3(e),r=`${q}.${T8()}.tmp`;O8(Us(q),{recursive:!0,mode:448});try{P8(r,JSON.stringify({version:1,chat:t,at:n})+`
|
|
3105
|
+
`,{flag:"wx",mode:384}),N8(r,q)}catch(s){throw N3(r,{force:!0}),s}}catch{}}function F3(e,t=Date.now()){for(let n=P3(e);;n=Us(n)){let q=M3(n),r=null;try{r=JSON.parse(E8(q,"utf8")),N3(q,{force:!0})}catch{}if(r&&r.version===1&&typeof r.chat=="string"&&r.chat&&typeof r.at=="number"&&t-r.at>=0&&t-r.at<M8)return r.chat;if(Us(n)===n)return null}}var M8,L8,j3,M3,Gs=Z(()=>{"use strict";g();e1();M8=1e4,L8=/(?:^|[;&|(]|\$\()\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:[^\s;&|()]*\/)?canary(?=[\s;&|)]|$)/m,j3=e=>e.some(t=>L8.test(t)),M3=e=>j8(G(),"hold",`chat-${R8("sha256").update(P3(e)).digest("hex").slice(0,32)}.json`)});import{mkdirSync as F8,readFileSync as $8,writeFileSync as D8}from"node:fs";import{homedir as W8}from"node:os";import{dirname as H8,join as $3}from"node:path";function W3(){try{return JSON.parse($8(Vs(),"utf8"))}catch{return{}}}function _8(e,t){let n=e.split(".").map(Number),q=t.split(".").map(Number);for(let r=0;r<3;r+=1){let s=(n[r]||0)-(q[r]||0);if(s!==0)return s>0}return!1}function H3(){if(ke==="0.0.0-dev")return;let{latest:e}=W3();e&&_8(e,ke)&&console.error(`A newer Canary CLI is available (${ke} -> ${e}): npm install -g ${D3}`)}function Zt(){if(ke==="0.0.0-dev")return;let e=W3();e.checkedAt&&Date.now()-e.checkedAt<B8||(async()=>{let t=n=>{try{F8(H8(Vs()),{recursive:!0}),D8(Vs(),JSON.stringify({checkedAt:Date.now(),latest:n??e.latest})+`
|
|
3106
|
+
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${D3}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return t();let{version:q}=await n.json();t(q||void 0)}catch{t()}})()}var ke,D3,B8,Vs,bt=Z(()=>{"use strict";g();ke="0.1.29",D3="@runcanary/cli",B8=1440*60*1e3,Vs=()=>$3(process.env.CANARY_HOME||$3(W8(),".canary"),"update-check.json")});import{createHash as U8}from"node:crypto";import{execFileSync as G8,spawn as V8}from"node:child_process";function Q1(e){Ve={...Ve,...e},qn=null}function Ys(e=process.env){if(e.CLAUDECODE==="1"||e.CLAUDE_CODE_SESSION_ID){let t=e.CLAUDE_CODE_SESSION_ID??e.CLAUDE_CODE_HOST_SESSION_ID;return{harness:"claude-code",...t?{chatId:t}:{}}}return e.CODEX_SANDBOX||e.CODEX_SANDBOX_NETWORK_DISABLED==="1"?{harness:"codex"}:e.CURSOR_AGENT==="1"?{harness:"cursor"}:{harness:"unknown"}}function kt(e=process.env,t=process.cwd()){let n=e.CLAUDE_CODE_SESSION_ID?.trim(),q=e.CODEX_THREAD_ID?.trim();return n&&!q?n:(Js===void 0&&(Js=F3(t)),Js??q??n??null)}function J8(e,t){return U8("sha256").update(`${t}\0${e}`).digest("hex").slice(0,24)}function pq(){return{...Object.fromEntries(Object.entries(process.env).filter(([e])=>!e.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(e))),GIT_OPTIONAL_LOCKS:"0",GIT_NO_LAZY_FETCH:"1",GIT_NO_REPLACE_OBJECTS:"1",GIT_TERMINAL_PROMPT:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"}}function B3(e,t){try{let n=pq();return G8("git",e,{cwd:t,env:n,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function Y8(e,t){let[n,q,r]=(B3(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],e)??"").split(`
|
|
3107
|
+
`);if(!n)return{};let s={worktreeId:J8(n,t)};if(r!=="true"){let o=Di(s.worktreeId);o&&B3(["cat-file","-e",`${o}^{commit}`],n)!==null?s.repoFingerprint=o:K8(n,s.worktreeId)}return s.branch=q&&q!=="HEAD"?q:"HEAD",s}function K8(e,t){_3.has(t)||_3.set(t,new Promise(n=>{try{let q=pq(),r=V8("git",["rev-list","--max-parents=0","HEAD"],{cwd:e,env:q,stdio:["ignore","pipe","ignore"],timeout:6e4}),s="";r.stdout.on("data",o=>{s+=o.toString("utf8")}),r.on("error",()=>n()),r.on("close",o=>{let i=o===0?s.trim().split(`
|
|
3108
|
+
`).filter(Boolean).sort()[0]:void 0;i&&Wi(t,i),n()}),r.unref(),r.stdout.unref?.()}catch{n()}}))}function X8(){if(qn)return qn;let e=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",t=Ys(),n=Ve.harness??t.harness,q=t.harness===n?t.chatId:void 0,r="",s={};try{r=$i(),s=Y8(Ve.cwd??process.cwd(),r)}catch{}return qn={cliVersion:ke,command:e,installId:r,...s,harness:n,...q?{chatId:q}:{},...Ve.agent!==void 0?{agent:Ve.agent}:{},...Ve.mode?{mode:Ve.mode}:{}},qn}function Je(){let e=X8(),t=q=>q.replace(/[^\x20-\x7e]/g,"?").slice(0,200),n={[g1.cli]:e.cliVersion,[g1.harness]:e.harness};return e.installId&&(n[g1.install]=e.installId),e.command&&(n[g1.command]=t(e.command)),e.worktreeId&&(n[g1.worktree]=e.worktreeId),e.repoFingerprint&&(n[g1.repo]=e.repoFingerprint),e.branch&&(n[g1.branch]=t(e.branch)),e.chatId&&(n[g1.chat]=t(e.chatId)),e.agent!==void 0&&(n[g1.agent]=e.agent?"1":"0"),e.mode&&(n[g1.mode]=e.mode),n}var g1,Ve,qn,Js,_3,ie=Z(()=>{"use strict";g();e1();Gs();bt();g1={cli:"x-canary-cli",command:"x-canary-command",install:"x-canary-install",worktree:"x-canary-worktree",repo:"x-canary-repo",branch:"x-canary-branch",harness:"x-canary-harness",chat:"x-canary-chat",agent:"x-canary-agent",mode:"x-canary-mode"},Ve={},qn=null;_3=new Map});async function W(e,t={}){let n=(t.baseUrl||a1()).replace(/\/+$/,""),q={...Je(),...t.headers};t.token&&(q.authorization=`Bearer ${t.token}`),t.body!==void 0&&(q["content-type"]="application/json");let r;try{r=await fetch(n+e,{method:t.method??"GET",headers:q,body:t.body!==void 0?JSON.stringify(t.body):void 0,signal:t.signal})}catch(s){throw new L(0,`could not reach ${n} (${s instanceof Error?s.message:String(s)})`)}if(!r.ok){let s=r.statusText,o,i,a;try{let l=await r.json();s=l.error||l.message||s,typeof l.fix=="string"&&l.fix&&(o=l.fix),typeof l.runId=="string"&&l.runId&&(i=l.runId),typeof l.code=="string"&&l.code&&(a=l.code)}catch{}throw new L(r.status,s,o,i,a)}return r.status===204?null:await r.json()}var L,z1,p1=Z(()=>{"use strict";g();e1();ie();L=class extends Error{constructor(n,q,r,s,o){super(q);this.status=n;this.fix=r;this.runId=s;this.code=o;this.name="ApiError"}},z1=e=>e instanceof L&&(e.status===0||e.status===408||e.status===429||e.status===502||e.status===503||e.status===504)});function U3(e){return P1(t=>({...t,gate:{...t.gate,mode:e}}))}var zt,fq=Z(()=>{"use strict";g();e1();zt=()=>K().gate?.mode==="off"?"off":"on"});var Tk,vq,Q8,Ok,G3=Z(()=>{"use strict";g();Tk=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:e=>`canary verify: tree ${e}`}),vq=e=>`tree:${e.slice(0,12)}`,Q8=[["core.fsmonitor","false"],["core.splitIndex","false"],["gc.auto","0"],["commit.gpgsign","false"],["i18n.commitEncoding","utf-8"],["log.showSignature","false"],["diff.noprefix","false"],["diff.mnemonicPrefix","false"],["diff.relative","false"],["diff.context","3"],["diff.interHunkContext","0"],["diff.submodule","short"],["apply.ignoreWhitespace","no"],["apply.whitespace","nowarn"]],Ok=Q8.flatMap(([e,t])=>["-c",`${e}=${t}`])});import{createHash as Z8}from"node:crypto";import{existsSync as ed,mkdirSync as Ks,readFileSync as e2,writeFileSync as gq}from"node:fs";import{join as Ne}from"node:path";function t2(e){return Ne(e,".canary")}function Y3(e){let t=e.trim();if(!t)return null;if(!t.includes("://")){let n=t.match(/^[^@]+@([^:]+):(.+)$/);if(n){let q=n[2].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);return q.length>=2?{host:n[1],owner:q[0],name:q.slice(1).join("/")}:null}}try{let n=new URL(t),q=n.pathname.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);if(q.length>=2)return{host:n.host,owner:q[0],name:q.slice(1).join("/")}}catch{}return null}function rn(e){let t=t2(e),n=Ne(t,".gitignore");try{let q=e2(n,"utf8").split(`
|
|
3079
3109
|
`).map(r=>r.trim()).filter(r=>r.length>0);if(q[q.length-1]==="*")return}catch{}try{Ks(t,{recursive:!0});let q="";try{q=e2(n,"utf8"),q&&!q.endsWith(`
|
|
3080
3110
|
`)&&(q+=`
|
|
3081
|
-
`)}catch{}
|
|
3082
|
-
`)}catch{}}function Ye(e){let t=t2(e),n;try{n=e2(Ne(t,"setup.sh"),"utf8")}catch{throw new Z1("recipe_missing","No .canary/setup.sh found. Produce the recipe first (run the Canary setup skill in your coding agent).","canary setup skill")}if(!n.trim())throw new Z1("recipe_invalid",".canary/setup.sh is empty.");let q;try{q=JSON.parse(e2(Ne(t,"run.json"),"utf8"))}catch(i){throw new Z1("recipe_invalid",`Cannot read .canary/run.json: ${i instanceof Error?i.message:String(i)}`)}let r=[],s={},o=Ne(t,"env.json");if(
|
|
3083
|
-
`),
|
|
3084
|
-
`}catch{}
|
|
3085
|
-
`,{flag:"wx",mode:384});try{
|
|
3086
|
-
`,{flag:"wx",mode:384}),
|
|
3087
|
-
`,{flag:"wx",mode:384}),
|
|
3111
|
+
`)}catch{}gq(n,`${q}*
|
|
3112
|
+
`)}catch{}}function Ye(e){let t=t2(e),n;try{n=e2(Ne(t,"setup.sh"),"utf8")}catch{throw new Z1("recipe_missing","No .canary/setup.sh found. Produce the recipe first (run the Canary setup skill in your coding agent).","canary setup skill")}if(!n.trim())throw new Z1("recipe_invalid",".canary/setup.sh is empty.");let q;try{q=JSON.parse(e2(Ne(t,"run.json"),"utf8"))}catch(i){throw new Z1("recipe_invalid",`Cannot read .canary/run.json: ${i instanceof Error?i.message:String(i)}`)}let r=[],s={},o=Ne(t,"env.json");if(ed(o)){let i;try{i=JSON.parse(e2(o,"utf8"))}catch(l){throw new Z1("recipe_invalid",`Cannot read .canary/env.json: ${l instanceof Error?l.message:String(l)}`)}if(i===null||typeof i!="object"||Array.isArray(i))throw new Z1("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let a=i;r=X3(a.manifest),s=Q3(a.values),nd(r)}return{setupSh:n,runJson:q,envManifest:r,envValues:s}}function xt(e){return Z8("sha256").update(JSON.stringify([e.setupSh,e.runJson,e.envManifest,e.envValues])).digest("hex")}function Xs(e,t){let n=e.filter(q=>q.neededAt==="boot").map(q=>q.name).filter(q=>!Object.prototype.hasOwnProperty.call(t,q)||t[q]==="");return{missing:[...new Set(n)]}}function X3(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.name=="string"):[]}function nd(e){for(let t of e){if(!V3.has(String(t.class)))throw new Z1("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has unknown class "${String(t.class)}"`,`use one of: ${[...V3].join(", ")}`);if(!td.has(String(t.neededAt)))throw new Z1("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has invalid neededAt "${String(t.neededAt)}"`,'use "boot" or "runtime"')}}function Q3(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function qd(e){try{let t=JSON.parse(e2(Ne(t2(e),"env.json"),"utf8"));return{manifest:X3(t.manifest),values:Q3(t.values)}}catch{return{manifest:[],values:{}}}}function rd(e,t){Ks(t2(e),{recursive:!0}),gq(Ne(t2(e),"env.json"),JSON.stringify(t,null,2)+`
|
|
3113
|
+
`),rn(e)}function Qs(e,t){if(t.length===0)return;let n=qd(e),q=new Map(n.manifest.map(r=>[r.name,r]));for(let r of t){n.values[r.name]=r.value;let s=q.get(r.name);if(s)r.class&&J3.has(r.class)&&!J3.has(s.class??"")&&(s.class=r.class,s.neededAt="boot");else{let o={name:r.name,class:r.class??"config",neededAt:"boot",why:r.why??"added during cloud verification"};q.set(r.name,o),n.manifest.push(o)}}rd(e,n)}function Z3(e,t){let n=[],q=t2(e);if(Ks(q,{recursive:!0}),typeof t.setupSh=="string"&&t.setupSh.trim()&&(gq(Ne(q,"setup.sh"),t.setupSh),n.push(".canary/setup.sh")),typeof t.runJson=="string"&&t.runJson.trim()){let s=t.runJson;try{s=JSON.stringify(JSON.parse(t.runJson),null,2)+`
|
|
3114
|
+
`}catch{}gq(Ne(q,"run.json"),s),n.push(".canary/run.json")}let r=Object.entries(t.envOverrides??{});return r.length>0&&(Qs(e,r.map(([s,o])=>({name:s,value:o,why:"authored by the cloud verifier while fixing the boot"}))),n.push(".canary/env.json")),rn(e),n}var Z1,K3,V3,td,J3,Zs=Z(()=>{"use strict";g();Z1=class extends Error{constructor(n,q,r){super(q);this.code=n;this.fix=r;this.name="RecipeError"}};K3=new Set(["github.com","ssh.github.com"]);V3=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),td=new Set(["boot","runtime"]);J3=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"])});import{execFileSync as sd}from"node:child_process";import{createHash as na,randomUUID as wq}from"node:crypto";import{linkSync as od,lstatSync as qa,mkdirSync as bq,readdirSync as id,readFileSync as to,realpathSync as yq,renameSync as ra,rmSync as kq,writeFileSync as no}from"node:fs";import{basename as qo,dirname as sa,isAbsolute as ad,join as ee,relative as ld,resolve as ro,sep as hd}from"node:path";function cd(e){let t=Y3(e);if(!(!t||!K3.has(t.host.toLowerCase().replace(/:\d+$/,"")))&&!(!ea.test(t.owner)||!ea.test(t.name)))return`${t.owner}/${t.name}`}function q2(e=process.cwd()){let t={...Object.fromEntries(Object.entries(process.env).filter(([i])=>!i.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(i))),GIT_OPTIONAL_LOCKS:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"},n=i=>sd("git",i,{cwd:e,env:t,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").replace(/\r?\n$/,""),q,r;try{q=yq(n(["rev-parse","--show-toplevel"])),r=yq(ro(yq(e),n(["rev-parse","--git-common-dir"])))}catch{throw new n1("not_a_git_repository","Run this command inside the Git repository you want Canary to use.")}let s;try{s=cd(n(["remote","get-url","origin"]))}catch{}if(s)return{root:q,commonDirectory:r,name:s,githubFullName:s};let o=qo(q).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:q,commonDirectory:r,name:o}}function dd(e){let t;try{t=new URL(e)}catch{throw new n1("invalid_api_url","The Canary API URL is invalid.")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new n1("invalid_api_url","The Canary API URL must be HTTP(S) without credentials, a query, or a fragment.");return t.href.replace(/\/+$/,"")}function zq(e){try{return yq(e)}catch(t){if(t.code!=="ENOENT")throw t;if(qa(e,{throwIfNoEntry:!1})?.isSymbolicLink())throw new n1("cache_path_unresolvable","A symlink under CANARY_HOME/local-repositories points at a missing target. Remove or fix that link, then run the command again.");let n=sa(e);if(n===e)throw t;return ee(zq(n),qo(e))}}function eo(e,t){let n=ld(e,t);return n===""||!ad(n)&&n!==".."&&!n.startsWith(`..${hd}`)}function r2(e,t){let n=zq(t);if(!eo(e,n))throw new n1("cache_outside_home","Something under CANARY_HOME/local-repositories links outside CANARY_HOME. Remove that link, then run the command again.");return n}function s2(e){if(!n2.test(e.userId)||!n2.test(e.workspaceId))throw new n1("invalid_account_context","Sign in with canary login and select a workspace with canary workspace use <id>, then run the command again.");let t=q2(e.directory),n=dd(e.apiUrl),q=zq(ro(G())),r=qo(t.commonDirectory)===".git"?sa(t.commonDirectory):t.commonDirectory,s=na("sha256").update(JSON.stringify([sn,n,e.userId,e.workspaceId,t.githubFullName?`github:${t.githubFullName.toLowerCase()}`:t.commonDirectory])).digest("hex"),o=ee(q,"local-repositories"),i=r2(o,ee(o,s));if([t.root,t.commonDirectory,r].some(a=>eo(a,q)||eo(a,i)))throw new n1("cache_inside_checkout","CANARY_HOME is inside this repository. Point it at a directory outside the checkout, then run the command again.");return{...t,apiUrl:n,scope:s,cacheRoot:o,cacheDirectory:i}}function ta(e,t){let n=r2(e.cacheRoot,ee(e.cacheDirectory,t)),q;try{q=to(n,"utf8")}catch(o){if(o.code==="ENOENT")return null;throw new n1("binding_unreadable","Could not read Canary's saved record for this repository under CANARY_HOME/local-repositories. Check its permissions, then run the command again.")}let r;try{r=JSON.parse(q)}catch{}let s=t==="identity.json"?["version","scope","localKey"]:["version","scope","localKey","repositoryId"];if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(o=>!s.includes(o))||r.version!==sn||r.scope!==e.scope||typeof r.localKey!="string"||!n2.test(r.localKey)||t==="repository.json"&&(typeof r.repositoryId!="string"||!n2.test(r.repositoryId)))throw new n1("invalid_binding","Canary's saved record for this repository under CANARY_HOME/local-repositories is damaged. Canary left it in place: restore it, or remove it to register this repository as new.");return r}function St(e){let t=ta(e,"identity.json"),n=ta(e,"repository.json");if(!t&&!n)return null;if(!t||n&&n.localKey!==t.localKey)throw new n1("invalid_binding","Canary's saved records for this repository under CANARY_HOME/local-repositories disagree with each other. Canary left them in place: restore them, or remove them to register this repository as new.");return{localKey:t.localKey,...n?{repositoryId:n.repositoryId}:{}}}function so(e,t,n){bq(e.cacheDirectory,{recursive:!0,mode:448});let q=ee(e.cacheDirectory,`${t}.${wq()}.tmp`);try{no(q,JSON.stringify({version:sn,scope:e.scope,...n})+`
|
|
3115
|
+
`,{flag:"wx",mode:384});try{od(q,ee(e.cacheDirectory,t))}catch(r){if(r.code!=="EEXIST")throw r}}finally{kq(q,{force:!0})}}function oa(e,t){bq(e.cacheDirectory,{recursive:!0,mode:448});let n=ee(e.cacheDirectory,`repository.json.${wq()}.tmp`);no(n,JSON.stringify({version:sn,scope:e.scope,...t})+`
|
|
3116
|
+
`,{flag:"wx",mode:384}),ra(n,ee(e.cacheDirectory,"repository.json"))}function ia(e){return St(s2(e))}function oo(e,t){let n=s2(e),q=St(n);!q?.repositoryId||q.repositoryId===t||oa(n,{localKey:q.localKey,repositoryId:t})}function Ke(e,t){if(!/^[a-z0-9-]+\.json(?:\.gz)?$/.test(t))throw new n1("invalid_receipt_name","Invalid cache file name.");let n=s2(e);return bq(n.cacheDirectory,{recursive:!0,mode:448}),r2(n.cacheRoot,ee(n.cacheDirectory,t))}function ud(e){return aa(s2(e))}function aa(e){let t=St(e);return t||(so(e,"identity.json",{localKey:wq()}),St(e))}function md(e){try{let t=JSON.parse(to(r2(e.cacheRoot,ee(e.cacheDirectory,io)),"utf8"));return t.version===1&&t.checkout===ao(e.githubFullName)}catch{return!1}}function pd(e){bq(e.cacheDirectory,{recursive:!0,mode:448});let t=r2(e.cacheRoot,ee(e.cacheDirectory,io)),n=`${t}.${wq()}.tmp`;try{no(n,JSON.stringify({version:1,at:new Date().toISOString(),checkout:ao(e.githubFullName)})+`
|
|
3117
|
+
`,{flag:"wx",mode:384}),ra(n,t)}finally{kq(n,{force:!0})}}async function la(e,t){let n=s2(e),q=St(n);if(q?.repositoryId)return q;let{githubFullName:r}=n;if(!r||md({...n,githubFullName:r}))return null;let s=await t(r);if(!s)return null;if("notConnected"in s)return pd({...n,githubFullName:r}),null;if(!n2.test(s.repositoryId))return null;let o=aa(n);return o.repositoryId||so(n,"repository.json",{localKey:o.localKey,repositoryId:s.repositoryId}),St(n)}function ha(){let e=ee(zq(ro(G())),"local-repositories"),t=r2(e,e),n;try{n=id(t,{withFileTypes:!0}).filter(q=>q.isDirectory()).map(q=>q.name)}catch{return[]}return n.map(q=>ee(t,q,io)).filter(q=>qa(q,{throwIfNoEntry:!1})?.isFile())}function xq(){try{for(let e of ha())kq(e,{force:!0})}catch{}}function Sq(e){try{let t=ha();if(!t.length)return;let{githubFullName:n}=q2(e??process.cwd());if(!n)return;let q=ao(n);for(let r of t)try{JSON.parse(to(r,"utf8")).checkout===q&&kq(r,{force:!0})}catch{}}catch{}}function fd(e,t,n,q){let r=e,s=n.githubFullName?"github":"local";if(!r||typeof r.repositoryId!="string"||!n2.test(r.repositoryId)||r.provider!==s||t.repositoryId&&r.repositoryId!==t.repositoryId&&s!=="github"||(s==="local"?r.localKey!==t.localKey:r.localKey!==void 0)||typeof r.name!="string"||!r.name.trim()||r.name.length>512||/[\u0000-\u001f\u007f]/.test(r.name)||!r.workspace||r.workspace.id!==q||typeof r.workspace.name!="string")throw new n1("invalid_repository_response","Canary returned an unexpected answer while looking up this repository. Run the command again; if it repeats, update the CLI.");return r}async function Pe(e,t=W){if(!e.token)throw new n1("not_logged_in","Run canary login first.");let n=s2(e),q=ud(e),r={token:e.token,baseUrl:n.apiUrl},s=q.repositoryId?await t(`/api/v1/cli/local-repositories/${q.repositoryId}?workspaceId=${encodeURIComponent(e.workspaceId)}`,r):await t("/api/v1/cli/local-repositories",{...r,method:"POST",body:{workspaceId:e.workspaceId,localKey:q.localKey,name:n.name,...n.githubFullName?{githubFullName:n.githubFullName}:{}}}),o=fd(s,q,n,e.workspaceId);q.repositoryId&&q.repositoryId!==o.repositoryId?oa(n,{localKey:q.localKey,repositoryId:o.repositoryId}):so(n,"repository.json",{localKey:q.localKey,repositoryId:o.repositoryId});let i=St(n);if(i?.repositoryId!==o.repositoryId||i.localKey!==q.localKey)throw new n1("binding_conflict","Another canary process registered this repository at the same time. Run the command again.");return o}var n2,sn,ea,n1,io,ao,M1=Z(()=>{"use strict";g();p1();e1();Zs();n2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,sn=2,ea=/^[A-Za-z0-9_.-]+$/,n1=class extends Error{constructor(n,q){super(q);this.code=n;this.name="LocalRepositoryError"}};io="not-connected.json",ao=e=>na("sha256").update(JSON.stringify([sn,`github:${e.toLowerCase()}`])).digest("hex")});async function je(e,t,n=a1()){let q=K().team?.id;if(!q)throw new n1("workspace_selection_required","Select a workspace with canary workspace list and canary workspace use <id>, then run the command again.");let r=await W("/api/v1/cli/auth/whoami",{token:t,baseUrl:n});if(!r?.user?.id)throw new n1("invalid_identity_response","Canary could not tell which account this token belongs to. Run canary login again.");return{apiUrl:n,userId:r.user.id,workspaceId:q,directory:e}}async function Cq(e,t,n){let q=ia(e);if(!q?.repositoryId)return;let r=await W(`/api/v1/cli/local-repositories/${q.repositoryId}/status?workspaceId=${encodeURIComponent(e.workspaceId)}`,{token:t,baseUrl:e.apiUrl,signal:n});if(typeof r?.repositoryId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r.repositoryId)||!["setup_required","ready"].includes(r.state))throw new n1("invalid_readiness_response","Canary returned an unexpected answer about this repository's setup. Run the command again.");return r.repositoryId!==q.repositoryId&&oo(e,r.repositoryId),r}function ca(e=process.cwd()){try{return q2(e).name}catch{return}}var o2=Z(()=>{"use strict";g();p1();e1();M1()});import{spawn as vd}from"node:child_process";import{createHash as ln}from"node:crypto";import{constants as da}from"node:fs";import{lstat as fo,mkdir as Rq,mkdtemp as pa,open as fa,readFile as gd,readdir as yd,readlink as wd,realpath as Me,rm as lo,writeFile as vo}from"node:fs/promises";import{tmpdir as va}from"node:os";import{basename as bd,dirname as kd,isAbsolute as zd,join as f1,relative as xd,resolve as ga,sep as Sd}from"node:path";import{promisify as Cd}from"node:util";import{deflate as Ad}from"node:zlib";function go(e,t){let n=e.split("/");(!e||Buffer.byteLength(e)>t.maxPathBytes||n.length>t.maxDepth||n.some(q=>!q||Buffer.byteLength(q)>255||q==="."||q===".."||ba(q)||q.includes("\0")||q.includes("\\")))&&_("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(e)}.`)}function Od(e){return{...Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")||!e&&["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(n))),GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_NO_LAZY_FETCH:"1",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0",...e?{GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1"}:{}}}function ka(e,t){return At(e).map(n=>{let q=n.indexOf(" "),[r,s,o]=n.slice(0,q).split(" ");return q<0||!(t?on.test(s):on.test(o))?_("git_source_error","Git returned an invalid source entry."):(t&&o!=="0"&&_("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:n.slice(q+1),mode:r,oid:t?s:o})})}function yo(e){return(e??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256)||void 0}async function co(e,t){let n=await e.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,q=await ho(e),r={headSha:n,branch:q,baseRef:null,baseSha:null,baselineMode:"whole-project"};if(t!==void 0){(!t||t.startsWith("-")||t.length>1024||/[\x00-\x1f\x7f]/.test(t))&&_("invalid_base","--base must name a local Git commit or ref.");let i=await e.text(["rev-parse","--verify","--quiet",`${t}^{commit}`],!0);return on.test(i)||_("invalid_base",`--base ${JSON.stringify(t)} is not a local commit or ref. Canary does not fetch; pass one that exists locally.`),{...r,baseRef:t,baseSha:i,baselineMode:"explicit"}}if(!n)return r;let s=await e.text(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"],!0),o;for(let i of[[s],["refs/remotes/origin/main","refs/remotes/origin/master"],["main","master"].filter(a=>a!==q).map(a=>`refs/heads/${a}`)]){for(let a of[...new Set(i.filter(Boolean))]){let l=await e.text(["rev-parse","--verify","--quiet",`${a}^{commit}`],!0);if(!l)continue;let c=await e.text(["merge-base",n,l],!0);if(!c)continue;let h=Number(await e.text(["rev-list","--count",`${c}..${n}`]));(!o||h<o.distance)&&(o={ref:a,base:c,distance:h})}if(o)break}return o?{...r,baseRef:o.ref,baseSha:o.base,baselineMode:"merge-base"}:r}async function za(e,t){let{git:n}=await wo(e,t);return(await co(n)).baseSha}async function uo(e){return new Set(At(await e.run(["ls-files","--cached","--ignored","--exclude-standard","-z"])))}async function Ct(e,t,n){if(!t.length)return;let q=At(await e.run(["check-attr",...n?["--cached"]:[],"-z","--stdin","filter"],{input:`${t.join("\0")}\0`}));for(let r=0;r<q.length;r+=3)q[r+2]==="lfs"&&_("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(q[r])}. Remove the LFS attribute for it, or ignore the file.`)}function Nd(e,t){(e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
|
|
3088
3118
|
`)||e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1\r
|
|
3089
|
-
`))&&_("unsupported_lfs",`${JSON.stringify(t)} is a Git LFS pointer. Canary needs the real file contents.`)}function mo(e,t){(e.length>t.maxTreeFiles||e.reduce((s,o)=>s+o.size,0)>t.maxTreeBytes)&&_("snapshot_limit","This repository has too many files, or too many bytes, to upload.");let n=new Map,q=new Map,r=new Map;for(let s of e){go(s.path,t),s.link!==void 0&&r.set(s.path,s.link);let o=s.path.split("/");for(let i=1;i<=o.length;i++){let a=o.slice(0,i).join("/"),l=a.normalize("NFC").toLowerCase();n.has(l)&&n.get(l)!==a&&_("unsupported_path",`Source paths differ only by case or Unicode normalization: ${JSON.stringify(a)}.`),n.set(l,a);let c=i<o.length;q.has(a)&&q.get(a)!==c&&_("unsupported_path",`Source path is both a directory and a file: ${JSON.stringify(a)}.`),q.set(a,c)}}[...q.values()].filter(Boolean).length+1>t.maxObjects&&_("snapshot_limit","This repository has too many directories to upload.");for(let[s,o]of r){(!o||Buffer.byteLength(o)>t.maxSymlinkBytes||o.startsWith("/")||o.includes("\0")||o.includes("\\")||/^[a-z]:/i.test(o))&&_("unsafe_symlink",`Unsafe symlink target at ${JSON.stringify(s)}.`);let i=o.split("/"),a=s.split("/").slice(0,-1),l=0;for(;i.length;){let c=i.shift();if(!c||c===".")continue;if(c===".."){a.length||_("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(s)}.`),a.pop();continue}
|
|
3119
|
+
`))&&_("unsupported_lfs",`${JSON.stringify(t)} is a Git LFS pointer. Canary needs the real file contents.`)}function mo(e,t){(e.length>t.maxTreeFiles||e.reduce((s,o)=>s+o.size,0)>t.maxTreeBytes)&&_("snapshot_limit","This repository has too many files, or too many bytes, to upload.");let n=new Map,q=new Map,r=new Map;for(let s of e){go(s.path,t),s.link!==void 0&&r.set(s.path,s.link);let o=s.path.split("/");for(let i=1;i<=o.length;i++){let a=o.slice(0,i).join("/"),l=a.normalize("NFC").toLowerCase();n.has(l)&&n.get(l)!==a&&_("unsupported_path",`Source paths differ only by case or Unicode normalization: ${JSON.stringify(a)}.`),n.set(l,a);let c=i<o.length;q.has(a)&&q.get(a)!==c&&_("unsupported_path",`Source path is both a directory and a file: ${JSON.stringify(a)}.`),q.set(a,c)}}[...q.values()].filter(Boolean).length+1>t.maxObjects&&_("snapshot_limit","This repository has too many directories to upload.");for(let[s,o]of r){(!o||Buffer.byteLength(o)>t.maxSymlinkBytes||o.startsWith("/")||o.includes("\0")||o.includes("\\")||/^[a-z]:/i.test(o))&&_("unsafe_symlink",`Unsafe symlink target at ${JSON.stringify(s)}.`);let i=o.split("/"),a=s.split("/").slice(0,-1),l=0;for(;i.length;){let c=i.shift();if(!c||c===".")continue;if(c===".."){a.length||_("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(s)}.`),a.pop();continue}ba(c)&&_("unsafe_symlink",`Symlink enters Git metadata: ${JSON.stringify(s)}.`),a.push(c);let h=n.get(a.join("/").normalize("NFC").toLowerCase());if(h!==void 0&&r.has(h)){++l>t.maxDepth&&_("unsafe_symlink",`Symlink cycle or excessive chain depth at ${JSON.stringify(s)}.`);let d=r.get(h);(d.startsWith("/")||d.includes("\\")||/^[a-z]:/i.test(d))&&_("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(s)}.`),a.pop(),i.unshift(...d.split("/"))}i.length+a.length>t.maxPathBytes&&_("unsafe_symlink","Symlink expansion exceeds the source limit.")}}}async function Eq(e,t){let n=new Map;for(let r of e){let s=r.path.split("/"),o=n;for(let i of s.slice(0,-1))o.has(i)||o.set(i,new Map),o=o.get(i);o.set(s.at(-1),r)}let q=async r=>{let s=[];for(let[o,i]of r)s.push(i instanceof Map?{name:o,mode:"40000",oid:await q(i)}:{name:o,mode:i.mode,oid:i.oid});return s.sort((o,i)=>Buffer.compare(Buffer.from(o.name+(o.mode==="40000"?"/":"")),Buffer.from(i.name+(i.mode==="40000"?"/":"")))),t.put("tree",Buffer.concat(s.map(o=>Buffer.concat([Buffer.from(`${o.mode} ${o.name}\0`),Buffer.from(o.oid,"hex")]))))};return q(n)}async function xa(e,t){let n=t.split("/");for(let q=1;q<=n.length;q++)try{let r=await fo(f1(e,...n.slice(0,q)));if(q===n.length)return r;if(!r.isDirectory())return null}catch(r){if(["ENOENT","ENOTDIR"].includes(r.code??""))return null;throw r}return null}async function Pd(e,t,n,q){let r=await xa(e,t);if(n.set(t,r?i2(r):null),!r||r.isDirectory())return null;if(!r.isFile()&&!r.isSymbolicLink()&&_("unsupported_file",`This is not a regular file or symlink and cannot be uploaded: ${JSON.stringify(t)}.`),r.size>(r.isSymbolicLink()?q.maxSymlinkBytes:q.maxObjectBytes)&&_("snapshot_limit",`This file is too large to upload: ${JSON.stringify(t)}.`),r.isSymbolicLink())return{data:await wd(f1(e,t),{encoding:"buffer"}),mode:"120000"};let s=await fa(f1(e,t),da.O_RDONLY|da.O_NOFOLLOW);try{i2(await s.stat())!==i2(r)&&_("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.");let o=Buffer.alloc(r.size+1),i=0;for(;i<o.length;){let l=await s.read(o,i,o.length-i);if(!l.bytesRead)break;i+=l.bytesRead}return(i!==r.size||i2(await s.stat())!==i2(r))&&_("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped."),{data:o.subarray(0,i),mode:r.mode&73?"100755":"100644"}}finally{await s.close()}}async function ua(e,t,n,q,r,s=[]){let o=s.map(l=>({...l,commit:jq(l.treeHash)})),i=Buffer.from(`# v2 git bundle
|
|
3090
3120
|
${n} refs/canary/base
|
|
3091
3121
|
${q} refs/canary/head
|
|
3092
3122
|
${o.map(l=>`${l.commit} refs/canary/earlier/${l.requestId}
|
|
3093
3123
|
`).join("")}
|
|
3094
|
-
`),a=await
|
|
3124
|
+
`),a=await fa(t,"wx",384);try{let l=e.child(["pack-objects","--stdout","--revs","--no-reuse-delta","--no-reuse-object","--window=0","--threads=1","--compression=6"]),c=ln("sha256"),h=0,d="";l.stderr.on("data",p=>{d.length<8192&&(d+=p.toString())}),l.stdin.on("error",()=>{});let m=new Promise((p,f)=>{l.on("close",p),l.on("error",f)});m.catch(()=>{});let u=async p=>{h+=p.length,h>r.maxBundleBytes&&_("snapshot_limit","This repository is too large to upload, even compressed."),c.update(p),await a.writeFile(p)};try{await u(i),l.stdin.end(`${[q,...o.map(p=>p.commit)].join(`
|
|
3095
3125
|
`)}
|
|
3096
|
-
`);for await(let p of l.stdout)await u(p);return await m!==0&&_("git_source_error",`Cannot package source: ${d.trim()}`),{bytes:h,sha256:c.digest("hex")}}finally{l.kill(),await m.catch(()=>{})}}finally{await a.close()}}async function
|
|
3097
|
-
`);let i=[];for(let a of s)await t.run(["rev-list","--objects","--missing=print",
|
|
3098
|
-
`).some(h=>h.startsWith("?")),()=>!0)||i.push(a);return i}function
|
|
3126
|
+
`);for await(let p of l.stdout)await u(p);return await m!==0&&_("git_source_error",`Cannot package source: ${d.trim()}`),{bytes:h,sha256:c.digest("hex")}}finally{l.kill(),await m.catch(()=>{})}}finally{await a.close()}}async function jd(e,t,n,q,r){let s=n?.versions.slice(0,r.maxEarlierVersions)??[],o=s.length+1;if(!s.length||q.count*o>r.maxObjects||q.bytes*o>r.maxExpandedBytes)return[];await Rq(f1(e,"objects","info"),{recursive:!0}),await vo(f1(e,"objects","info","alternates"),`${n.objects}
|
|
3127
|
+
`);let i=[];for(let a of s)await t.run(["rev-list","--objects","--missing=print",jq(a.treeHash)]).then(c=>c.toString("utf8").split(`
|
|
3128
|
+
`).some(h=>h.startsWith("?")),()=>!0)||i.push(a);return i}function Sa(e){let t={...l2,...e};for(let[n,q]of Object.entries(t))(!Object.hasOwn(l2,n)||!Number.isSafeInteger(q)||q<=0||q>l2[n])&&_("invalid_limit",`Invalid source snapshot limit ${n}.`);return t}async function wo(e,t){let n=await Me(e),q=new ze(n,t),r;try{r=await Me(await q.text(["rev-parse","--show-toplevel"]))}catch(a){if(t?.aborted)throw a;return _("not_a_git_repository","Run this command inside a Git repository.")}let s=new ze(r,t),o=await Me(ga(r,await s.text(["rev-parse","--git-common-dir"]))),i=await s.text(["config","--get-regexp","^(extensions\\.partialclone|remote\\..*\\.promisor|extensions\\.objectformat)$"],!0);return i.split(`
|
|
3099
3129
|
`).some(a=>/^extensions\.objectformat\s+(?!sha1$)/i.test(a))&&_("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(i.split(`
|
|
3100
|
-
`).some(a=>/^extensions\.partialclone\s/i.test(a)||/^remote\..*\.promisor(?:\s|$)/i.test(a)&&!/\s(false|no|off|0)$/i.test(a))||(await
|
|
3130
|
+
`).some(a=>/^extensions\.partialclone\s/i.test(a)||/^remote\..*\.promisor(?:\s|$)/i.test(a)&&!/\s(false|no|off|0)$/i.test(a))||(await yd(f1(o,"objects","pack")).catch(()=>[])).some(a=>a.endsWith(".promisor")))&&_("partial_clone","This is a partial clone. Canary needs every Git object on disk and will not fetch them; use a full clone."),{root:r,common:o,git:s}}async function Md(e,t,n){let q=f1(e,n,".git"),r=await fo(q).catch(()=>null);if(!r?.isFile()||r.size>4096)return!1;let s=/^gitdir: (.+?)\r?\n?$/.exec(await gd(q,"utf8").catch(()=>""))?.[1];if(!s)return!1;let[o,i]=await Promise.all([Me(ga(e,n,s)).catch(()=>null),Me(f1(t,"worktrees")).catch(()=>null)]);return o!==null&&i!==null&&kd(o)===i}async function Nq(e,t,n,q){let r=ka(await e.run(["ls-files","--stage","-z"]),!0),s=q.likeClone?new Set:await uo(e),o=r.filter(c=>Aa(c,s)),i=[];for(let c of At(await e.run(["ls-files","--others","--exclude-standard","-z"])).filter(h=>!Ca(h)))c.endsWith("/")&&(q.likeClone||await Md(t,n,c.slice(0,-1)))||i.push(c);let a=new Set(At(await e.run(["ls-files","-t","-z"])).filter(c=>c.startsWith("S ")).map(c=>c.slice(2))),l=new Set(o.filter(Xe).map(c=>c.path));return{tracked:o,paths:[...new Set([...o.map(c=>c.path),...i])].sort(),skip:a,gitlinks:l}}async function Ia(e){return async()=>ln("sha256").update(await e.run(["ls-files","--stage","-v","-z"])).digest("hex")}function Ra(e,t){for(let n of e)go(n.path,t),["100644","100755","120000",Pq].includes(n.mode)||_("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(n.path)}.`)}function Oa(e,t){let n=e.filter(q=>q.endsWith("/")).map(q=>q.slice(0,-1));if(n.length){let[q]=n,r=n.length===1;_("embedded_repo",`${r?"This directory is a separate Git repository, so its":"These directories are separate Git repositories, so their"} files cannot be uploaded: ${Ta(n)}.`,`remove ${q}/.git to upload its files, add it as a submodule, or ignore ${q}/ in .gitignore or .git/info/exclude${r?"":" (and the same for each directory listed)"}`)}for(let q of e)go(q,t)}function Ea(e,t,n){let q=new Map;return async(r,s,o)=>{Nd(s,r.path);let i=await e.put("blob",s);n&&s.length>=Td&&s.subarray(0,8e3).includes(0)&&n.add(i),r.oid&&r.oid!==i&&_("invalid_source_object",`Git blob contents do not match their hash: ${JSON.stringify(r.path)}.`);let a=(q.get(o)??0)+s.length;q.set(o,a),a>t.maxTreeBytes&&_("snapshot_limit","This repository has too many bytes to upload."),o.push({...r,oid:i,size:s.length,...r.mode==="120000"?{link:wa(s)}:{}})}}async function Na(e,t){let n=t.filter(o=>["100644","100755"].includes(o.mode)).map(o=>o.path);if(!n.length)return new Set;let q=["true","yes","on","1","input"].includes((await e.text(["config","--get","core.autocrlf"],!0)).toLowerCase()),r=new Map,s=At(await e.run(["check-attr","-z","--stdin","text","eol"],{input:`${n.join("\0")}\0`}));for(let o=0;o+2<s.length;o+=3)r.set(s[o],{...r.get(s[o]),[s[o+1]]:s[o+2]});return new Set(n.filter(o=>{let{text:i,eol:a}=r.get(o)??{};return i==="unset"?!1:i==="set"||i==="auto"||a==="lf"||a==="crlf"||q}))}function Ld(e,t){if(!e.includes(`\r
|
|
3101
3131
|
`)||e.subarray(0,8e3).includes(0))return null;let n=Buffer.allocUnsafe(e.length),q=0,r=0;for(let o=e.indexOf(`\r
|
|
3102
3132
|
`);o!==-1;o=e.indexOf(`\r
|
|
3103
|
-
`,o+2))q+=e.copy(n,q,r,o),r=o+1;q+=e.copy(n,q,r);let s=n.subarray(0,q);return
|
|
3104
|
-
`);if(!s||!o||!
|
|
3105
|
-
`)+1)))}catch(q){if(q instanceof W1&&q.code==="git_source_error")return new Set;throw q}}async function
|
|
3133
|
+
`,o+2))q+=e.copy(n,q,r,o),r=o+1;q+=e.copy(n,q,r);let s=n.subarray(0,q);return ln("sha1").update(`blob ${q}\0`).update(s).digest("hex")===t.oid?s:null}async function Pa(e,t,n){let q=f1(e,t);if(!await fo(f1(q,".git")).then(()=>!0,()=>!1))return null;let r;try{r=(await new ze(q,n).run(["rev-parse","--show-toplevel","--verify","--quiet","HEAD^{commit}"],{optional:!0})).toString("utf8")}catch(l){if(l instanceof W1&&l.code==="git_source_error")return null;throw l}let[s,o]=r.trim().split(`
|
|
3134
|
+
`);if(!s||!o||!on.test(o))return null;let[i,a]=await Promise.all([Me(s).catch(()=>null),Me(q).catch(()=>null)]);return i!==null&&i===a?o:null}async function ja(e){let{root:t,current:n,trustFileMode:q,limits:r,stamps:s,heads:o,capture:i,out:a}=e,l=new Map(n.tracked.map(c=>[c.path,c]));for(let c of n.paths){e.signal?.throwIfAborted();let h=l.get(c);if(e.likeClone&&h&&Xe(h)){a.push(Iq(c,h.oid));continue}let d=await Pd(t,c,s,r);if(d){let m=!q&&d.mode!=="120000"&&h&&["100644","100755"].includes(h.mode)?h.mode:d.mode,u=h&&d.mode!=="120000"&&e.converts.has(c)?Ld(d.data,h):null;await i({path:c,mode:m,oid:""},u??d.data,a)}else if(h&&Xe(h))if(s.get(c)!==null){let m=await Pa(t,c,e.signal);o.set(c,m),a.push(Iq(c,m??h.oid))}else n.skip.has(c)&&a.push(Iq(c,h.oid));else if(s.get(c)===null&&n.skip.has(c)){let m=l.get(c);await i(m,await e.blob(m.oid),a)}}}async function Ma(e,t){for(let[n,q]of t){let r=await xa(e,n);(r?i2(r):null)!==q&&_("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}}async function La(e,t,n){for(let[q,r]of t)await Pa(e,q,n)!==r&&_("source_changed","A submodule moved to another commit while the source was being captured. Run the command again once it has settled.")}async function Fd(e,t,n){if(!n.some(q=>q.path===".gitmodules"&&q.mode.startsWith("100")))return new Set;try{let q=At(await e.run(["config","-z","--blob",`${t}:.gitmodules`,"--get-regexp","^submodule\\..*\\.path$"],{optional:!0}));return new Set(q.map(r=>r.slice(r.indexOf(`
|
|
3135
|
+
`)+1)))}catch(q){if(q instanceof W1&&q.code==="git_source_error")return new Set;throw q}}async function $d(e,t,n,q){let r=new Map(n.filter(Xe).map(c=>[c.path,c.oid])),s=q.filter(c=>Xe(c)&&r.get(c.path)!==c.oid);if(!s.length)return;let o=await Fd(e,t,q),i=s.map(c=>c.path).filter(c=>!o.has(c));if(!i.length)return;let[a]=i,l=i.length===1;_("embedded_repo",`${l?"This path is a nested Git repository":"These paths are nested Git repositories"} that .gitmodules does not declare, so none of ${l?"its":"their"} files would be uploaded: ${Ta(i)}.`,`add it as a submodule, or run \`git rm --cached -f ${a}\` and remove ${a}/.git so its files are uploaded as plain files${l?"":" (and the same for each path listed)"}`)}function Dd(e,t){return e?t?e.oid===t.oid&&e.mode===t.mode?null:ma(e.mode)===ma(t.mode)?"M":"T":"D":"A"}async function It(e,t={}){let n=Sa(t.limits),{root:q,common:r,git:s}=await wo(e,t.signal),o=await Me(va());(Tq(q,o)||Tq(r,o))&&_("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let i=await pa(f1(o,"canary-source-")),a,l=()=>lo(i,{recursive:!0,force:!0});try{let c=await co(s,t.baseRef),h=await Ia(s),d=await h(),m=new ze(q,t.signal,!1,{GIT_INDEX_FILE:f1(i,"baseline-index")});await m.run(["read-tree",c.baseSha??"--empty"]);let u=c.baseSha?ka(await s.run(["ls-tree","-r","-z","--full-tree",c.baseSha]),!1):[],p=t.likeClone?new Set:await uo(m),f=u.filter(U=>Aa(U,p)),k=await Nq(s,q,r,t),x=await s.text(["config","--bool","--get","core.fileMode"],!0)!=="false";(f.length>n.maxTreeFiles||k.paths.length>n.maxTreeFiles)&&_("snapshot_limit","This repository has too many files to upload."),Ra([...f,...k.tracked],n),Oa(k.paths,n),await Ct(m,Aq(f),!0),await Ct(s,po(k),!1);let y=f1(i,"repository.git");await Rq(y);let b=new ze(y,t.signal,!0);await b.run(["init","--bare","--quiet","--template="]);let z=new an(y,n,t.signal);a=new Oq(s,n);let C=[],I=[],S=new Set,v=Ea(z,n,S),w=a;for(let U of f)Xe(U)?C.push(Iq(U.path,U.oid)):await v(U,await a.get(U.oid),C);let P=new Map,V=new Map,J1=t.likeClone?await Na(s,k.tracked):new Set;await ja({root:q,current:k,trustFileMode:x,limits:n,signal:t.signal,stamps:P,heads:V,capture:v,blob:U=>w.get(U),out:I,converts:J1,likeClone:t.likeClone===!0}),mo(C,n),mo(I,n);let T1=await Eq(C,z),o1=await Eq(I,z);for(let[U,se]of[[T1,C],[o1,I]])await b.run(["read-tree",U]),await Ct(b,Aq(se),!0);await $d(b,o1,C,I);let R=await z.put("commit",Buffer.from(`tree ${T1}
|
|
3106
3136
|
author ${a2}
|
|
3107
3137
|
committer ${a2}
|
|
3108
3138
|
|
|
@@ -3113,67 +3143,67 @@ author ${a2}
|
|
|
3113
3143
|
committer ${a2}
|
|
3114
3144
|
|
|
3115
3145
|
Canary snapshot current
|
|
3116
|
-
`)),T=f1(i,"source.bundle"),D=t.earlier?await
|
|
3146
|
+
`)),T=f1(i,"source.bundle"),D=t.earlier?await jd(y,b,await t.earlier({root:q,branch:c.branch}).catch(()=>null),z,n).catch(()=>[]):[],J;try{J=await ua(b,T,R,M,n,D)}catch(U){if(!D.length||t.signal?.aborted)throw U;await lo(T,{force:!0}),D=[],J=await ua(b,T,R,M,n)}let q1=await Nq(s,q,r,t);(d!==await h()||JSON.stringify(k.paths)!==JSON.stringify(q1.paths)||!t.likeClone&&JSON.stringify([...p].sort())!==JSON.stringify([...await uo(m)].sort())||JSON.stringify(c)!==JSON.stringify(await co(s,t.baseRef)))&&_("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped."),await Ma(q,P),await La(q,V,t.signal),await Ct(m,Aq(f),!0),await Ct(s,po(k),!1);let Y1=new Map(C.map(U=>[U.path,U])),ye=new Map(I.map(U=>[U.path,U])),K1=[];for(let U of[...new Set([...Y1.keys(),...ye.keys()])].sort()){let se=Dd(Y1.get(U),ye.get(U));se&&K1.push({path:U,status:se})}await a.close(),a=void 0;let _e=I.map(U=>({path:U.path,mode:U.mode,oid:U.oid})),pt=I.filter(Xe).map(U=>U.path),ue=async U=>{let se=await z.put("commit",Buffer.from(ya(o1)));await Rq(f1(y,"objects","info"),{recursive:!0}),await vo(f1(y,"objects","info","alternates"),`${f1(U,"objects")}
|
|
3117
3147
|
`);let Gt=(await b.run(["rev-list","--objects",se])).toString("utf8").split(`
|
|
3118
|
-
`).map(d1=>d1.slice(0,40)).filter(d1=>
|
|
3148
|
+
`).map(d1=>d1.slice(0,40)).filter(d1=>on.test(d1)&&!S.has(d1));await b.run(["pack-objects","--local","--non-empty","-q",f1(U,"objects","pack","pack")],{input:`${Gt.join(`
|
|
3119
3149
|
`)}
|
|
3120
|
-
`})};return{bundlePath:T,manifest:{kind:"local_snapshot",version:2,...J,baseTreeHash:T1,treeHash:o1,baseSha:R,headSha:M,provenance:c,...D.length?{earlier:D}:{}},root:q,files:K1,entries:_e,submodules:pt,keep:ue,dispose:l}}catch(c){throw await a?.close(),await l(),c}}async function
|
|
3150
|
+
`})};return{bundlePath:T,manifest:{kind:"local_snapshot",version:2,...J,baseTreeHash:T1,treeHash:o1,baseSha:R,headSha:M,provenance:c,...D.length?{earlier:D}:{}},root:q,files:K1,entries:_e,submodules:pt,keep:ue,dispose:l}}catch(c){throw await a?.close(),await l(),c}}async function Wd(e,t,n,q,r,s){let o=await Me(va());(Tq(e,o)||Tq(t,o))&&_("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let i=await pa(f1(o,"canary-identity-"));try{let a=new ze(i,s,!0);await a.run(["init","--bare","--quiet","--template="]);let l=new an(i,r,s);for(let c of q.values())await l.put("blob",c);await a.run(["read-tree",await Eq(n,l)]),await Ct(a,Aq(n),!0)}finally{await lo(i,{recursive:!0,force:!0})}}async function hn(e,t={}){let n=Sa(t.limits),{root:q,common:r,git:s}=await wo(e,t.signal),o;try{let i=await ho(s),a=await Ia(s),l=await a(),c=await Nq(s,q,r,t),h=await s.text(["config","--bool","--get","core.fileMode"],!0)!=="false";c.paths.length>n.maxTreeFiles&&_("snapshot_limit","This repository has too many files to upload."),Ra(c.tracked,n),Oa(c.paths,n),await Ct(s,po(c),!1);let d=new an(null,n,t.signal),m=[],u=new Map,p=new Map,f=new Map,k=Ea(d,n),x=(C,I,S)=>(bd(C.path)===".gitattributes"&&f.set(C.path,I),k(C,I,S)),y=t.likeClone?await Na(s,c.tracked):new Set;await ja({root:q,current:c,trustFileMode:h,limits:n,signal:t.signal,stamps:u,heads:p,capture:x,blob:C=>(o??=new Oq(s,n)).get(C),out:m,converts:y,likeClone:t.likeClone===!0}),mo(m,n);let b=await Eq(m,d);[...f.values()].some(C=>/(?:^|\s)filter=lfs(?:\s|$)/m.test(C.toString("utf8")))&&await Wd(q,r,m,f,n,t.signal);let z=await Nq(s,q,r,t);return(l!==await a()||JSON.stringify(c.paths)!==JSON.stringify(z.paths)||i!==await ho(s))&&_("source_changed","The Git state changed while the source was being read. Run the command again once editing has stopped."),await Ma(q,u),await La(q,p,t.signal),{root:q,treeHash:b,branch:i,files:m.map(C=>({path:C.path,mode:C.mode,oid:C.oid}))}}finally{await o?.close()}}var l2,W1,_,Id,Rd,on,Pq,a2,ya,jq,Td,Tq,wa,At,ba,Ed,ze,ho,Oq,an,i2,Ca,Aa,Xe,po,Aq,Ta,Iq,ma,Le=Z(()=>{"use strict";g();l2={maxBundleBytes:4*1024*1024*1024,maxObjectBytes:1024*1024*1024,maxExpandedBytes:16*1024*1024*1024,maxObjects:1e6,maxTreeFiles:5e5,maxTreeBytes:16*1024*1024*1024,maxDepth:64,maxPathBytes:4096,maxSymlinkBytes:4096,maxEarlierVersions:5},W1=class extends Error{constructor(n,q,r){super(q);this.code=n;this.fix=r;this.name="SourceSnapshotError"}},_=(e,t,n)=>{throw new W1(e,t,n)},Id=Cd(Ad),Rd=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),on=/^[a-f0-9]{40}$/,Pq="160000",a2="Canary Snapshot <snapshot@runcanary.ai> 0 +0000",ya=e=>`tree ${e}
|
|
3121
3151
|
author ${a2}
|
|
3122
3152
|
committer ${a2}
|
|
3123
3153
|
|
|
3124
3154
|
Canary snapshot earlier
|
|
3125
|
-
`,
|
|
3155
|
+
`,jq=e=>{let t=ya(e);return ln("sha1").update(`commit ${Buffer.byteLength(t)}\0`).update(t).digest("hex")},Td=1024*1024,Tq=(e,t)=>{let n=xd(e,t);return n===""||!n.startsWith(`..${Sd}`)&&n!==".."&&!zd(n)},wa=e=>{try{return Rd.decode(e)}catch{return _("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},At=e=>e.length?wa(e).split("\0").filter(Boolean):[],ba=e=>{let t=e.normalize("NFC").replace(/[\u200c-\u200f\u202a-\u202e\u206a-\u206f\ufeff]/g,"").toLowerCase().replace(/[ .]+$/g,"");return t===".git"||t.startsWith(".git:")||/^git~[0-9]+(?:\.|$)/.test(t)};Ed=["-c","core.fsmonitor=false","-c","core.untrackedCache=false","-c","core.hooksPath=/dev/null","-c","gc.auto=0","-c","maintenance.auto=false","-c","protocol.allow=never"],ze=class{constructor(t,n,q=!1,r={}){this.cwd=t;this.signal=n;this.isolated=q;this.extra=r}child(t){return this.signal?.throwIfAborted(),vd("git",[...Ed,...t],{cwd:this.cwd,env:{...Od(this.isolated),...this.extra},signal:this.signal,stdio:"pipe"})}async run(t,n={}){let q=this.child(t),r=[],s=0,o="",i;q.on("error",l=>{i=l}),q.stdout.on("data",l=>{s+=l.length,s>(n.maxBytes??256*1024*1024)?(i=new W1("snapshot_limit","This repository's Git metadata is too large to upload."),q.kill()):r.push(l)}),q.stderr.on("data",l=>{o.length<8192&&(o+=l.toString("utf8"))}),q.stdin.on("error",()=>{}),q.stdin.end(n.input);let a=await new Promise(l=>q.on("close",l));if(i)throw i;return a!==0&&!(n.optional&&a===1)&&_("git_source_error",`Cannot read local Git source: ${o.trim()||`git ${t[0]} failed`}`),a===1?Buffer.alloc(0):Buffer.concat(r)}async text(t,n=!1){return(await this.run(t,{optional:n})).toString("utf8").trim()}};ho=async e=>await e.text(["symbolic-ref","--quiet","--short","HEAD"],!0)||null;Oq=class{constructor(t,n){this.limits=n;this.child=t.child(["cat-file","--batch"]),this.child.on("error",q=>{this.error=q}),this.child.stdin.on("error",()=>{}),this.child.stderr.resume(),this.iterator=this.child.stdout[Symbol.asyncIterator]()}child;iterator;pending=Buffer.alloc(0);error;async read(t){let n=[],q=t;for(;q;){if(!this.pending.length){let s=await this.iterator.next();if(s.done)throw this.error??new W1("missing_source_object","A Git object this repository needs is missing on disk. Canary does not fetch; restore it, then run the command again.");this.pending=s.value}let r=Math.min(q,this.pending.length);n.push(this.pending.subarray(0,r)),this.pending=this.pending.subarray(r),q-=r}return Buffer.concat(n,t)}async get(t){this.child.stdin.write(`${t}
|
|
3126
3156
|
`);let n="";for(;!n.endsWith(`
|
|
3127
|
-
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[q,r,s]=n.trim().split(" "),o=Number(s);(q!==t||r!=="blob"||!Number.isSafeInteger(o)||o<0)&&_("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),o>this.limits.maxObjectBytes&&_("snapshot_limit","A file in this repository is too large to upload.");let i=await this.read(o);return(await this.read(1))[0]!==10&&_("git_source_error","Invalid Git object framing."),i}async close(){this.child.exitCode!==null||this.child.signalCode!==null||(this.child.stdin.end(),this.child.kill(),await new Promise(t=>this.child.on("close",()=>t())))}},on=class{constructor(t,n,q){this.directory=t;this.limits=n;this.signal=q}sizes=new Map;expanded=0;get count(){return this.sizes.size}get bytes(){return this.expanded}async put(t,n){this.signal?.throwIfAborted(),n.length>this.limits.maxObjectBytes&&_("snapshot_limit","A file in this repository is too large to upload.");let q=Buffer.from(`${t} ${n.length}\0`),r=an("sha1").update(q).update(n).digest("hex");if(!this.sizes.has(r)&&((this.sizes.size+1>this.limits.maxObjects||this.expanded+n.length>this.limits.maxExpandedBytes)&&_("snapshot_limit","This repository has too many files, or too many bytes, to upload."),this.sizes.set(r,n.length),this.expanded+=n.length,this.directory!==null)){let s=f1(this.directory,"objects",r.slice(0,2));await Iq(s,{recursive:!0}),await vo(f1(s,r.slice(2)),await Ad(Buffer.concat([q,n]),{level:6}),{mode:384,flag:"wx"})}return r}};i2=e=>`${e.dev}:${e.ino}:${e.mode}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`;xa=e=>e.split("/").some(t=>t.toLowerCase()===".git"),Sa=(e,t)=>!t.has(e.path)&&!xa(e.path),Xe=e=>e.mode===Nq;po=e=>e.paths.filter(t=>!e.gitlinks.has(t)),Cq=e=>e.filter(t=>!Xe(t)).map(t=>t.path);Ia=e=>e.slice(0,5).map(t=>JSON.stringify(t)).join(", ")+(e.length>5?` and ${e.length-5} more`:"");Aq=(e,t)=>({path:e,mode:Nq,oid:t,size:0});da=e=>e==="120000"?"symlink":e===Nq?"submodule":"file"});import{readFileSync as Wd,renameSync as az,rmSync as Hd,writeFileSync as lz}from"node:fs";async function hn(e,t,n={}){try{await W("/api/v1/cli/events",{method:"POST",token:t.token,baseUrl:t.apiUrl,body:{outcome:e,...n.runId?{runId:n.runId}:{}},signal:AbortSignal.timeout(n.timeoutMs??1500)})}catch{}}function Ma(e,t){return!t||e.decision!=="allow"||!Bd.has(e.cause)?Promise.resolve():hn(`gate_allow:${e.cause}`,t,{timeoutMs:500})}function La(e,t=Date.now()){try{let n=Ke(e,_d),q=Date.parse(JSON.parse(Wd(n,"utf8")).at??"");return Hd(n,{force:!0}),Number.isFinite(q)&&t-q>=0&&t-q<Ud}catch{return!1}}var Bd,_d,Ud,jq=Z(()=>{"use strict";g();p1();M1();Bd=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);_d="last-denial.json",Ud=1440*60*1e3});import{randomUUID as Gd}from"node:crypto";import{readdirSync as Vd,readFileSync as fz,renameSync as Jd,rmSync as Fa,statSync as Yd,writeFileSync as Kd}from"node:fs";import{dirname as $a,join as Xd}from"node:path";import{gunzipSync as yz,gzipSync as Qd}from"node:zlib";function Da(e,t,n){try{let q=Ke(e,eu(t)),r=`${q}.${Gd()}.tmp`,s=Qd(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:t,entries:n.map(o=>[o.path,o.mode,o.oid])})));try{Kd(r,s,{flag:"wx",mode:384}),Jd(r,q)}catch(o){throw Fa(r,{force:!0}),o}for(let o of Vd($a(q))){if(!o.startsWith("tree-")||!o.endsWith(".json.gz"))continue;let i=Xd($a(q),o);try{Date.now()-Yd(i).mtimeMs>Zd&&Fa(i,{force:!0})}catch{}}}catch{}}var Zd,eu,bo=Z(()=>{"use strict";g();M1();Zd=720*60*60*1e3,eu=e=>`tree-${e}.json.gz`});import{createHash as tu}from"node:crypto";import{constants as Wa}from"node:fs";import{open as nu}from"node:fs/promises";import{Readable as qu}from"node:stream";function Fq(e){if(!Lq(e,e&&typeof e=="object"&&Object.hasOwn(e,"earlier")?[...zo,"earlier"]:zo)||e.earlier!==void 0&&!ru(e.earlier))return!1;let t=e.provenance;return e.kind==="local_snapshot"&&e.version===2&&typeof e.sha256=="string"&&/^[a-f0-9]{64}$/.test(e.sha256)&&typeof e.bytes=="number"&&Number.isSafeInteger(e.bytes)&&e.bytes>0&&e.bytes<=l2.maxBundleBytes&&[e.baseTreeHash,e.treeHash,e.baseSha,e.headSha].every(n=>typeof n=="string"&&ko.test(n))&&Lq(t,Ga)&&[t.headSha,t.baseSha].every(n=>n===null||typeof n=="string"&&ko.test(n))&&[t.branch,t.baseRef].every(n=>n===null||typeof n=="string"&&n.length>0&&n.length<=1024&&!/[\x00-\x1f\x7f]/.test(n))&&["explicit","merge-base","whole-project"].includes(t.baselineMode)}function su(e,t){return JSON.stringify(e.earlier??null)===JSON.stringify(t.earlier??null)&&zo.filter(n=>n!=="provenance").every(n=>e[n]===t[n])&&Ga.every(n=>e.provenance[n]===t.provenance[n])}function cn(e,t){if(!Lq(e,["uploadId","expiresAt","status","source"])||typeof e.uploadId!="string"||!dn.test(e.uploadId)||typeof e.expiresAt!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.expiresAt)||!Number.isFinite(Date.parse(e.expiresAt))||!["pending","uploading","completed","cancelled"].includes(e.status)||!Fq(e.source)||t?.uploadId!==void 0&&t.uploadId!==e.uploadId||t?.manifest!==void 0&&!su(t.manifest,e.source))throw new x1(502,"invalid_upload_response","Canary's answer does not match the upload in progress.","Run the command again to continue the upload.",t?.uploadId);return e}function Va(e){if(!dn.test(e))throw new x1(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${Ua}/${e}`}function ou(e,t){return e instanceof x1?new x1(e.status,e.code,e.message,e.fix,t):e instanceof L?new x1(e.status,"source_upload_failed",e.message,e.fix,t):new x1(0,"source_upload_failed",e instanceof Error?e.message:"The source upload failed.","Run the command again to continue the upload.",t)}function Mq(e){if(e.status==="completed")return e;throw e.status==="cancelled"?new x1(410,"source_upload_cancelled","This upload was cancelled.",void 0,e.uploadId):new x1(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",e.uploadId)}async function Ha(e,t,n={}){let q=await(n.request??W)(Va(e),{...t});return cn(q,{uploadId:e})}async function*Ja(e,t,n){let q=0;for(;q<t;){n?.throwIfAborted();let r=Buffer.allocUnsafe(Math.min(64*1024,t-q)),s=await e.read(r,0,r.length,q);if(!s.bytesRead)throw new x1(0,"source_changed","The source changed while it was being uploaded. Run the command again.");q+=s.bytesRead,yield r.subarray(0,s.bytesRead)}}async function Ba(e,t,n){let q=await e.stat();if(!q.isFile()||q.size!==t.bytes)throw new x1(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let r=tu("sha256");for await(let o of Ja(e,t.bytes,n))r.update(o);let s=await e.stat();if(r.digest("hex")!==t.sha256||s.size!==q.size||s.mtimeMs!==q.mtimeMs||s.ctimeMs!==q.ctimeMs)throw new x1(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function _a(e,t,n,q){let r=qu.from(Ja(e,t.manifest.bytes,t.signal));try{let s=await(q.fetch??fetch)(`${t.baseUrl.replace(/\/+$/,"")}${Va(n)}/content`,{method:"PUT",headers:{...(q.headers??Je)(),authorization:`Bearer ${t.token}`,"content-type":"application/octet-stream","content-length":String(t.manifest.bytes)},body:r,duplex:"half",signal:t.signal,redirect:"error"});if(!s.ok){let o={};try{o=await s.json()}catch{}throw new x1(s.status,typeof o.code=="string"?o.code:"source_upload_failed",typeof o.error=="string"?o.error:s.statusText,typeof o.fix=="string"?o.fix:void 0,n)}return Mq(cn(await s.json(),{uploadId:n,manifest:t.manifest}))}catch(s){throw s instanceof x1?s:new x1(0,"source_upload_uncertain","The connection dropped before Canary confirmed the upload.","An earlier upload is still in progress. Run the command again to continue it.",n)}finally{r.destroy()}}async function $q(e,t={}){if(!Fq(e.manifest)||!dn.test(e.workspaceId)||!dn.test(e.repositoryId))throw new x1(0,"invalid_source_receipt","A captured source, a workspace, and a repository are required before uploading.");let n={token:e.token,baseUrl:e.baseUrl,signal:e.signal},q;if(e.uploadId&&(q=cn(await Ha(e.uploadId,n,t),{uploadId:e.uploadId,manifest:e.manifest}),q.status!=="pending"))return Mq(q);let r=await nu(e.bundlePath,Wa.O_RDONLY|Wa.O_NOFOLLOW);try{if(await Ba(r,e.manifest,e.signal),q||(q=cn(await(t.request??W)(Ua,{...n,method:"POST",body:{workspaceId:e.workspaceId,repositoryId:e.repositoryId,source:e.manifest}}),{manifest:e.manifest})),e.onReceipt?.(q),q.status!=="pending")return Mq(q);try{return await _a(r,e,q.uploadId,t)}catch(s){if(e.signal?.aborted||!(z1(s)||s instanceof L&&s.status===409))throw s;let o=cn(await Ha(q.uploadId,n,t),{uploadId:q.uploadId,manifest:e.manifest});return o.status!=="pending"?Mq(o):(await Ba(r,e.manifest,e.signal),await _a(r,e,q.uploadId,t))}}catch(s){throw q?ou(s,q.uploadId):s}finally{await r.close()}}var x1,Ua,dn,ko,zo,Ga,Lq,ru,Dq=Z(()=>{"use strict";g();p1();ie();Le();x1=class extends L{constructor(n,q,r,s,o){super(n,r,s);this.code=q;this.uploadId=o;this.name="SourceUploadError"}},Ua="/api/v1/cli/source-uploads",dn=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,ko=/^[a-f0-9]{40}$/,zo=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],Ga=["headSha","branch","baseRef","baseSha","baselineMode"],Lq=(e,t)=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),ru=e=>Array.isArray(e)&&e.length>=1&&e.length<=l2.maxEarlierVersions&&e.every(t=>Lq(t,["requestId","treeHash"])&&typeof t.requestId=="string"&&dn.test(t.requestId)&&typeof t.treeHash=="string"&&ko.test(t.treeHash))&&new Set(e.map(t=>t.requestId)).size===e.length});import{createHash as iu,randomUUID as au}from"node:crypto";import{readFileSync as lu,renameSync as hu,rmSync as Ya,writeFileSync as cu}from"node:fs";function Ka(e,t,n,q="verify"){let r=iu("sha256").update(JSON.stringify([n,e,q])).digest("hex");return Ke(t,`source-upload-${r}.json`)}function Xa(e){try{let t=JSON.parse(lu(e,"utf8"));if(typeof t.uploadId!="string"||!/^[a-f0-9-]{36}$/i.test(t.uploadId)||typeof t.expiresAt!="string"||!Number.isFinite(Date.parse(t.expiresAt)))throw new Error("invalid upload record");return{uploadId:t.uploadId,expiresAt:t.expiresAt}}catch(t){if(t.code!=="ENOENT")throw new x1(0,"invalid_upload_receipt","Canary's record of an earlier upload under CANARY_HOME/local-repositories is unreadable.","Fix or remove that file, then run the command again.")}}function un(e,t,n,q){let r=Ka(e,t,n,q.requestKey),s=Xa(r);s&&(!q.uploadId||s.uploadId===q.uploadId)&&Ya(r,{force:!0})}async function h2(e,t,n,q,r={}){let s=Ka(e.manifest,t,n,r.requestKey),o=r.fresh?void 0:Xa(s),i=o&&Date.parse(o.expiresAt)>Date.now()?o.uploadId:void 0,a=await $q({bundlePath:e.bundlePath,manifest:e.manifest,workspaceId:t.workspaceId,repositoryId:n,token:q,baseUrl:t.apiUrl,...i?{uploadId:i}:{},onReceipt:({uploadId:l,expiresAt:c})=>{let h=`${s}.${au()}.tmp`;try{cu(h,JSON.stringify({uploadId:l,expiresAt:c})+`
|
|
3128
|
-
`,{flag:"wx",mode:384}),
|
|
3129
|
-
`),do:Array.isArray(e.do)?e.do:[]}}function
|
|
3130
|
-
`);let n=[e.failed?`\u2717 ${ae(e.failed,"finding")}`:"",e.passed?`\u2713 ${e.passed} passed`:"",e.blocked?`\u23F8 ${e.blocked} could not be verified`:""].filter(Boolean);e.findings.length===0&&e.errored===0?t.push(`\u2713 Clean \u2014 no findings in this change${e.passed?` \xB7 ${e.passed} passed`:""}.`):t.push(`${e.failed?"":"\u2713 No verified findings"}${e.failed||n.length===0?"":" \xB7 "}${n.join(" \xB7 ")}`);for(let q of e.findings)t.push(""),t.push(`${
|
|
3157
|
+
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[q,r,s]=n.trim().split(" "),o=Number(s);(q!==t||r!=="blob"||!Number.isSafeInteger(o)||o<0)&&_("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),o>this.limits.maxObjectBytes&&_("snapshot_limit","A file in this repository is too large to upload.");let i=await this.read(o);return(await this.read(1))[0]!==10&&_("git_source_error","Invalid Git object framing."),i}async close(){this.child.exitCode!==null||this.child.signalCode!==null||(this.child.stdin.end(),this.child.kill(),await new Promise(t=>this.child.on("close",()=>t())))}},an=class{constructor(t,n,q){this.directory=t;this.limits=n;this.signal=q}sizes=new Map;expanded=0;get count(){return this.sizes.size}get bytes(){return this.expanded}async put(t,n){this.signal?.throwIfAborted(),n.length>this.limits.maxObjectBytes&&_("snapshot_limit","A file in this repository is too large to upload.");let q=Buffer.from(`${t} ${n.length}\0`),r=ln("sha1").update(q).update(n).digest("hex");if(!this.sizes.has(r)&&((this.sizes.size+1>this.limits.maxObjects||this.expanded+n.length>this.limits.maxExpandedBytes)&&_("snapshot_limit","This repository has too many files, or too many bytes, to upload."),this.sizes.set(r,n.length),this.expanded+=n.length,this.directory!==null)){let s=f1(this.directory,"objects",r.slice(0,2));await Rq(s,{recursive:!0}),await vo(f1(s,r.slice(2)),await Id(Buffer.concat([q,n]),{level:6}),{mode:384,flag:"wx"})}return r}};i2=e=>`${e.dev}:${e.ino}:${e.mode}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`;Ca=e=>e.split("/").some(t=>t.toLowerCase()===".git"),Aa=(e,t)=>!t.has(e.path)&&!Ca(e.path),Xe=e=>e.mode===Pq;po=e=>e.paths.filter(t=>!e.gitlinks.has(t)),Aq=e=>e.filter(t=>!Xe(t)).map(t=>t.path);Ta=e=>e.slice(0,5).map(t=>JSON.stringify(t)).join(", ")+(e.length>5?` and ${e.length-5} more`:"");Iq=(e,t)=>({path:e,mode:Pq,oid:t,size:0});ma=e=>e==="120000"?"symlink":e===Pq?"submodule":"file"});import{readFileSync as Hd,renameSync as hz,rmSync as Bd,writeFileSync as cz}from"node:fs";async function cn(e,t,n={}){try{await W("/api/v1/cli/events",{method:"POST",token:t.token,baseUrl:t.apiUrl,body:{outcome:e,...n.runId?{runId:n.runId}:{}},signal:AbortSignal.timeout(n.timeoutMs??1500)})}catch{}}function Fa(e,t){return!t||e.decision!=="allow"||!_d.has(e.cause)?Promise.resolve():cn(`gate_allow:${e.cause}`,t,{timeoutMs:500})}function $a(e,t=Date.now()){try{let n=Ke(e,Ud),q=Date.parse(JSON.parse(Hd(n,"utf8")).at??"");return Bd(n,{force:!0}),Number.isFinite(q)&&t-q>=0&&t-q<Gd}catch{return!1}}var _d,Ud,Gd,Mq=Z(()=>{"use strict";g();p1();M1();_d=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);Ud="last-denial.json",Gd=1440*60*1e3});import{randomUUID as Vd}from"node:crypto";import{readdirSync as Jd,readFileSync as gz,renameSync as Yd,rmSync as Da,statSync as Kd,writeFileSync as Xd}from"node:fs";import{dirname as Wa,join as Qd}from"node:path";import{gunzipSync as bz,gzipSync as Zd}from"node:zlib";function Ha(e,t,n){try{let q=Ke(e,tu(t)),r=`${q}.${Vd()}.tmp`,s=Zd(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:t,entries:n.map(o=>[o.path,o.mode,o.oid])})));try{Xd(r,s,{flag:"wx",mode:384}),Yd(r,q)}catch(o){throw Da(r,{force:!0}),o}for(let o of Jd(Wa(q))){if(!o.startsWith("tree-")||!o.endsWith(".json.gz"))continue;let i=Qd(Wa(q),o);try{Date.now()-Kd(i).mtimeMs>eu&&Da(i,{force:!0})}catch{}}}catch{}}var eu,tu,bo=Z(()=>{"use strict";g();M1();eu=720*60*60*1e3,tu=e=>`tree-${e}.json.gz`});import{createHash as nu}from"node:crypto";import{constants as Ba}from"node:fs";import{open as qu}from"node:fs/promises";import{Readable as ru}from"node:stream";function $q(e){if(!Fq(e,e&&typeof e=="object"&&Object.hasOwn(e,"earlier")?[...zo,"earlier"]:zo)||e.earlier!==void 0&&!su(e.earlier))return!1;let t=e.provenance;return e.kind==="local_snapshot"&&e.version===2&&typeof e.sha256=="string"&&/^[a-f0-9]{64}$/.test(e.sha256)&&typeof e.bytes=="number"&&Number.isSafeInteger(e.bytes)&&e.bytes>0&&e.bytes<=l2.maxBundleBytes&&[e.baseTreeHash,e.treeHash,e.baseSha,e.headSha].every(n=>typeof n=="string"&&ko.test(n))&&Fq(t,Ja)&&[t.headSha,t.baseSha].every(n=>n===null||typeof n=="string"&&ko.test(n))&&[t.branch,t.baseRef].every(n=>n===null||typeof n=="string"&&n.length>0&&n.length<=1024&&!/[\x00-\x1f\x7f]/.test(n))&&["explicit","merge-base","whole-project"].includes(t.baselineMode)}function ou(e,t){return JSON.stringify(e.earlier??null)===JSON.stringify(t.earlier??null)&&zo.filter(n=>n!=="provenance").every(n=>e[n]===t[n])&&Ja.every(n=>e.provenance[n]===t.provenance[n])}function dn(e,t){if(!Fq(e,["uploadId","expiresAt","status","source"])||typeof e.uploadId!="string"||!un.test(e.uploadId)||typeof e.expiresAt!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.expiresAt)||!Number.isFinite(Date.parse(e.expiresAt))||!["pending","uploading","completed","cancelled"].includes(e.status)||!$q(e.source)||t?.uploadId!==void 0&&t.uploadId!==e.uploadId||t?.manifest!==void 0&&!ou(t.manifest,e.source))throw new x1(502,"invalid_upload_response","Canary's answer does not match the upload in progress.","Run the command again to continue the upload.",t?.uploadId);return e}function Ya(e){if(!un.test(e))throw new x1(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${Va}/${e}`}function iu(e,t){return e instanceof x1?new x1(e.status,e.code,e.message,e.fix,t):e instanceof L?new x1(e.status,"source_upload_failed",e.message,e.fix,t):new x1(0,"source_upload_failed",e instanceof Error?e.message:"The source upload failed.","Run the command again to continue the upload.",t)}function Lq(e){if(e.status==="completed")return e;throw e.status==="cancelled"?new x1(410,"source_upload_cancelled","This upload was cancelled.",void 0,e.uploadId):new x1(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",e.uploadId)}async function _a(e,t,n={}){let q=await(n.request??W)(Ya(e),{...t});return dn(q,{uploadId:e})}async function*Ka(e,t,n){let q=0;for(;q<t;){n?.throwIfAborted();let r=Buffer.allocUnsafe(Math.min(64*1024,t-q)),s=await e.read(r,0,r.length,q);if(!s.bytesRead)throw new x1(0,"source_changed","The source changed while it was being uploaded. Run the command again.");q+=s.bytesRead,yield r.subarray(0,s.bytesRead)}}async function Ua(e,t,n){let q=await e.stat();if(!q.isFile()||q.size!==t.bytes)throw new x1(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let r=nu("sha256");for await(let o of Ka(e,t.bytes,n))r.update(o);let s=await e.stat();if(r.digest("hex")!==t.sha256||s.size!==q.size||s.mtimeMs!==q.mtimeMs||s.ctimeMs!==q.ctimeMs)throw new x1(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function Ga(e,t,n,q){let r=ru.from(Ka(e,t.manifest.bytes,t.signal));try{let s=await(q.fetch??fetch)(`${t.baseUrl.replace(/\/+$/,"")}${Ya(n)}/content`,{method:"PUT",headers:{...(q.headers??Je)(),authorization:`Bearer ${t.token}`,"content-type":"application/octet-stream","content-length":String(t.manifest.bytes)},body:r,duplex:"half",signal:t.signal,redirect:"error"});if(!s.ok){let o={};try{o=await s.json()}catch{}throw new x1(s.status,typeof o.code=="string"?o.code:"source_upload_failed",typeof o.error=="string"?o.error:s.statusText,typeof o.fix=="string"?o.fix:void 0,n)}return Lq(dn(await s.json(),{uploadId:n,manifest:t.manifest}))}catch(s){throw s instanceof x1?s:new x1(0,"source_upload_uncertain","The connection dropped before Canary confirmed the upload.","An earlier upload is still in progress. Run the command again to continue it.",n)}finally{r.destroy()}}async function Dq(e,t={}){if(!$q(e.manifest)||!un.test(e.workspaceId)||!un.test(e.repositoryId))throw new x1(0,"invalid_source_receipt","A captured source, a workspace, and a repository are required before uploading.");let n={token:e.token,baseUrl:e.baseUrl,signal:e.signal},q;if(e.uploadId&&(q=dn(await _a(e.uploadId,n,t),{uploadId:e.uploadId,manifest:e.manifest}),q.status!=="pending"))return Lq(q);let r=await qu(e.bundlePath,Ba.O_RDONLY|Ba.O_NOFOLLOW);try{if(await Ua(r,e.manifest,e.signal),q||(q=dn(await(t.request??W)(Va,{...n,method:"POST",body:{workspaceId:e.workspaceId,repositoryId:e.repositoryId,source:e.manifest}}),{manifest:e.manifest})),e.onReceipt?.(q),q.status!=="pending")return Lq(q);try{return await Ga(r,e,q.uploadId,t)}catch(s){if(e.signal?.aborted||!(z1(s)||s instanceof L&&s.status===409))throw s;let o=dn(await _a(q.uploadId,n,t),{uploadId:q.uploadId,manifest:e.manifest});return o.status!=="pending"?Lq(o):(await Ua(r,e.manifest,e.signal),await Ga(r,e,q.uploadId,t))}}catch(s){throw q?iu(s,q.uploadId):s}finally{await r.close()}}var x1,Va,un,ko,zo,Ja,Fq,su,Wq=Z(()=>{"use strict";g();p1();ie();Le();x1=class extends L{constructor(n,q,r,s,o){super(n,r,s);this.code=q;this.uploadId=o;this.name="SourceUploadError"}},Va="/api/v1/cli/source-uploads",un=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,ko=/^[a-f0-9]{40}$/,zo=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],Ja=["headSha","branch","baseRef","baseSha","baselineMode"],Fq=(e,t)=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n)),su=e=>Array.isArray(e)&&e.length>=1&&e.length<=l2.maxEarlierVersions&&e.every(t=>Fq(t,["requestId","treeHash"])&&typeof t.requestId=="string"&&un.test(t.requestId)&&typeof t.treeHash=="string"&&ko.test(t.treeHash))&&new Set(e.map(t=>t.requestId)).size===e.length});import{createHash as au,randomUUID as lu}from"node:crypto";import{readFileSync as hu,renameSync as cu,rmSync as Xa,writeFileSync as du}from"node:fs";function Qa(e,t,n,q="verify"){let r=au("sha256").update(JSON.stringify([n,e,q])).digest("hex");return Ke(t,`source-upload-${r}.json`)}function Za(e){try{let t=JSON.parse(hu(e,"utf8"));if(typeof t.uploadId!="string"||!/^[a-f0-9-]{36}$/i.test(t.uploadId)||typeof t.expiresAt!="string"||!Number.isFinite(Date.parse(t.expiresAt)))throw new Error("invalid upload record");return{uploadId:t.uploadId,expiresAt:t.expiresAt}}catch(t){if(t.code!=="ENOENT")throw new x1(0,"invalid_upload_receipt","Canary's record of an earlier upload under CANARY_HOME/local-repositories is unreadable.","Fix or remove that file, then run the command again.")}}function mn(e,t,n,q){let r=Qa(e,t,n,q.requestKey),s=Za(r);s&&(!q.uploadId||s.uploadId===q.uploadId)&&Xa(r,{force:!0})}async function h2(e,t,n,q,r={}){let s=Qa(e.manifest,t,n,r.requestKey),o=r.fresh?void 0:Za(s),i=o&&Date.parse(o.expiresAt)>Date.now()?o.uploadId:void 0,a=await Dq({bundlePath:e.bundlePath,manifest:e.manifest,workspaceId:t.workspaceId,repositoryId:n,token:q,baseUrl:t.apiUrl,...i?{uploadId:i}:{},onReceipt:({uploadId:l,expiresAt:c})=>{let h=`${s}.${lu()}.tmp`;try{du(h,JSON.stringify({uploadId:l,expiresAt:c})+`
|
|
3158
|
+
`,{flag:"wx",mode:384}),cu(h,s)}finally{Xa(h,{force:!0})}}});return{...a.source,uploadId:a.uploadId}}var Hq=Z(()=>{"use strict";g();M1();Wq()});import{readFileSync as e4}from"node:fs";function vn(e){let t=Array.isArray(e.lines)?e.lines.filter(n=>typeof n=="string"):[];return{...e,say:typeof e.say=="string"?e.say:t.join(`
|
|
3159
|
+
`),do:Array.isArray(e.do)?e.do:[]}}function vu(e){if(e===void 0)return;let t=e;try{e==="-"?t=e4(0,"utf8"):e.startsWith("@")&&(t=e4(e.slice(1),"utf8"))}catch(n){throw new xe("brief_unreadable",`could not read the brief from ${e==="-"?"stdin":e.slice(1)}: ${n instanceof Error?n.message:String(n)}`,"pass the brief as text, @<file>, or - (stdin)")}return t.trim()===""?void 0:t}function Se(e){return e==="P3"?null:e==="P0"||e==="P1"?e:"P2"}function gu(e,t){if(Se(e.materiality)===null)return null;let q=t??null;return e.result==="fail"?{checkRunId:e.checkRunId,kind:"fail",proof:q?.isStatic===!1?"runtime":"source",headline:F(q?.finding?.headline)||F(e.title),summary:F(q?.verdict?.reasonOneLiner??q?.finding?.whatWasTested),location:r4(q?.finding?.nextActionCodeRef??q?.codeRefs?.[0]),fix:F(q?.finding?.reproduce)||null}:e.result==="blocked"?{checkRunId:e.checkRunId,kind:"blocked",proof:"none",headline:F(e.title),summary:F(q?.verdict?.reasonOneLiner)||(gn[e.blockedReason??""]??""),location:r4(q?.checkReadback?.codeRefs?.[0]??q?.codeRefs?.[0]),fix:null}:null}function Co(e,t,n){let q=Q();W("/api/v1/cli/events",{method:"POST",...q?{token:q}:{},...n?{baseUrl:n}:{},body:{outcome:e,...t?{runId:t}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function o4(e){if(e.status!=="completed"||e.stageB.status==="failed")return 2;let t=e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns;return t>0&&e.stageC.checks.length===t?2:0}async function Ao(e,t,n={}){let q=h=>W(h,{token:t,...n.baseUrl?{baseUrl:n.baseUrl}:{}}),r=new Map,s="",o=new Set,i=!1,a=!1,l=null,c=Date.now();for(;;){let h;try{h=(await q(`/api/v1/red-team/runs/${e}`)).run,l=null}catch(u){if(z1(u)&&(l??=Date.now(),Date.now()-l<uu)){n.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await pn(xo);continue}throw u}for(let u of h.stageC.checks)if(!(!(u.status==="completed"&&(u.result==="fail"||u.result==="blocked"))||r.has(u.checkRunId))){if(!le.test(u.checkRunId)){r.set(u.checkRunId,null);continue}try{r.set(u.checkRunId,await q(`/api/v1/red-team/runs/${e}/checks/${u.checkRunId}/finding`))}catch(f){z1(f)||r.set(u.checkRunId,null)}}for(let u of h.stageC.checks){if(o.has(u.checkRunId)||!(u.status==="completed"||u.status==="failed"||u.status==="cancelled")||Se(u.materiality)===null)continue;o.add(u.checkRunId);let f=r.get(u.checkRunId),k=u.status!=="completed"?"!":u.result==="pass"?"\u2713":u.result==="fail"?"\u2717":"\u23F8",x=u.status!=="completed"?"errored":u.result==="pass"?"passed":u.result==="fail"?f?.isStatic===!1?"verified failure":"finding from the code":"could not verify";n.onProgress?.(`${k} ${x}: ${F(u.title)}`)}h.stageB.status!=="completed"&&(a=!0);let d=h.stageC.checks.length>0||h.stageB.finalChecksCount===0||So.has(h.status);!i&&h.stageB.status==="completed"&&d&&(i=!0,n.onProgress?.(wu(h,a?Date.now()-c:null,r)));let m=yu(h);if(m!==s&&(n.onProgress?.(m),s=m),So.has(h.status)){for(let p=0;p<3;p++){let f=h.stageC.checks.filter(k=>k.status==="completed"&&(k.result==="fail"||k.result==="blocked")&&!r.has(k.checkRunId));if(f.length===0)break;await pn(Math.min(xo,1e3));for(let k of f)try{r.set(k.checkRunId,await q(`/api/v1/red-team/runs/${e}/checks/${k.checkRunId}/finding`))}catch(x){(!z1(x)||p===2)&&r.set(k.checkRunId,null)}}let u=h.stageC.checks.filter(p=>p.status==="completed"&&(p.result==="fail"||p.result==="blocked")).sort((p,f)=>s4[Se(p.materiality)??"P2"]-s4[Se(f.materiality)??"P2"]).map(p=>gu(p,r.get(p.checkRunId)??null)).filter(p=>p!==null);return{run:h,findings:u}}if(Date.now()-c>t4)throw new xe("still_running",`run ${e} is still ${h.status} after ${Math.round(t4/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await pn(xo)}}function yu(e){if(e.status==="queued")return"\u2026 queued";if(e.phase==="stage_b"||e.stageC.checks.length===0){let n=e.stageB.risksFound??0;return`\u2026 analyzing the change${n?` \xB7 ${n} risk${n===1?"":"s"} found`:""}`}return`\u2026 ${e.stageC.completedCheckRuns+e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns}/${e.stageC.checks.length} checks done \xB7 ${e.stageC.results.fail} failed`}function wu(e,t,n=new Map){let q=e.stageC.checks.filter(h=>Se(h.materiality)!==null),r=h=>h.result==="fail"&&n.get(h.checkRunId)?.isStatic!==!1,s=q.filter(r).length,o=e.stageC.checks.filter(h=>h.status==="failed"||h.status==="cancelled").length,i=q.filter(h=>!r(h)&&h.status!=="failed"&&h.status!=="cancelled").length,a=e.stageC.results.pass+e.stageC.results.blocked+q.filter(h=>h.result==="fail"&&n.get(h.checkRunId)?.isStatic===!1).length,l=So.has(e.status)?a>0?"verified in sandboxes":"not run":"verifying in sandboxes";return`${t===null?"analysis done":`analysis done in ${Math.max(1,Math.round(t/6e4))} min`} \xB7 ${ae(s,"finding")} from the code \xB7 ${i} runtime check${i===1?"":"s"}${o?` \xB7 ${o} errored`:""} \xB7 ${l}`}function bu(e,t,n){let q=e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns;if(o4(e)===2)return`Verification did not complete (${e.status})${q?`: ${ae(q,"check")} errored`:""}; nothing was verified.`;let r=t.filter(c=>c.kind==="fail"&&c.proof==="runtime").length,s=t.filter(c=>c.kind==="fail"&&c.proof==="source").length,o=t.filter(c=>c.kind==="blocked").length,i=e.stageC.results.pass,a=[`${ae(r,"verified failure")}`,`${ae(i,"check")} passed`,`${ae(s,"finding")} from the code (source-reasoned, not run)`,...o?[`${o} could not be verified`]:[],`${ae(q,"check")} errored`],l=i===0&&r===0&&o===0&&q===0;return`${a.join("; ")}.${l?" Nothing in this change was executed.":""}${ku(n)}`}function ku(e){let t=e?e.reverifiable-e.carried:0;return!e||t<=0?"":` ${t} of run ${e.sourceRunId.slice(0,8)}'s ${ae(e.reverifiable,"failed check")} ${t===1?"was":"were"} not re-run (reported disputed or skipped).`}function zu(e,t){let n=e.slice(0,8);if(!t)return`re-checking the failed set of run ${n} \u2014`;let q=`of run ${n}'s ${ae(t.reverifiable,"failed check")}`;return t.excludedReported>0?`re-checking ${t.carried} ${q} (${t.excludedReported} reported disputed or skipped, not re-run) \u2014`:`re-checking all ${t.reverifiable} failed checks of run ${n} \u2014`}function Io(e,t,n,q){return{ok:!0,runId:e.runId,treeHash:t,status:e.status,findings:n,summary:bu(e,n,q),failed:n.filter(r=>r.kind==="fail").length,passed:e.stageC.results.pass,blocked:n.filter(r=>r.kind==="blocked").length,errored:e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns,exitCode:o4(e),failureMessage:e.failure?.publicMessage??null,...q?{reverify:q}:{}}}function Ro(e){let t=[];if(t.push(`Receipt ${vq(e.treeHash)} \xB7 run ${F(e.runId)}`),e.exitCode===2)return t.push(`\u2717 Verification did not complete (${F(e.status)})${e.failureMessage?`: ${F(e.failureMessage)}`:""}`),e.errored>0&&t.push(` ${ae(e.errored,"check")} errored \u2014 nothing was verified; this is not a clean result.`),t.push(` Run \`canary verify\` again; if it repeats, report run ${F(e.runId)}.`),t.join(`
|
|
3160
|
+
`);let n=[e.failed?`\u2717 ${ae(e.failed,"finding")}`:"",e.passed?`\u2713 ${e.passed} passed`:"",e.blocked?`\u23F8 ${e.blocked} could not be verified`:""].filter(Boolean);e.findings.length===0&&e.errored===0?t.push(`\u2713 Clean \u2014 no findings in this change${e.passed?` \xB7 ${e.passed} passed`:""}.`):t.push(`${e.failed?"":"\u2713 No verified findings"}${e.failed||n.length===0?"":" \xB7 "}${n.join(" \xB7 ")}`);for(let q of e.findings)t.push(""),t.push(`${xu[q.kind]} ${F(q.headline)}${Su[q.kind]}`),q.summary&&t.push(` ${F(q.summary)}`),q.location&&t.push(` \u2192 ${F(q.location)}`),q.fix&&t.push(` reproduce: ${F(q.fix)}`);return e.errored>0&&t.push(`
|
|
3131
3161
|
(${ae(e.errored,"check")} errored and could not be verified.)`),t.push(`
|
|
3132
3162
|
${e.summary}`),t.join(`
|
|
3133
|
-
`)}function
|
|
3163
|
+
`)}function yn(e){let t=e;return!t||!["EPERM","EACCES","EROFS"].includes(t.code??"")||typeof t.path!="string"||!t.path.startsWith(G())?null:{message:`Canary keeps its records under ${G()} and cannot write there from here (${t.code})`,fix:"run the command outside the sandbox, or let it write under that folder"}}function $(e,t,n,q,r,s={}){if(e)console.log(JSON.stringify({ok:!1,error:t,message:n,...q?{fix:q}:{},exitCode:r,...s}));else{let o=typeof s.runId=="string"?s.runId:null;console.error(`\u2717 ${F(n)}${q?`
|
|
3134
3164
|
fix: ${F(q)}`:""}${o?`
|
|
3135
|
-
run: ${F(o)}`:""}`)}process.exitCode=r}async function
|
|
3136
|
-
${b.next}`);return}let k;try{k=await Ao(u,i,{...s,onProgress:m})}catch(y){if(y instanceof xe)return o(y.code,y.message,y.fix,2,{runId:u});if(y instanceof L){let b=y.status===401||y.status===403;return o("api_error",`${y.message} \u2014 run ${u} may still be running`,y.fix??(b?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:u,httpStatus:y.status})}throw y}let x={...Io(k.run,l.manifest.treeHash,k.findings,p),source:l.manifest,repositoryId:h.repositoryId};console.log(n?JSON.stringify(x):Ro(x)),process.exitCode=x.exitCode}function
|
|
3137
|
-
`).map(
|
|
3138
|
-
`).trim(),
|
|
3139
|
-
|
|
3140
|
-
`);le=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
|
3141
|
-
`).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${
|
|
3142
|
-
`)}function
|
|
3143
|
-
${t.snippet}`):console.log(`${t.result==="unchanged"?"\xB7":"\u2713"} ${t.file}: ${t.result==="written"?"added":t.result==="removed"?"removed":"nothing to change"}${t.detail?`; ${t.detail}`:""}${
|
|
3144
|
-
`));return}if(e.plan){console.log(e.json?JSON.stringify({ok:!0,plan:r}):
|
|
3165
|
+
run: ${F(o)}`:""}`)}process.exitCode=r}async function Cu(e,t,n,q,r={}){let s={baseUrl:r.baseUrl??a1()};Q1({cwd:e,agent:n,mode:q!==void 0?"reverify_failed":"full"});let o=(y,b,z,C=3,I={})=>{$(n,y,b,z,C,I),Co(`exit${C}:${y}`,I.runId,s.baseUrl)},i=Q();if(!i)return o("not_logged_in","Not logged in","run `canary login` first");if(q!==void 0&&!le.test(q))return o("bad_run_id",`"${q}" is not a run id`,"pass the run id from your last `canary verify` (see the receipt line), e.g. `canary verify --failed <run-id>`");let a,l;try{a=vu(t),l=await It(e,{baseRef:r.baseRef})}catch(y){if(y instanceof W1||y instanceof xe)return o(y.code,y.message,y.fix);throw y}if(l.manifest.treeHash===l.manifest.baseTreeHash&&q===void 0)return await l.dispose(),o("nothing_to_verify","The current source matches the selected baseline","make a change, or choose a different baseline with --base <ref>");let c,h,d;try{c=await je(e,i,s.baseUrl),h=await Pe({...c,token:i});let y=AbortSignal.timeout(3e3);if((await Cq(c,i,y).catch(z=>{throw y.aborted?new L(0,"Checking this repository's setup timed out","run `canary verify` again"):z}))?.state!=="ready")throw new xe("setup_required",`This repository isn't set up for you in ${F(h.workspace.name)} yet`,"run `canary setup`");d=await h2(l,c,h.repositoryId,i,{fresh:!0}),Ha(c,l.manifest.treeHash,l.entries)}catch(y){if(y instanceof n1||y instanceof xe)return o(y.code,y.message,"fix"in y?y.fix:void 0);if(y instanceof L)return o("api_error",y.message,y.fix,y.status>=400&&y.status<500?3:2);throw y}finally{await l.dispose()}a===void 0&&q===void 0&&console.error("! No --brief given \u2014 Canary will attack the change using the submitted source and baseline. A brief with acceptance criteria and must-not-break finds more."),Zt();let m=y=>{n?console.error(` ${y}`):console.log(` ${y}`)};l.manifest.provenance.baselineMode==="whole-project"?m("No comparison branch found: reviewing the whole eligible project against an empty baseline."):m(`Baseline: ${F(l.manifest.provenance.baseRef)} \xB7 source ${vq(l.manifest.treeHash)}`);let u,p,f;{let y,b=yo(l.manifest.provenance.branch),z=()=>W("/api/v1/cli/runs",{method:"POST",token:i,...s,body:{repositoryId:h.repositoryId,workspaceId:c.workspaceId,source:d,...a!==void 0?{brief:a}:{},...b?{branch:b}:{},...q!==void 0?{reverifySourceRunId:q}:{}}});try{for(let I=1;;I+=1)try{y=await z();break}catch(S){if(I>=n4||!z1(S)||S instanceof L&&S.runId&&le.test(S.runId))throw S;m(`${S.message} \u2014 retrying (${I}/${n4-1})`),await pn(q4*I)}}catch(I){if(I instanceof L){let S=!z1(I)&&I.status>=400&&I.status<500,v=I.fix??(I.status===401||I.status===403?"run `canary login`":S?void 0:"run `canary verify` again in a minute"),w={httpStatus:I.status,...I.runId?{runId:I.runId}:{}};return S?$(n,"api_error",I.message,v,3,w):o("api_error",I.message,v,2,w)}throw I}if(y.treeHash!==l.manifest.treeHash||y.headSha!==l.manifest.headSha)return $(n,"api_error","Canary's answer does not match the source that was uploaded","run `canary verify` again",2);if(!le.test(y.runId))return $(n,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);u=y.runId;let C=q?zu(q,y.reverify):y.created?"submitted":"same verification inputs as an existing run \u2014 following it:";m(`${C} ${vq(l.manifest.treeHash)} \xB7 run ${u} \xB7 ${ae(l.files.length,"file")}`),p=y.reverify,f=y.created,f&&cn(`started_by:${$a(c)?"hook":n||Ys().harness!=="unknown"?"skill":"manual"}`,{token:i,apiUrl:s.baseUrl},{runId:u})}if(r.noWait){let y=!1;if(q!==void 0&&!p&&!f)for(let z=0;z<3&&!p;z++)try{p=(await W(`/api/v1/red-team/runs/${u}`,{token:i,...s})).run.reverify;break}catch(C){if(!z1(C)||z===2){y=!0;break}await pn(q4*(z+1))}let b={ok:!0,runId:u,runUrl:pu(u),treeHash:l.manifest.treeHash,created:f,...p?{reverify:p}:{},next:`${fu(u)}${y?" What this re-check carried could not be read just now; the document from `canary run wait` will say.":""}`};console.log(n?JSON.stringify(b):`Run ${u} is under way: ${b.runUrl}
|
|
3166
|
+
${b.next}`);return}let k;try{k=await Ao(u,i,{...s,onProgress:m})}catch(y){if(y instanceof xe)return o(y.code,y.message,y.fix,2,{runId:u});if(y instanceof L){let b=y.status===401||y.status===403;return o("api_error",`${y.message} \u2014 run ${u} may still be running`,y.fix??(b?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:u,httpStatus:y.status})}throw y}let x={...Io(k.run,l.manifest.treeHash,k.findings,p),source:l.manifest,repositoryId:h.repositoryId};console.log(n?JSON.stringify(x):Ro(x)),process.exitCode=x.exitCode}function i4(e){e.command("verify").description("Pressure-test your local change set with Canary (no commit or PR needed)").option("--brief <text>","what the change intends and must not break (text, @file, or - for stdin)").option("--failed <runId>","re-check only the failed checks of an earlier run, against your current (fixed) code").option("--json","output one JSON document").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","compare directly with a local commit (use HEAD for worktree changes only)").option("--no-wait","start the run and return its id at once; collect it later with `canary run wait <runId>`").action(async t=>{try{Q()&&await(await Promise.resolve().then(()=>(Rt(),a4))).installByDefault({json:t.json===!0}),await Cu(t.dir??process.cwd(),t.brief,t.json===!0,t.failed,{baseRef:t.base,noWait:t.wait===!1})}catch(n){let q=yn(n);if(q){$(t.json===!0,"home_not_writable",q.message,q.fix,2),Co("exit2:home_not_writable");return}$(t.json===!0,"internal_error",n instanceof Error?n.message:String(n),void 0,2),Co("exit2:internal_error")}})}var xo,uu,t4,So,xe,F,mu,Fe,fn,le,pu,fu,pn,n4,q4,r4,s4,gn,xu,Su,ae,Qe=Z(()=>{"use strict";g();p1();ie();e1();G3();o2();M1();Le();Mq();bo();Hq();bt();xo=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,uu=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,t4=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,So=new Set(["completed","failed","cancelled"]),xe=class extends Error{constructor(n,q,r){super(q);this.code=n;this.fix=r;this.name="VerifyError"}},F=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ").trim(),mu=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ").trimEnd(),Fe=e=>e.split(`
|
|
3167
|
+
`).map(mu).join(`
|
|
3168
|
+
`).trim(),fn=e=>e.map(Fe).filter(t=>t!=="").join(`
|
|
3169
|
+
|
|
3170
|
+
`);le=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pu=e=>`${Ee().replace(/\/+$/,"")}/runs/${e}`,fu=e=>`Collect the result with \`canary run wait ${e}\` (it returns when the run has finished; run it in the background where your shell allows).`,pn=e=>new Promise(t=>setTimeout(t,e)),n4=3,q4=1e3;r4=e=>e?e.startLine?`${e.file}:${e.startLine}`:e.file:null;s4={P0:0,P1:1,P2:2},gn={setup_install_failure:"the app's dependencies could not be installed in the sandbox",setup_boot_failure:"the app failed to start in the sandbox",health_timeout:"the app never became healthy in the sandbox",runtime_precondition:"a runtime precondition for this check could not be reached",missing_capability:"the sandbox lacks a capability this check needs",missing_required_secret:"a required secret is not configured for this repository"};xu={fail:"\u2717",blocked:"\u23F8"},Su={fail:"",blocked:" (could not be verified)"},ae=(e,t)=>`${e} ${t}${e===1?"":"s"}`});var a4={};Ur(a4,{hooksStatus:()=>wn,installByDefault:()=>bn,pendingPushCheck:()=>Eo,registerHooks:()=>No,runHooksInstall:()=>d4,runHooksUninstall:()=>u4,statusLines:()=>Bq});function Oo(e,t=[]){try{P1(n=>({...n,hooks:{...n.hooks?.codex?{codex:n.hooks.codex}:{},state:e,at:new Date().toISOString(),...t.length?{refused:t}:{}}}))}catch{}}function Au(e){return[To,"It is a hook in the agent's own settings, which the agent runs. `canary hooks install` adds:","",...e.flatMap(t=>[` ${t.file}`,` ${t.summary}`,...t.snippet.split(`
|
|
3171
|
+
`).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${l4}`].join(`
|
|
3172
|
+
`)}function c4(e){for(let t of e)t.result==="refused"?console.log(`\u2717 ${t.file} was left alone: ${t.detail}. To do it by hand:
|
|
3173
|
+
${t.snippet}`):console.log(`${t.result==="unchanged"?"\xB7":"\u2713"} ${t.file}: ${t.result==="written"?"added":t.result==="removed"?"removed":"nothing to change"}${t.detail?`; ${t.detail}`:""}${h4(t.edit?.backup??t.removed?.backup)}`)}function Iu(e,t){for(let n of t)n.afterInstall&&e.some(q=>q.harness===n.id&&q.result==="written")&&console.log(`${n.label}: ${n.afterInstall}`);dq("canary")||console.log("Note: `canary` is not on PATH in this shell. The agent's harness must be able to find it, or the hook does nothing."),e.some(n=>n.result==="written")&&zt()==="off"&&console.log("The check itself is switched off (`canary gate on` turns it on).")}function Ru(e,t){return t?.length?{targets:e.filter(n=>t.includes(n.id)&&n.detected()),unknown:t.filter(n=>!e.some(q=>q.id===n&&q.detected()))}:{targets:e.filter(n=>n.byDefault&&n.detected()),unknown:[]}}async function d4(e){let t=e.targets??tn(),{targets:n,unknown:q}=Ru(t,e.harnesses),r=n.flatMap(o=>o.plan());if(q.length)return $(e.json,"harness_not_found",`not found on this machine: ${q.join(", ")}`,`known: ${t.map(o=>o.id).join(", ")}; one counts as found once its settings folder exists`,3);if(!n.length){let o=t.filter(i=>!i.byDefault&&i.detected()).map(i=>`\`canary hooks install --harness ${i.id}\` registers ${i.label}, which is not covered by default yet.`);e.json?console.log(JSON.stringify({ok:!0,installed:[],note:"no coding agent to register by default"})):console.log([`No coding agent to register was found on this machine (looked for ${t.filter(i=>i.byDefault).map(i=>i.label).join(", ")}).`,...o].join(`
|
|
3174
|
+
`));return}if(e.plan){console.log(e.json?JSON.stringify({ok:!0,plan:r}):Au(r));return}let s=n.flatMap(o=>o.install());s.some(o=>o.result!=="refused")&&Oo("installed"),e.json?console.log(JSON.stringify({ok:!s.some(o=>o.result==="refused"),outcomes:s,canaryOnPath:dq("canary"),mode:zt(),notes:n.filter(o=>o.afterInstall&&s.some(i=>i.harness===o.id&&i.result==="written")).map(o=>`${o.label}: ${o.afterInstall}`)})):(c4(s),Iu(s,n)),s.some(o=>o.result==="refused")&&(process.exitCode=2)}function u4(e){let t=(e.targets??tn()).flatMap(n=>n.uninstall());Oo("removed"),e.json?console.log(JSON.stringify({ok:!t.some(n=>n.result==="refused"),outcomes:t})):c4(t),t.some(n=>n.result==="refused")&&(process.exitCode=2)}function wn(e=tn()){return{mode:zt(),registration:K().hooks?.state??null,canaryOnPath:dq("canary"),harnesses:e.map(t=>({harness:t.id,label:t.label,detected:t.detected(),items:t.status()}))}}function Eo(e){try{return zt()==="off"?[]:wn(e).harnesses.flatMap(t=>t.items.filter(n=>n.state==="untrusted"&&n.pending).map(n=>({harness:t.harness,label:t.label,...n.pending})))}catch{return[]}}function Bq(e){let t=[];for(let n of e.harnesses){if(!n.detected&&n.items.every(q=>q.state==="missing")){t.push(`${n.label}: not found on this machine`);continue}for(let q of n.items)t.push(`${n.label}: ${q.state==="registered"?"registered":q.state==="untrusted"?"registered, not yet trusted":q.state==="missing"?"not registered":q.state} (${q.file})${q.detail?`: ${q.detail}`:""}`)}return e.harnesses.some(n=>n.items.some(q=>q.state!=="missing"))&&!e.canaryOnPath&&t.push("`canary` is not on PATH in this shell; a harness that cannot find it runs no check."),e.harnesses.some(n=>n.items.some(q=>q.state!=="missing"))&&t.push("Switch the check off: `canary gate off`. Take it out: `canary hooks uninstall` (before `npm uninstall`; afterwards `npx -y @runcanary/cli hooks uninstall` does the same)."),t}async function bn(e){try{if(process.env.CI||!e.targets&&process.env.NODE_TEST_CONTEXT)return;let t=K();if(t.agentSkills===!1||t.hooks?.state==="removed")return;let n=new Set(t.hooks?.refused??[]);if(t.hooks?.state==="installed"&&!n.size)return;let q=(e.targets??tn()).filter(h=>h.byDefault&&h.detected());if(!q.length)return;let r=q.flatMap(h=>h.install()),s=r.filter(h=>h.result==="written"),o=r.filter(h=>h.result==="refused"&&!n.has(h.file)),i=r.filter(h=>h.result==="refused").map(h=>h.file);if(r.some(h=>h.result!=="refused")||t.hooks?.state==="installed")Oo("installed",i);else if(i.length)try{P1(h=>({...h,hooks:{...h.hooks,refused:i}}))}catch{}let a=q.filter(h=>h.afterInstall&&s.some(d=>d.harness===h.id)).map(h=>`${h.label}: ${h.afterInstall}`),l=s.filter(h=>!h.edit),c=s.filter(h=>h.edit);if(e.json){(s.length||o.length)&&console.error(JSON.stringify({notice:"push_check",added:s.map(h=>h.file),leftAlone:o.map(h=>({file:h.file,why:h.detail})),...c.length?{edits:c.map(h=>({file:h.file,line:h.edit.line,text:h.edit.text,backup:h.edit.backup,created:h.edit.created}))}:{},message:To,off:"canary gate off",remove:"canary hooks uninstall",notes:a}));return}if(l.length){let h=q.filter(d=>l.some(m=>m.harness===d.id)).map(d=>d.label).join(" and ");console.error(`
|
|
3145
3175
|
Canary added its push check to ${h} (${l.map(d=>d.file).join(", ")}).
|
|
3146
3176
|
${To}
|
|
3147
|
-
${
|
|
3177
|
+
${l4}`)}for(let h of c)console.error(`Canary ${h.edit.created?"created":"edited"} ${h.file}: ${h.detail}${h4(h.edit.backup)}. \`canary hooks uninstall\` takes it out again.`);for(let h of a)console.error(h);for(let h of o)console.error(`Canary left ${h.file} alone (${h.detail}): not added there: ${h.summary}. \`canary hooks install --plan\` shows what to add by hand.`)}catch{}}function No(e){let t=e.command("hooks").description("The push check in your coding agents' settings: install, uninstall, status. Login adds it; `canary hooks uninstall` takes it out, also as `npx -y @runcanary/cli hooks uninstall` once the CLI is gone");t.command("install").description("Add the push check to your coding agents' settings (login does this by default)").option("--plan","show exactly what would be added, and add nothing").option("--harness <id...>","register only these (claude, codex, cursor); default: every one found that is covered by default").option("--json","print one JSON document").action(async n=>{try{await d4({plan:n.plan===!0,json:n.json===!0,harnesses:n.harness})}catch(q){$(n.json===!0,"internal_error",q instanceof Error?q.message:String(q),void 0,2)}}),t.command("uninstall").description("Remove exactly what `canary hooks install` added (do this before `npm uninstall`; afterwards `npx -y @runcanary/cli hooks uninstall` does the same)").option("--json","print one JSON document").action(n=>{try{u4({json:n.json===!0})}catch(q){$(n.json===!0,"internal_error",q instanceof Error?q.message:String(q),void 0,2)}}),t.command("status").description("Show where the check is registered, and anything that stops it from running").option("--json","print one JSON document").action(n=>{let q=wn();if(n.json===!0)console.log(JSON.stringify({ok:!0,...q}));else{console.log(`The push check is ${q.mode}.`);for(let r of Bq(q))console.log(r)}})}var To,l4,h4,Rt=Z(()=>{"use strict";g();e1();fq();js();Qe();To="Before an agent pushes or opens a pull request, Canary checks whether its chat has run /canary with nothing left to fix. If not, the agent asks you first. No other command is affected.",l4="Switch it off: `canary gate off` \xB7 take it out: `canary hooks uninstall`.";h4=e=>e?` (the file as it was: ${e})`:""});g();g();var Oi=z6(Ti(),1),{program:Aw,createCommand:Iw,createArgument:Rw,createOption:Tw,CommanderError:Ow,InvalidArgumentError:Ew,InvalidOptionArgumentError:Nw,Command:Ei,Argument:Pw,Option:Ni,Help:jw}=Oi.default;g();Ws();mq();p1();bt();e1();Rt();M1();import{createHash as Du,randomBytes as A4}from"node:crypto";import{spawn as Wu}from"node:child_process";import{createServer as Hu}from"node:http";g();p1();o2();function m4(e){try{return new URL(e).href.replace(/\/+$/,"")}catch{return}}var Po=ca;async function p4(e,t,n,q){let r=await W("/api/v1/cli/workspaces",{token:e.token,baseUrl:q,signal:AbortSignal.timeout(3e3)});if(!Array.isArray(r?.workspaces)||r.workspaces.some(h=>!h||typeof h.id!="string"||!h.id||typeof h.name!="string"))throw new Error("The service returned an invalid workspace list. Run canary login again.");let s=[...new Map(r.workspaces.map(({id:h,name:d})=>[h,{id:h,name:d}])).values()],i=t.user?.id===e.user.id&&m4(n)===m4(q)?s.find(h=>h.id===t.team?.id):void 0,a=s.length===1?s[0]:void 0,l=i??a??s.find(h=>h.id===e.team.id)??s[0]??{id:"",name:"No workspace selected"},c=Po();return{workspace:l,workspaces:s,source:i?"saved in CLI":a?"only workspace":"active on platform",selectionRequired:!i&&!a,...c?{repository:c}:{},...s.length?{}:{workspaceNotice:"Create or join a workspace in Canary, then run canary login again."}}}async function _q(e,t,n,q=AbortSignal.timeout(3e3)){try{let r=await Cq({apiUrl:e.apiUrl,userId:e.userId,workspaceId:n},e.token,q);return r?{state:r.state}:void 0}catch{return}}function Uq(e,t){let n=/^\d+$/.test(t)?Number(t)-1:-1,q=n>=0?e.workspaces.filter((r,s)=>s===n):e.workspaces.filter(r=>r.id===t||r.name.toLowerCase()===t.toLowerCase());if(q.length!==1)throw new Error(q.length?"Workspace name is ambiguous. Use its ID.":"Workspace not found. Run canary workspace list.");return q[0]}g();g();import{stripVTControlCharacters as f4}from"node:util";var S1="\x1B[";function zn(e,t,n){let q={gold:"38;2;255;212;0",text:"39",muted:"90",green:"32"}[t];return n?`${S1}${q}m${e}${S1}0m`:e}function l1(e){return f4(e).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var jo=new Intl.Segmenter(void 0,{granularity:"grapheme"});function v4(e){if(/^[\p{Mark}\u200d\ufe0f]+$/u.test(e))return 0;if(new RegExp("\\p{Extended_Pictographic}|\\p{Regional_Indicator}|\\u20e3","u").test(e))return 2;let t=e.codePointAt(0);return t>=4352&&(t<=4447||t===9001||t===9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=131072)?2:1}function kn(e){return[...jo.segment(f4(e))].reduce((t,n)=>t+v4(n.segment),0)}function Gq(e,t){let n=0,q="";for(let r of e.split(/(\x1b\[[0-9;]*m)/)){if(r.startsWith(S1)){q+=r;continue}for(let{segment:s}of jo.segment(r))n+=v4(s),n<=t&&(q+=s)}return q}function Ze(e,t){let n=[],q="";for(let r of l1(e).split(/\s+/)){q&&kn(q+" "+r)>t&&(n.push(q),q="");for(let{segment:s}of jo.segment((q?" ":"")+r))kn(q+s)>t&&q&&(n.push(q),q=""),q+=s}return q&&n.push(q),n}function c2(e){let t=[];return{render(n){if(n.join(`
|
|
3148
3178
|
`)===t.join(`
|
|
3149
|
-
`))return;let q=Math.max(2,e.columns||80),r=Math.max(3,e.rows||24),s=Math.min(r-1,t.reduce((o,i)=>o+Math.max(1,Math.ceil(
|
|
3179
|
+
`))return;let q=Math.max(2,e.columns||80),r=Math.max(3,e.rows||24),s=Math.min(r-1,t.reduce((o,i)=>o+Math.max(1,Math.ceil(kn(i)/q)),0));e.write((s?`\r${S1}${s}A`:"")+`${S1}0J`+(n.length?n.join(`\r
|
|
3150
3180
|
`)+`\r
|
|
3151
|
-
`:"")),t=n}}}function
|
|
3181
|
+
`:"")),t=n}}}function g4(e,t,n){return e?[JSON.stringify({authorizeUrl:n})]:[t?"Opening your browser to authorize the Canary CLI...":"Open this URL in your browser to authorize the Canary CLI:",(t?`If it doesn't open, visit:
|
|
3152
3182
|
`:" ")+n+`
|
|
3153
|
-
`]}function v4(e,t){return e?JSON.stringify({waiting:!0,elapsedSeconds:t}):`Still waiting for the sign-in to finish in your browser (${Math.max(1,Math.round(t/60))} min). The link above is still valid.`}function Gq(e){return`Repository ${l1(e)}`}var Tt="Next: in your coding agent, type /canary to check your changes.";function g4(e){return e?.result==="added"||e?.result==="updated"?`Canary plugin ${e.result==="added"?"added to":"updated in"} Claude Code: new chats load it.`:e?.result==="refused"?`Couldn't add Canary's plugin to Claude Code: ${e.detail} (${e.file}). Checks that need this machine wait for it: fix that, then run canary login again.`:null}g();import{stripVTControlCharacters as Ru}from"node:util";g();var d2=[[" "," \u2880\u28F4\u28F6\u28FF\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F\u2801 "," \u28B0\u28FF\u2841\u28B8\u28FF\u28FF\u2801 "," \u2838\u28FF\u28E7\u2818\u28BF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F "," \u28B0\u28FF\u2840\u28BA\u28FF\u28FF "," \u2838\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280F "," \u28B0\u28FF \u28FF\u28FF\u28FF "," \u28B8\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u281F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280B "," \u28B0\u28FF \u28FF\u28FF\u285F "," \u28B8\u28FF\u28C7\u2839\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FF\u281F\u2809 "," \u28E0\u2802\u28FC\u28FF\u28FF\u2803 "," \u28B0\u28FF \u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u283B\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28F7\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E4\u28F6\u28FF\u281B\u2801 "," \u28E0\u2802\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28E6\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u287F\u280B\u2801 "," \u28E0\u2882\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28BB\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28BF\u28E6\u28D9\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B "," \u28E0\u28A0\u28FF\u28FF\u285F "," \u28F8\u28FF\u28B8\u28FF\u28FF\u2843 "," \u28BB\u28FF\u284C\u28BF\u28FF\u2847 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28E6\u28D9\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u281F\u2809 "," \u28F4\u28A0\u28FF\u28FF\u284F "," \u28F8\u28C7\u28B8\u28FF\u28FF "," \u28BF\u28FF\u285C\u28BF\u28FF\u2846 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u28DB\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28A0\u28F4\u28FE\u281F\u2801 "," \u2874\u28B0\u28FF\u28FF\u2807 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28BF\u28FF\u285C\u28FF\u28FF\u2844 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u287B\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u280B\u2801 "," \u2874\u28F0\u28FF\u28FF\u2803 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u283F\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2874\u28FC\u28FF\u28FF\u2801 "," \u28FC\u2847\u28FF\u28FF\u28CF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2854\u28FC\u28FF\u287F "," \u28FC\u2867\u28FF\u28FF\u2847 "," \u28FF\u28F7\u28FB\u28FF\u28F7\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28FF\u287B\u28F7\u2844 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u285F\u2801 "," \u2880\u2854\u28FE\u28FF\u285F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28E7\u28FF\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28FD\u287F\u28F7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u281F\u2801 "," \u2880\u28D4\u28FE\u28FF\u284F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28EF\u28BF\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28DD\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2807 "," \u28FE\u28F8\u28FF\u28FF "," \u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28BF\u28FF\u28DF\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2803 "," \u28FE\u28BC\u28FF\u28FF "," \u2818\u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28FF\u28FF\u28DF\u28FF\u28E6\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "]];var zn="\x1B[",Tu={gold:"33",text:"39",muted:"90",green:"32"};function Ou(e,t,n){if(!n)return e;let q=t==="gold"?"38;2;255;212;0":Tu[t];return`${zn}${q}m${e}${zn}0m`}function y4(e){return Ru(e).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var w4=1.4;function Eu(e){let{phase:t,seconds:n,columns:q,rows:r,color:s,open:o}=e,i=e.phaseSeconds??n,a=1.4,c=n%(a+.2),h=y=>Math.sin(y/a*Math.PI*2)*Math.sin(y/a*Math.PI),d=t==="waiting"&&c<a?h(c):t==="success"&&i<w4?h(i):0,m=d2[Math.max(0,Math.min(16,Math.round(d*10)+8))],u=t==="success"?"You're signed in.":t==="failed"?"Sign-in didn't finish.":t==="saving"?"Securing your CLI session":n<1.5?"Let's get you connected.":"Waiting for browser approval",p=t==="success"?"Your terminal is ready for the next step.":t==="failed"?"Run canary login to try again.":t==="saving"?"Exchanging authorization and saving credentials.":o&&n<1.5?"Opening your browser...":"Finish signing in at the link above.",f=(y,b="text")=>Ou(y,b,s),k=t==="success"?"green":t==="failed"?"muted":"gold",x;if(r<5)x=[f(u)];else if(q>=72&&r>=18){let y={1:f("CANARY","gold"),3:f(u,t==="success"?"green":"text"),5:f(p,"muted")};x=["",...m.map((b,z)=>` ${f(b,k)} ${y[z]??""}`)]}else q>=42&&r>=23?x=["",...m.map(y=>` ${f(y,k)}`),` ${f("CANARY","gold")}`,"",` ${f(u)}`,` ${f(p,"muted")}`]:x=["",` ${f("CANARY","gold")}`,` ${f(u)}`];return r>=10&&(x.push("",` ${f("\u2500".repeat(Math.max(1,Math.min(54,q-5))),"gold")}`),(t==="waiting"||t==="saving")&&x.push(` ${f("Ctrl+C","muted")} ${f("cancel sign-in","muted")}`),x.push("")),x.slice(0,Math.max(1,r-2)).map(y=>{let b=0;return y.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,z=>z.startsWith("\x1B")||++b<q?z:"")})}function b4(e){if(e.json||!e.animation||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"||process.env.CI||process.env.CANARY_NO_ANIMATION)return;let t=process.stderr,n=!process.env.NO_COLOR,q=performance.now(),r="waiting",s=q,o=f=>{r=f,s=performance.now()},i=c2(t),a=!1;function l(){if(a)return;let f=Math.max(2,t.columns||80),k=Math.max(3,t.rows||24),x=performance.now(),y=Eu({phase:r,seconds:(x-q)/1e3,phaseSeconds:(x-s)/1e3,columns:f,rows:k,color:n,open:e.open});i.render(y)}let c=()=>t.write(`${zn}0m${zn}?25h`);function h(){a||(a=!0,clearInterval(p),t.removeListener("resize",l),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",u),process.removeListener("exit",c),c())}function d(f){o("failed"),l(),h(),t.write(`Sign-in cancelled.
|
|
3154
|
-
`),process.exit(f)}let m=()=>d(130),u=()=>d(143),p=setInterval(l,80);return p.unref(),t.on("resize",l),process.once("SIGINT",m),process.once("SIGTERM",u),process.once("exit",c),t.write(`${
|
|
3155
|
-
Workspace ${
|
|
3183
|
+
`]}function y4(e,t){return e?JSON.stringify({waiting:!0,elapsedSeconds:t}):`Still waiting for the sign-in to finish in your browser (${Math.max(1,Math.round(t/60))} min). The link above is still valid.`}function Vq(e){return`Repository ${l1(e)}`}var Tt="Next: in your coding agent, type /canary to check your changes.";function w4(e){return e?.result==="added"||e?.result==="updated"?`Canary plugin ${e.result==="added"?"added to":"updated in"} Claude Code: new chats load it.`:e?.result==="refused"?`Couldn't add Canary's plugin to Claude Code: ${e.detail} (${e.file}). Checks that need this machine wait for it: fix that, then run canary login again.`:null}g();import{stripVTControlCharacters as Tu}from"node:util";g();var d2=[[" "," \u2880\u28F4\u28F6\u28FF\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F\u2801 "," \u28B0\u28FF\u2841\u28B8\u28FF\u28FF\u2801 "," \u2838\u28FF\u28E7\u2818\u28BF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u281F\u2809 "," \u28E0\u284E\u28A0\u28FF\u28FF\u285F "," \u28B0\u28FF\u2840\u28BA\u28FF\u28FF "," \u2838\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u283F\u28F7\u28CC\u283B\u28E7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28E4\u28ED\u28D9\u28C2\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280F "," \u28B0\u28FF \u28FF\u28FF\u28FF "," \u28B8\u28FF\u28E7\u2818\u28FF\u28FF \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C7 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u281F\u280B\u2801 "," \u28E0\u280E\u28F0\u28FF\u28FF\u280B "," \u28B0\u28FF \u28FF\u28FF\u285F "," \u28B8\u28FF\u28C7\u2839\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u2819\u28BF\u28F7\u28CC\u283B\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D1\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FF\u281F\u2809 "," \u28E0\u2802\u28FC\u28FF\u28FF\u2803 "," \u28B0\u28FF \u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u283B\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28F7\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E4\u28F6\u28FF\u281B\u2801 "," \u28E0\u2802\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28B8\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28C4\u283B\u28BF\u28E6\u28DD\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u287F\u280B\u2801 "," \u28E0\u2882\u28FE\u28FF\u287F\u2801 "," \u28B8\u28FF\u28B8\u28FF\u28FF\u2847 "," \u28BB\u28FF\u28C6\u28BB\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28BF\u28E6\u28D9\u283F\u28C6 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28EC\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u287F\u280B "," \u28E0\u28A0\u28FF\u28FF\u285F "," \u28F8\u28FF\u28B8\u28FF\u28FF\u2843 "," \u28BB\u28FF\u284C\u28BF\u28FF\u2847 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28E6\u28D9\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28ED\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28FE\u281F\u2809 "," \u28F4\u28A0\u28FF\u28FF\u284F "," \u28F8\u28C7\u28B8\u28FF\u28FF "," \u28BF\u28FF\u285C\u28BF\u28FF\u2846 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u28DB\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28A0\u28F4\u28FE\u281F\u2801 "," \u2874\u28B0\u28FF\u28FF\u2807 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28BF\u28FF\u285C\u28FF\u28FF\u2844 \u28F4\u28FF\u28FF\u2846 "," \u28CC\u283B\u28FF\u28EE\u287B\u28BF\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28F6\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u28FE\u280B\u2801 "," \u2874\u28F0\u28FF\u28FF\u2803 "," \u28FC\u2847\u28FF\u28FF\u28FF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u283F\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FD\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2874\u28FC\u28FF\u28FF\u2801 "," \u28FC\u2847\u28FF\u28FF\u28CF "," \u28FF\u28F7\u2879\u28FF\u28FF\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28EE\u287B\u28B7\u28C4 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u28E0\u28F6\u287F\u280B "," \u2854\u28FC\u28FF\u287F "," \u28FC\u2867\u28FF\u28FF\u2847 "," \u28FF\u28F7\u28FB\u28FF\u28F7\u2840 \u28F4\u28FF\u28FF\u2846 "," \u28DC\u28BF\u28FF\u28FF\u287B\u28F7\u2844 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CA\u28E1\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u285F\u2801 "," \u2880\u2854\u28FE\u28FF\u285F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28E7\u28FF\u28FF\u28F7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28FD\u287F\u28F7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FE\u28ED\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28E4\u28F6\u281F\u2801 "," \u2880\u28D4\u28FE\u28FF\u284F "," \u28FE\u28FF\u28FF\u28FF\u2847 "," \u28FF\u28EF\u28BF\u28FF\u28E7 \u28F4\u28FF\u28FF\u2846 "," \u28DD\u28BF\u28F7\u28DD\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D3\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2807 "," \u28FE\u28F8\u28FF\u28FF "," \u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28BF\u28FF\u28DF\u287F\u28E7\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "],[" "," \u2880\u28F4\u28F6\u280B "," \u2880\u28E4\u28FF\u28FF\u2803 "," \u28FE\u28BC\u28FF\u28FF "," \u2818\u28FF\u28FF\u28FF\u28FF\u28C7 \u28F4\u28FF\u28FF\u2846 "," \u28FD\u28FF\u28FF\u28DF\u28FF\u28E6\u2840 \u283B\u28F7\u281F\u28E1 "," \u2818\u28BF\u28FF\u28FD\u28FF\u28D2\u28CB\u28E0\u28E4\u28F4\u287E\u2803 "," \u2819\u283B\u283F\u283F\u283F\u283F\u281F\u280B "," "]];var xn="\x1B[",Ou={gold:"33",text:"39",muted:"90",green:"32"};function Eu(e,t,n){if(!n)return e;let q=t==="gold"?"38;2;255;212;0":Ou[t];return`${xn}${q}m${e}${xn}0m`}function b4(e){return Tu(e).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var k4=1.4;function Nu(e){let{phase:t,seconds:n,columns:q,rows:r,color:s,open:o}=e,i=e.phaseSeconds??n,a=1.4,c=n%(a+.2),h=y=>Math.sin(y/a*Math.PI*2)*Math.sin(y/a*Math.PI),d=t==="waiting"&&c<a?h(c):t==="success"&&i<k4?h(i):0,m=d2[Math.max(0,Math.min(16,Math.round(d*10)+8))],u=t==="success"?"You're signed in.":t==="failed"?"Sign-in didn't finish.":t==="saving"?"Securing your CLI session":n<1.5?"Let's get you connected.":"Waiting for browser approval",p=t==="success"?"Your terminal is ready for the next step.":t==="failed"?"Run canary login to try again.":t==="saving"?"Exchanging authorization and saving credentials.":o&&n<1.5?"Opening your browser...":"Finish signing in at the link above.",f=(y,b="text")=>Eu(y,b,s),k=t==="success"?"green":t==="failed"?"muted":"gold",x;if(r<5)x=[f(u)];else if(q>=72&&r>=18){let y={1:f("CANARY","gold"),3:f(u,t==="success"?"green":"text"),5:f(p,"muted")};x=["",...m.map((b,z)=>` ${f(b,k)} ${y[z]??""}`)]}else q>=42&&r>=23?x=["",...m.map(y=>` ${f(y,k)}`),` ${f("CANARY","gold")}`,"",` ${f(u)}`,` ${f(p,"muted")}`]:x=["",` ${f("CANARY","gold")}`,` ${f(u)}`];return r>=10&&(x.push("",` ${f("\u2500".repeat(Math.max(1,Math.min(54,q-5))),"gold")}`),(t==="waiting"||t==="saving")&&x.push(` ${f("Ctrl+C","muted")} ${f("cancel sign-in","muted")}`),x.push("")),x.slice(0,Math.max(1,r-2)).map(y=>{let b=0;return y.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,z=>z.startsWith("\x1B")||++b<q?z:"")})}function z4(e){if(e.json||!e.animation||!process.stderr.isTTY||!process.stdout.isTTY||process.env.TERM==="dumb"||process.env.CI||process.env.CANARY_NO_ANIMATION)return;let t=process.stderr,n=!process.env.NO_COLOR,q=performance.now(),r="waiting",s=q,o=f=>{r=f,s=performance.now()},i=c2(t),a=!1;function l(){if(a)return;let f=Math.max(2,t.columns||80),k=Math.max(3,t.rows||24),x=performance.now(),y=Nu({phase:r,seconds:(x-q)/1e3,phaseSeconds:(x-s)/1e3,columns:f,rows:k,color:n,open:e.open});i.render(y)}let c=()=>t.write(`${xn}0m${xn}?25h`);function h(){a||(a=!0,clearInterval(p),t.removeListener("resize",l),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",u),process.removeListener("exit",c),c())}function d(f){o("failed"),l(),h(),t.write(`Sign-in cancelled.
|
|
3184
|
+
`),process.exit(f)}let m=()=>d(130),u=()=>d(143),p=setInterval(l,80);return p.unref(),t.on("resize",l),process.once("SIGINT",m),process.once("SIGTERM",u),process.once("exit",c),t.write(`${xn}?25l`),l(),{saving(){o("saving"),l()},celebrate(){return o("success"),l(),new Promise(f=>setTimeout(f,k4*1e3+100))},succeed(f,k){o("success"),l(),h(),process.stdout.write(` Account ${b4(f)}
|
|
3185
|
+
Workspace ${b4(k)}
|
|
3156
3186
|
|
|
3157
|
-
`)},fail(){o("failed"),l(),h()},clear(){i.render([]),h()},stop:h}}g();import{spawn as
|
|
3187
|
+
`)},fail(){o("failed"),l(),h()},clear(){i.render([]),h()},stop:h}}g();import{spawn as Pu}from"node:child_process";import{createInterface as ju,emitKeypressEvents as Mu}from"node:readline";function Mo(e){return e?e.installed.length+e.refreshed.length+e.current.length?`Installed \xB7 available to your coding agent${e.skipped.length?" (some locations skipped)":""}`:"Not installed \xB7 no writable agent location found":"Skipped \xB7 --no-agent-skills"}function Lo(e){return e.workspaces.length>1}function Lu(e){return!e||e.result==="skipped"?null:e.result==="refused"?`Not added \xB7 ${e.detail}`:"Added \xB7 new Claude Code chats load it"}var x4="/canary";async function S4(e){let t=process.stdin,n=process.stderr,q=t.readableFlowing===!0;n.write(`Choose a workspace:
|
|
3158
3188
|
`),e.workspaces.forEach((o,i)=>{let a=e.workspaces.some(l=>l.id!==o.id&&l.name===o.name);n.write(` ${i+1}. ${l1(o.name)}${a?` (${l1(o.id)})`:""}
|
|
3159
|
-
`)});let r=
|
|
3160
|
-
Workspace (number or name): `)}}finally{process.off("SIGINT",s),r.close(),q||t.pause()}}function
|
|
3189
|
+
`)});let r=ju({input:t,output:n,terminal:!1}),s=()=>r.close();process.once("SIGINT",s);try{n.write("Workspace (number or name): ");for await(let o of r)try{return Uq(e,o.trim())}catch(i){n.write(`${i instanceof Error?i.message:"Choose a listed workspace."}
|
|
3190
|
+
Workspace (number or name): `)}}finally{process.off("SIGINT",s),r.close(),q||t.pause()}}function Fu(e,t,n,q){let{context:r}=e,s=Math.max(1,t-5),o=(d,m="text")=>zn(l1(d),m,q),i=(d="",m="text")=>` ${o(d,m)}`,a=[];if(t>=90&&n>=36&&!e.picker){let d={1:o("CANARY","gold"),3:o("You're connected."),5:o("Let's give your agent the next step.","muted")};a.push("",...d2[8].map((m,u)=>` ${o(m,"green")} ${d[u]??""}`),"")}else a.push(i("CANARY","gold"),i("You're connected."),"");if(a.push(i(`Account ${l1(e.email)}`)),a.push(i(`Workspace ${r.selectionRequired?"Choose below":l1(r.workspace.name)}`)),a.push(i(` ${r.source}${!e.done&&Lo(r)?" \xB7 [w] Change":""}`,"muted")),e.picker){a.push("",i("Choose a workspace","gold"));let d=Math.max(1,Math.min(8,n-a.length-5)),m=Math.max(0,Math.min(e.highlighted-Math.floor(d/2),r.workspaces.length-d));for(let u=m;u<Math.min(m+d,r.workspaces.length);u++){let p=r.workspaces[u],k=r.workspaces.some(y=>y.id!==p.id&&y.name===p.name)?` \xB7 ${l1(p.id)}`:"",x=!r.selectionRequired&&p.id===r.workspace.id?" \xB7 current":"";a.push(i(`${u===e.highlighted?"\u203A":" "} ${u+1}. ${l1(p.name)}${k}${x}`,u===e.highlighted?"gold":"text"))}a.push(i(`${e.highlighted+1} of ${r.workspaces.length}`,"muted"),"",i("\u2191 \u2193 choose \xB7 number highlight \xB7 Enter select \xB7 Esc back","muted"))}else{let d=r.repository?l1(r.repository):void 0;a.push(i(d?`Repository ${d}`:"Repository Open a local Git repository to continue")),a.push(i(`Agent skill ${Mo(e.skill)}`,e.skill&&Mo(e.skill).startsWith("Installed")?"green":"muted"));let m=Lu(e.plugin);m&&a.push(i(`Plugin ${m}`,e.plugin?.result==="refused"?"muted":"green")),r.workspaceNotice&&a.push(...Ze(r.workspaceNotice,s).map(p=>i(p,"muted"))),a.push("",i("\u2500".repeat(Math.min(68,s)),"muted"),i("NEXT \xB7 CHECK A CHANGE","gold"));let u=!!e.skill&&Mo(e.skill).startsWith("Installed");a.push(i(u?"In your coding agent, type:":"In your coding agent, run canary skills, then type:","muted")),a.push(...Ze(x4,s-2).map(p=>i(`\u2502 ${p}`))),e.done||a.push("",i(`${Lo(r)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),e.message&&a.push(...Ze(e.message,s).map(p=>i(p,"muted"))),a.push("",i("Signed in","green"))}let c=Math.max(1,n-2);return(c<=3?a.slice(0,c):a.length>c?[...a.slice(0,Math.max(0,c-3)),...a.slice(-3)]:a).map(d=>Gq(d,Math.max(1,t-1)))}async function $u(e,t){let n=process.platform==="darwin"?[["pbcopy"]]:process.platform==="win32"?[["clip.exe"]]:[["wl-copy"],["xclip","-selection","clipboard"],["xsel","--clipboard","--input"]];for(let[q,...r]of n){if(t.aborted)return!1;if(await new Promise(o=>{let i=Pu(q,r,{stdio:["pipe","ignore","ignore"],signal:t}),a=setTimeout(()=>{i.kill(),o(!1)},1e3),l=c=>{clearTimeout(a),o(c)};i.on("error",()=>l(!1)),i.on("close",c=>l(c===0)),i.stdin.on("error",()=>{}),i.stdin.end(e)}))return!0}return!1}async function C4(e){let t=process.stdin,n=process.stderr,q={...e,picker:e.context.workspaces.length>1,highlighted:Math.max(0,e.context.workspaces.findIndex(d=>d.id===e.context.workspace.id))},r=!process.env.NO_COLOR,s=c2(n),o=()=>s.render(Fu(q,n.columns||80,n.rows||24,r));if(!t.isTTY||!n.isTTY||(n.rows||24)<16||(n.columns||80)<30){q.done=!0,o(),n.write(`
|
|
3161
3191
|
${Tt}
|
|
3162
3192
|
`);return}let i=t.isRaw,a=t.readableFlowing===!0,l=new AbortController,c=!1,h;await new Promise(d=>{function m(){if(c)return;c=!0,l.abort(),t.off("keypress",k),t.off("end",m),n.off("resize",f),process.off("SIGINT",m),process.off("SIGTERM",p),process.off("exit",u),q.picker=!1,q.done=!0,q.message=void 0;let x=e.sessionCurrent();x?o():s.render(["CLI session changed in another process. Run canary whoami to check the active account."]),u(),x&&!q.context.selectionRequired&&n.write(`
|
|
3163
3193
|
${Tt}
|
|
3164
3194
|
|
|
3165
|
-
`),d()}function u(){t.setRawMode(i),a||t.pause(),n.write(`${S1}0m${S1}?25h`)}function p(){process.exitCode=143,m()}function f(){(n.rows||24)<16||(n.columns||80)<30?m():o()}function k(x,y){if(!(!y||c)){if(!e.sessionCurrent()){m();return}if(y.ctrl&&["c","d"].includes(y.name??"")){m();return}if(!(y.ctrl||y.meta)){if(q.picker){let b=q.context.workspaces.length;if(y.name==="escape"){if(q.context.selectionRequired){m();return}q.picker=!1}else if(/^[1-9]$/.test(y.sequence??"")&&Number(y.sequence)<=b)q.highlighted=Number(y.sequence)-1;else if(y.name==="up")q.highlighted=(q.highlighted+b-1)%b;else if(y.name==="down")q.highlighted=(q.highlighted+1)%b;else if(y.name==="return"){let z=q.context.workspaces[q.highlighted];try{e.selectWorkspace(z),q.context={...q.context,workspace:z,source:"selected in CLI",selectionRequired:!1},q.picker=!1,q.message="Workspace saved for future CLI commands."}catch{if(!e.sessionCurrent()){m();return}q.picker=!1,q.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(y.name??"")){m();return}else if(y.name==="w"&&Lo(q.context))q.picker=!0,q.highlighted=Math.max(0,q.context.workspaces.findIndex(b=>b.id===q.context.workspace.id));else if(y.name==="c"&&!h){let b=new AbortController;h=b,l.signal.addEventListener("abort",()=>b.abort(),{once:!0}),Fu(k4,b.signal).then(z=>{h===b&&(h=void 0),!c&&(q.message=z?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",o())})}o()}}}ju(t),t.setRawMode(!0),t.resume(),t.on("keypress",k),t.once("end",m),n.on("resize",f),process.once("SIGINT",m),process.once("SIGTERM",p),process.once("exit",u),n.write(`${S1}?25l`),o()})}var Hu=900*1e3,Bu=6e4;var C4=e=>e.toString("base64url");function _u(e){let t=process.platform,[n,q]=t==="darwin"?["open",[e]]:t==="win32"?["explorer.exe",[e]]:["xdg-open",[e]];try{let r=Du(n,q,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}function Uu(e,t){return`<!doctype html><meta charset="utf-8"><title>${e}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${e}</h2><p style="color:#555">${t}</p></body>`}function Gu(e){return new Promise((t,n)=>{let q,r,s=new Promise((l,c)=>{q=l,r=c}),o=Wu((l,c)=>{let h=new URL(l.url??"/","http://127.0.0.1"),d=(p,f,k)=>{c.writeHead(k,{"content-type":"text/html",connection:"close"}),c.end(Uu(p,f))};if(h.pathname!=="/callback"){c.writeHead(404,{connection:"close"}),c.end("not found");return}if(h.searchParams.get("state")!==e){d("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let m=h.searchParams.get("error");if(m){d("Authorization failed","You can close this tab and return to your terminal.",400),r(new Error(`authorization failed: ${m}`));return}let u=h.searchParams.get("code");if(!u){d("Authorization failed","No authorization code was returned. Please run canary login again.",400),r(new Error("callback returned no code"));return}d("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),q(u)}),i=setTimeout(()=>r(new Error("timed out waiting for browser authorization")),Hu);i.unref?.();let a=()=>{clearTimeout(i),o.closeAllConnections?.(),o.close()};s.then(a,a),o.on("error",l=>{clearTimeout(i),n(l)}),o.listen(0,"127.0.0.1",()=>{t({port:o.address().port,code:s,close:a})})})}async function Vu(e,t){let n=K(),q=n.apiUrl||a1(),r=(t.apiUrl||a1()).replace(/\/+$/,""),s=C4(S4(32)),o=$u("sha256").update(s).digest("base64url"),i=C4(S4(16)),{port:a,code:l,close:c}=await Gu(i),h=`http://127.0.0.1:${a}/callback`,d=(t.webUrl||Ee()).replace(/\/+$/,""),m=`${d}/cli/authorize?challenge=${encodeURIComponent(o)}&state=${encodeURIComponent(i)}&redirect=${encodeURIComponent(h)}`;for(let k of f4(e,t.open,m))console.error(k);let u=b4({json:e,animation:t.animation,open:t.open}),p=Date.now(),f=u?void 0:setInterval(()=>console.error(v4(e,Math.round((Date.now()-p)/1e3))),Bu);f?.unref?.();try{t.open&&_u(m);let k=await l;f&&clearInterval(f),u?.saving();let x=await W("/api/v1/cli/auth/token",{method:"POST",body:{code:k,codeVerifier:s},baseUrl:r});return u&&await u.celebrate(),u?.clear(),await I4(x,n,q,r,e,{webUrl:d,agentSkills:t.agentSkills,workspace:t.workspace,interactive:!!u&&!!process.stdin.isTTY&&(process.stderr.rows||24)>=16&&(process.stderr.columns||80)>=30,promptWorkspace:!e&&!process.env.CI&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&!!process.stderr.isTTY})}catch(k){throw u?.fail(),k}finally{f&&clearInterval(f),u?.stop(),c()}}async function I4(e,t,n,q,r,s){P1(({team:p,...f})=>({...f,token:e.token,user:e.user,apiUrl:q,...s.webUrl?{webUrl:s.webUrl}:{},agentSkills:s.agentSkills}),{overwriteUnreadable:!0}),zq();let o=await u4(e,t,n,q);s.workspace!==void 0&&(o.workspace=_q(o,s.workspace),o.source="selected in CLI",o.selectionRequired=!1),o.selectionRequired||P1(p=>({...p,team:o.workspace}));let i=s.agentSkills?tn():void 0,a=s.agentSkills?Ds():void 0,l=()=>{let p=K();return p.token===e.token&&p.apiUrl===q},c=p=>{P1(f=>{if(f.token!==e.token||f.apiUrl!==q)throw new Error("CLI session changed");return{...f,team:p}}),o.selectionRequired=!1},h=o.repository?p=>Bq({token:e.token,apiUrl:q,userId:e.user.id},o.repository,p):void 0;if(!o.selectionRequired&&h&&(o.repositoryState=(await h(o.workspace.id))?.state),s.interactive&&o.workspaces.length)await x4({email:e.user.email,context:o,skill:i,plugin:a,selectWorkspace:c,sessionCurrent:l});else if(s.promptWorkspace&&o.selectionRequired&&o.workspaces.length){console.error(`Signed in as ${l1(e.user.email)}.`);let p=await z4(o);p&&(c(p),o.workspace=p,o.source="selected in CLI",h&&(o.repositoryState=(await h(p.id))?.state))}if(!l())throw new Error("CLI session changed in another process. Run canary whoami.");let d=!process.exitCode,m=K().team;if(!m){let p=o.workspaces.length?"workspace_selection_required":"workspace_required",f=o.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${Ee()}, then run canary login.`;return r?console.log(JSON.stringify({ok:!1,authenticated:!0,error:p,user:e.user,workspaces:o.workspaces,fix:f})):(console.log(`Signed in as ${l1(e.user.email)}. Select a workspace to continue.`),o.workspaces.forEach((k,x)=>console.log(` ${x+1}. ${l1(k.name)} (${l1(k.id)})`)),console.log(f)),process.exitCode=1,d}let u=o.repository?{name:o.repository,state:o.repositoryState}:void 0;if(r)console.log(JSON.stringify({ok:!0,user:e.user,team:m,workspace:m,...u?{repository:u}:{}}));else if(!s.interactive){console.log(`Logged in as ${l1(e.user.email)} (${l1(m.name??m.id)}).`),u&&console.log(Gq(u.name));for(let p of[i&&Ju(i),g4(a)])p&&console.log(p);console.log(Tt)}return d}async function A4(e,t,n){let q=K(),r=q.apiUrl||a1(),s=(n.apiUrl||a1()).replace(/\/+$/,""),o=await W("/api/v1/cli/auth/whoami",{token:e,baseUrl:s});return I4({...o,token:e,tokenType:"Bearer",expiresAt:null},q,r,s,t,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function Ju(e){let t=[...e.installed,...e.refreshed];return t.length?`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${t.join(", ")}).`:null}function R4(e){e.command("login").description("Authenticate the Canary CLI with your account").option("--json","output machine-readable JSON").option("--token <token>","log in with a token directly (CI / headless; else $CANARY_TOKEN)").option("--web-url <url>","override the authorization web URL").option("--api-url <url>","override the API base URL (moves with --web-url)").option("--workspace <id-or-name>","select a workspace from your memberships (required for an unselected headless login)").option("--no-open","print the authorization URL instead of opening a browser").option("--no-animation","use plain login output without the animated Canary").option("--no-agent-skills","skip installing the Canary skill for your coding agents (written to ~/.claude, ~/.agents, ~/.codex when present)").option("--no-hooks","skip adding the push check to your coding agents' settings").action(async t=>{let n=t.json===!0;try{let q;if(t.token!==void 0){let r=t.token.trim();if(!r)throw new Error("--token was provided but is empty");q=await A4(r,n,{...t,agentSkills:t.agentSkills!==!1})}else{let r=(process.env.CANARY_TOKEN??"").trim();r?q=await A4(r,n,{...t,agentSkills:t.agentSkills!==!1}):(q=await Vu(n,{webUrl:t.webUrl,apiUrl:t.apiUrl,workspace:t.workspace,open:t.open!==!1,animation:t.animation!==!1,agentSkills:t.agentSkills!==!1}),Zt())}q&&t.agentSkills!==!1&&t.hooks!==!1&&await wn({json:n})}catch(q){let r=q instanceof L?`${q.message}`:q instanceof Error?q.message:String(q);n?console.log(JSON.stringify({ok:!1,error:r})):console.error(`Login failed: ${r}`),process.exitCode=1}})}g();p1();e1();pq();Rt();g();p1();e1();M1();g();p1();M1();var Ot=5e3;function Fo(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let n=new AbortController;for(let q of[e,t])q.aborted?n.abort(q.reason):q.addEventListener("abort",()=>n.abort(q.reason),{once:!0});return n.signal}async function T4(e,t,n,q={}){let r=AbortSignal.timeout(q.timeoutMs??Ot);try{let s=await W(`/api/v1/cli/local-repositories/lookup?${new URLSearchParams({workspaceId:t,githubFullName:n}).toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:Fo(r,q.signal)});return s&&typeof s.repositoryId=="string"?{repositoryId:s.repositoryId}:null}catch(s){return s instanceof L&&s.status===404&&s.code==="repository_not_connected"?{notConnected:!0}:null}}async function $o(e,t={}){let{signal:n}=t,q=Q();if(!q)return{ok:!1,cause:"not_logged_in"};let r=K(),s=r.team?.id;if(!s)return{ok:!1,cause:"no_workspace"};let o=a1();try{let i=q===r.token?r.user?.id:void 0;if(i||(i=(await W("/api/v1/cli/auth/whoami",{token:q,baseUrl:o,signal:n}))?.user?.id),!i)return{ok:!1,cause:"not_logged_in"};let a={apiUrl:o,userId:i,workspaceId:s,directory:e},l=await ia(a,c=>T4({token:q,apiUrl:o},s,c,t));return l?.repositoryId?{ok:!0,context:{token:q,apiUrl:o,repository:a,repositoryId:l.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(i){return{ok:!1,cause:i.code==="not_a_git_repository"?"no_binding":"context_error"}}}jq();ie();M1();g();e1();import{randomUUID as Yu}from"node:crypto";import{mkdirSync as Ku,readFileSync as Xu,renameSync as Qu,rmSync as Zu,writeFileSync as em}from"node:fs";import{dirname as tm,join as nm}from"node:path";var Do=()=>nm(G(),"hold","raised.json"),qm=720*60*60*1e3,rm=100,sm=8e3,om=e=>{let t=e;if(typeof t?.requestId!="string"||!Array.isArray(t.open))return;let n=t.open.filter(q=>typeof q=="string");return n.length>0?{requestId:t.requestId,open:n}:void 0};function Wo(e){let t;try{t=JSON.parse(Xu(Do(),"utf8"))}catch{return{}}let n=t?.chats;if(t?.version!==1||!n||typeof n!="object"||Array.isArray(n))return{};let q={};for(let[r,s]of Object.entries(n)){let o=typeof s?.at=="string"?Date.parse(s.at):NaN;if(Array.isArray(s?.keys)&&Number.isFinite(o)&&e-o<qm){let i=om(s.held);q[r]={keys:s.keys.filter(a=>typeof a=="string"),at:s.at,...i?{held:i}:{}}}}return q}function O4(e,t=Date.now()){let n=[...Wo(t)[e]?.keys??[]];for(;n.join(",").length>sm;)n.shift();return n.length>0?n.join(","):void 0}function E4(e,t=Date.now()){return Wo(t)[e]?.held}function N4(e,t,n,q=Date.now()){try{U2(`${Do()}.lock`,"what pushes asked about",()=>{let r=Wo(q);if(t.length===0&&!n&&!r[e])return;let s=new Set(r[e]?.keys);for(let l of t)s.delete(l),s.add(l);let o=t.length>0||n||!r[e]?new Date(q).toISOString():r[e].at;r[e]={keys:[...s].slice(-rm),at:o,...n?{held:n}:{}};let i=Do(),a=`${i}.${Yu()}.tmp`;Ku(tm(i),{recursive:!0,mode:448});try{em(a,JSON.stringify({version:1,chats:r},null,2)+`
|
|
3166
|
-
`,{flag:"wx",mode:384}),
|
|
3167
|
-
`,{flag:"wx",mode:384}),
|
|
3168
|
-
`,{mode:n}),
|
|
3169
|
-
`).filter(Boolean).sort()[0];if(n)return`commit:${n}`}catch{}try{let n=t(["config","--get","remote.origin.url"]);return n?`origin:${n}`:null}catch{return null}}var
|
|
3195
|
+
`),d()}function u(){t.setRawMode(i),a||t.pause(),n.write(`${S1}0m${S1}?25h`)}function p(){process.exitCode=143,m()}function f(){(n.rows||24)<16||(n.columns||80)<30?m():o()}function k(x,y){if(!(!y||c)){if(!e.sessionCurrent()){m();return}if(y.ctrl&&["c","d"].includes(y.name??"")){m();return}if(!(y.ctrl||y.meta)){if(q.picker){let b=q.context.workspaces.length;if(y.name==="escape"){if(q.context.selectionRequired){m();return}q.picker=!1}else if(/^[1-9]$/.test(y.sequence??"")&&Number(y.sequence)<=b)q.highlighted=Number(y.sequence)-1;else if(y.name==="up")q.highlighted=(q.highlighted+b-1)%b;else if(y.name==="down")q.highlighted=(q.highlighted+1)%b;else if(y.name==="return"){let z=q.context.workspaces[q.highlighted];try{e.selectWorkspace(z),q.context={...q.context,workspace:z,source:"selected in CLI",selectionRequired:!1},q.picker=!1,q.message="Workspace saved for future CLI commands."}catch{if(!e.sessionCurrent()){m();return}q.picker=!1,q.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(y.name??"")){m();return}else if(y.name==="w"&&Lo(q.context))q.picker=!0,q.highlighted=Math.max(0,q.context.workspaces.findIndex(b=>b.id===q.context.workspace.id));else if(y.name==="c"&&!h){let b=new AbortController;h=b,l.signal.addEventListener("abort",()=>b.abort(),{once:!0}),$u(x4,b.signal).then(z=>{h===b&&(h=void 0),!c&&(q.message=z?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",o())})}o()}}}Mu(t),t.setRawMode(!0),t.resume(),t.on("keypress",k),t.once("end",m),n.on("resize",f),process.once("SIGINT",m),process.once("SIGTERM",p),process.once("exit",u),n.write(`${S1}?25l`),o()})}var Bu=900*1e3,_u=6e4;var I4=e=>e.toString("base64url");function Uu(e){let t=process.platform,[n,q]=t==="darwin"?["open",[e]]:t==="win32"?["explorer.exe",[e]]:["xdg-open",[e]];try{let r=Wu(n,q,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}function Gu(e,t){return`<!doctype html><meta charset="utf-8"><title>${e}</title><body style="font-family:system-ui,sans-serif;max-width:28rem;margin:12vh auto;text-align:center;color:#111"><h2>${e}</h2><p style="color:#555">${t}</p></body>`}function Vu(e){return new Promise((t,n)=>{let q,r,s=new Promise((l,c)=>{q=l,r=c}),o=Hu((l,c)=>{let h=new URL(l.url??"/","http://127.0.0.1"),d=(p,f,k)=>{c.writeHead(k,{"content-type":"text/html",connection:"close"}),c.end(Gu(p,f))};if(h.pathname!=="/callback"){c.writeHead(404,{connection:"close"}),c.end("not found");return}if(h.searchParams.get("state")!==e){d("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let m=h.searchParams.get("error");if(m){d("Authorization failed","You can close this tab and return to your terminal.",400),r(new Error(`authorization failed: ${m}`));return}let u=h.searchParams.get("code");if(!u){d("Authorization failed","No authorization code was returned. Please run canary login again.",400),r(new Error("callback returned no code"));return}d("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),q(u)}),i=setTimeout(()=>r(new Error("timed out waiting for browser authorization")),Bu);i.unref?.();let a=()=>{clearTimeout(i),o.closeAllConnections?.(),o.close()};s.then(a,a),o.on("error",l=>{clearTimeout(i),n(l)}),o.listen(0,"127.0.0.1",()=>{t({port:o.address().port,code:s,close:a})})})}async function Ju(e,t){let n=K(),q=n.apiUrl||a1(),r=(t.apiUrl||a1()).replace(/\/+$/,""),s=I4(A4(32)),o=Du("sha256").update(s).digest("base64url"),i=I4(A4(16)),{port:a,code:l,close:c}=await Vu(i),h=`http://127.0.0.1:${a}/callback`,d=(t.webUrl||Ee()).replace(/\/+$/,""),m=`${d}/cli/authorize?challenge=${encodeURIComponent(o)}&state=${encodeURIComponent(i)}&redirect=${encodeURIComponent(h)}`;for(let k of g4(e,t.open,m))console.error(k);let u=z4({json:e,animation:t.animation,open:t.open}),p=Date.now(),f=u?void 0:setInterval(()=>console.error(y4(e,Math.round((Date.now()-p)/1e3))),_u);f?.unref?.();try{t.open&&Uu(m);let k=await l;f&&clearInterval(f),u?.saving();let x=await W("/api/v1/cli/auth/token",{method:"POST",body:{code:k,codeVerifier:s},baseUrl:r});return u&&await u.celebrate(),u?.clear(),await T4(x,n,q,r,e,{webUrl:d,agentSkills:t.agentSkills,workspace:t.workspace,interactive:!!u&&!!process.stdin.isTTY&&(process.stderr.rows||24)>=16&&(process.stderr.columns||80)>=30,promptWorkspace:!e&&!process.env.CI&&!!process.stdin.isTTY&&!!process.stdout.isTTY&&!!process.stderr.isTTY})}catch(k){throw u?.fail(),k}finally{f&&clearInterval(f),u?.stop(),c()}}async function T4(e,t,n,q,r,s){P1(({team:p,...f})=>({...f,token:e.token,user:e.user,apiUrl:q,...s.webUrl?{webUrl:s.webUrl}:{},agentSkills:s.agentSkills}),{overwriteUnreadable:!0}),xq();let o=await p4(e,t,n,q);s.workspace!==void 0&&(o.workspace=Uq(o,s.workspace),o.source="selected in CLI",o.selectionRequired=!1),o.selectionRequired||P1(p=>({...p,team:o.workspace}));let i=s.agentSkills?nn():void 0,a=s.agentSkills?Ds():void 0,l=()=>{let p=K();return p.token===e.token&&p.apiUrl===q},c=p=>{P1(f=>{if(f.token!==e.token||f.apiUrl!==q)throw new Error("CLI session changed");return{...f,team:p}}),o.selectionRequired=!1},h=o.repository?p=>_q({token:e.token,apiUrl:q,userId:e.user.id},o.repository,p):void 0;if(!o.selectionRequired&&h&&(o.repositoryState=(await h(o.workspace.id))?.state),s.interactive&&o.workspaces.length)await C4({email:e.user.email,context:o,skill:i,plugin:a,selectWorkspace:c,sessionCurrent:l});else if(s.promptWorkspace&&o.selectionRequired&&o.workspaces.length){console.error(`Signed in as ${l1(e.user.email)}.`);let p=await S4(o);p&&(c(p),o.workspace=p,o.source="selected in CLI",h&&(o.repositoryState=(await h(p.id))?.state))}if(!l())throw new Error("CLI session changed in another process. Run canary whoami.");let d=!process.exitCode,m=K().team;if(!m){let p=o.workspaces.length?"workspace_selection_required":"workspace_required",f=o.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${Ee()}, then run canary login.`;return r?console.log(JSON.stringify({ok:!1,authenticated:!0,error:p,user:e.user,workspaces:o.workspaces,fix:f})):(console.log(`Signed in as ${l1(e.user.email)}. Select a workspace to continue.`),o.workspaces.forEach((k,x)=>console.log(` ${x+1}. ${l1(k.name)} (${l1(k.id)})`)),console.log(f)),process.exitCode=1,d}let u=o.repository?{name:o.repository,state:o.repositoryState}:void 0;if(r)console.log(JSON.stringify({ok:!0,user:e.user,team:m,workspace:m,...u?{repository:u}:{}}));else if(!s.interactive){console.log(`Logged in as ${l1(e.user.email)} (${l1(m.name??m.id)}).`),u&&console.log(Vq(u.name));for(let p of[i&&Yu(i),w4(a)])p&&console.log(p);console.log(Tt)}return d}async function R4(e,t,n){let q=K(),r=q.apiUrl||a1(),s=(n.apiUrl||a1()).replace(/\/+$/,""),o=await W("/api/v1/cli/auth/whoami",{token:e,baseUrl:s});return T4({...o,token:e,tokenType:"Bearer",expiresAt:null},q,r,s,t,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function Yu(e){let t=[...e.installed,...e.refreshed];return t.length?`Canary skill ${e.installed.length?"installed":"updated"} for your coding agents (${t.join(", ")}).`:null}function O4(e){e.command("login").description("Authenticate the Canary CLI with your account").option("--json","output machine-readable JSON").option("--token <token>","log in with a token directly (CI / headless; else $CANARY_TOKEN)").option("--web-url <url>","override the authorization web URL").option("--api-url <url>","override the API base URL (moves with --web-url)").option("--workspace <id-or-name>","select a workspace from your memberships (required for an unselected headless login)").option("--no-open","print the authorization URL instead of opening a browser").option("--no-animation","use plain login output without the animated Canary").option("--no-agent-skills","skip installing the Canary skill for your coding agents (written to ~/.claude, ~/.agents, ~/.codex when present)").option("--no-hooks","skip adding the push check to your coding agents' settings").action(async t=>{let n=t.json===!0;try{let q;if(t.token!==void 0){let r=t.token.trim();if(!r)throw new Error("--token was provided but is empty");q=await R4(r,n,{...t,agentSkills:t.agentSkills!==!1})}else{let r=(process.env.CANARY_TOKEN??"").trim();r?q=await R4(r,n,{...t,agentSkills:t.agentSkills!==!1}):(q=await Ju(n,{webUrl:t.webUrl,apiUrl:t.apiUrl,workspace:t.workspace,open:t.open!==!1,animation:t.animation!==!1,agentSkills:t.agentSkills!==!1}),Zt())}q&&t.agentSkills!==!1&&t.hooks!==!1&&await bn({json:n})}catch(q){let r=q instanceof L?`${q.message}`:q instanceof Error?q.message:String(q);n?console.log(JSON.stringify({ok:!1,error:r})):console.error(`Login failed: ${r}`),process.exitCode=1}})}g();p1();e1();fq();Rt();g();p1();e1();M1();g();p1();M1();var Ot=5e3;function Fo(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let n=new AbortController;for(let q of[e,t])q.aborted?n.abort(q.reason):q.addEventListener("abort",()=>n.abort(q.reason),{once:!0});return n.signal}async function E4(e,t,n,q={}){let r=AbortSignal.timeout(q.timeoutMs??Ot);try{let s=await W(`/api/v1/cli/local-repositories/lookup?${new URLSearchParams({workspaceId:t,githubFullName:n}).toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:Fo(r,q.signal)});return s&&typeof s.repositoryId=="string"?{repositoryId:s.repositoryId}:null}catch(s){return s instanceof L&&s.status===404&&s.code==="repository_not_connected"?{notConnected:!0}:null}}async function $o(e,t={}){let{signal:n}=t,q=Q();if(!q)return{ok:!1,cause:"not_logged_in"};let r=K(),s=r.team?.id;if(!s)return{ok:!1,cause:"no_workspace"};let o=a1();try{let i=q===r.token?r.user?.id:void 0;if(i||(i=(await W("/api/v1/cli/auth/whoami",{token:q,baseUrl:o,signal:n}))?.user?.id),!i)return{ok:!1,cause:"not_logged_in"};let a={apiUrl:o,userId:i,workspaceId:s,directory:e},l=await la(a,c=>E4({token:q,apiUrl:o},s,c,t));return l?.repositoryId?{ok:!0,context:{token:q,apiUrl:o,repository:a,repositoryId:l.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(i){return{ok:!1,cause:i.code==="not_a_git_repository"?"no_binding":"context_error"}}}Mq();ie();M1();g();e1();import{randomUUID as Ku}from"node:crypto";import{mkdirSync as Xu,readFileSync as Qu,renameSync as Zu,rmSync as em,writeFileSync as tm}from"node:fs";import{dirname as nm,join as qm}from"node:path";var Do=()=>qm(G(),"hold","raised.json"),rm=720*60*60*1e3,sm=100,om=8e3,im=e=>{let t=e;if(typeof t?.requestId!="string"||!Array.isArray(t.open))return;let n=t.open.filter(q=>typeof q=="string");return n.length>0?{requestId:t.requestId,open:n}:void 0};function Wo(e){let t;try{t=JSON.parse(Qu(Do(),"utf8"))}catch{return{}}let n=t?.chats;if(t?.version!==1||!n||typeof n!="object"||Array.isArray(n))return{};let q={};for(let[r,s]of Object.entries(n)){let o=typeof s?.at=="string"?Date.parse(s.at):NaN;if(Array.isArray(s?.keys)&&Number.isFinite(o)&&e-o<rm){let i=im(s.held);q[r]={keys:s.keys.filter(a=>typeof a=="string"),at:s.at,...i?{held:i}:{}}}}return q}function N4(e,t=Date.now()){let n=[...Wo(t)[e]?.keys??[]];for(;n.join(",").length>om;)n.shift();return n.length>0?n.join(","):void 0}function P4(e,t=Date.now()){return Wo(t)[e]?.held}function j4(e,t,n,q=Date.now()){try{G2(`${Do()}.lock`,"what pushes asked about",()=>{let r=Wo(q);if(t.length===0&&!n&&!r[e])return;let s=new Set(r[e]?.keys);for(let l of t)s.delete(l),s.add(l);let o=t.length>0||n||!r[e]?new Date(q).toISOString():r[e].at;r[e]={keys:[...s].slice(-sm),at:o,...n?{held:n}:{}};let i=Do(),a=`${i}.${Ku()}.tmp`;Xu(nm(i),{recursive:!0,mode:448});try{tm(a,JSON.stringify({version:1,chats:r},null,2)+`
|
|
3196
|
+
`,{flag:"wx",mode:384}),Zu(a,i)}catch(l){throw em(a,{force:!0}),l}})}catch{}}g();e1();M1();import{randomUUID as am}from"node:crypto";import{mkdirSync as lm,readFileSync as M4,renameSync as hm,rmSync as cm,writeFileSync as dm}from"node:fs";import{dirname as um,join as mm}from"node:path";var pm="skips.json",fm=720*60*60*1e3,vm=1440*60*1e3,gm=(e,t)=>{let n=Date.parse(e.at);return Number.isFinite(n)&&t-n<fm&&n-t<vm};function L4(e,t=Date.now()){let n={version:1,skips:{}},q;try{q=JSON.parse(M4(Ke(e,pm),"utf8"))}catch{return n}let r=q?.skips;if(!q||typeof q!="object"||q.version!==1||!r||typeof r!="object"||Array.isArray(r))return n;for(let[s,o]of Object.entries(r))/^[a-f0-9]{40}$/.test(s)&&o&&typeof o=="object"&&typeof o.reason=="string"&&typeof o.at=="string"&&gm(o,t)&&(n.skips[s]={reason:o.reason,at:o.at,...typeof o.branch=="string"?{branch:o.branch}:{}});return n}var Jq=()=>mm(G(),"hold","skips.json"),ym=600*1e3;function F4(e){let t;try{t=JSON.parse(M4(Jq(),"utf8"))}catch{return{}}let n=t?.skips;if(t?.version!==1||!n||typeof n!="object"||Array.isArray(n))return{};let q={};for(let[r,s]of Object.entries(n)){let o=Date.parse(s?.at??"");typeof s?.reason=="string"&&Number.isFinite(o)&&e-o>=0&&e-o<ym&&(q[r]={reason:s.reason,at:s.at})}return q}function $4(e){let t=Jq(),n=`${t}.${am()}.tmp`;lm(um(t),{recursive:!0,mode:448});try{dm(n,JSON.stringify({version:1,skips:e},null,2)+`
|
|
3197
|
+
`,{flag:"wx",mode:384}),hm(n,t)}catch(q){throw cm(n,{force:!0}),q}}function D4(e,t,n=Date.now()){return G2(`${Jq()}.lock`,"the push skips",()=>{let q=F4(n),r={reason:t,at:new Date(n).toISOString()};return $4({...q,[e]:r}),r})}function W4(e,t=Date.now()){try{return G2(`${Jq()}.lock`,"the push skips",()=>{let n=F4(t),q=n[e];return q?(delete n[e],$4(n),{reason:q.reason}):null})}catch{return null}}Qe();var wm=500,bm=5e3,H4={not_logged_in:["Not logged in","run `canary login` first"],no_workspace:["No workspace is selected","run `canary workspace list`, then `canary workspace use <id>`"],no_binding:["This checkout is not set up with Canary, so its pushes are not checked and there is nothing to skip","run `canary setup` to set it up"],context_error:["Canary's saved record for this checkout could not be read","run `canary setup` again"]};function B4(e){return e==="on"?"The push check is on: an agent's push or pull request is put to you until Canary has checked its chat with nothing left to fix.":"The push check is off: agents push and open pull requests without Canary being asked."}function km(e,t){try{if(!U3(e))return $(t,"config_unreadable","~/.canary/config.json exists but cannot be read, so the setting was not saved","repair or remove the file, then run the command again",2)}catch(n){if(n instanceof vt)return $(t,"config_busy",n.message,void 0,2);throw n}console.log(t?JSON.stringify({ok:!0,mode:e}):B4(e))}async function zm(e,t,n){let q=(t??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,wm);if(!q)return $(n,"reason_required","a skip needs the person's OK, in their words",'canary skip --reason "<their exact words>"',3);let r=kt(process.env,e);if(!r)return $(n,"no_chat","This isn't running in an agent chat Canary can name, so there is no held push to let through","run it from the agent chat whose push Canary held",3);let s;try{s=D4(r,q)}catch(l){if(l instanceof vt)return $(n,"config_busy",l.message,void 0,2);throw l}let o=Q(),i=o?P4(r):void 0;o&&await cn("gate_skip:chat",{token:o,apiUrl:a1()});let a=i?K().team?.id:void 0;o&&i&&a&&await W("/api/v1/cli/hold/accept",{method:"POST",body:{workspaceId:a,chat:r,requestId:i.requestId,bugs:i.open},token:o,baseUrl:a1(),signal:AbortSignal.timeout(bm)}).catch(()=>{}),console.log(n?JSON.stringify({ok:!0,chat:r,reason:s.reason,at:s.at}):`Skip recorded: this chat's next push goes out unchecked (${F(s.reason)}).`)}async function xm(e,t){Sq(e);let n=await $o(e);if(!n.ok){let[r,s]=H4[n.cause]??H4.context_error;return $(t,n.cause,r,s,3)}let q=Object.entries(L4(n.context.repository).skips).map(([r,s])=>({treeHash:r,...s})).sort((r,s)=>s.at.localeCompare(r.at));if(t)return console.log(JSON.stringify({ok:!0,skips:q}));if(!q.length)return console.log("No skips recorded for this repository.");for(let r of q)console.log(`${r.treeHash.slice(0,12)} ${r.at.slice(0,16).replace("T"," ")} ${r.branch?F(r.branch):"(detached)"} ${F(r.reason)}`)}function _4(e){let t=e.command("gate").description("The check on an agent's push or pull request: on, off, status");for(let n of["on","off"])t.command(n).description(n==="on"?"Hold an agent's unverified push or pull request (the default)":"Never hold a push or pull request").option("--json","print one JSON document").action(q=>km(n,q.json===!0));t.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let q=wn();if(n.json===!0)console.log(JSON.stringify({ok:!0,...q}));else{console.log(B4(q.mode));for(let r of Bq(q))console.log(r)}}),e.command("skip").description("Let this chat's next push go out unchecked, on the person's OK").option("--reason <text>","the person's OK, in their exact words").option("--list","show the skips recorded for this repository").option("--dir <path>","repo directory (default: current directory)").option("--json","print one JSON document").action(async n=>{let q=n.json===!0;try{n.list?await xm(n.dir??process.cwd(),q):await zm(n.dir??process.cwd(),n.reason,q)}catch(r){$(q,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}})}Rt();g();ie();var Sm={[g1.install]:"(random, minted once into ~/.canary/config.json)",[g1.worktree]:"(hash of this checkout's path, salted by the install id; the path never leaves)",[g1.repo]:"(root commit of the history; absent on a shallow clone)"};function U4(e){e.command("identity").description("Show what this CLI sends about where it runs (ids and hashes only; no request is made)").option("--json","print the headers as JSON").action(t=>{let n=Je();if(t.json===!0)return void console.log(JSON.stringify(n));for(let[q,r]of Object.entries(n)){let s=q===g1.harness&&r==="unknown"?"(no running coding-agent session detected)":Sm[q]??"";console.log(`${q.padEnd(18)} ${r}${s?` ${s}`:""}`)}})}g();p1();import{execFileSync as G5,spawn as V5}from"node:child_process";import{createHash as _f,randomBytes as Uf}from"node:crypto";import{appendFileSync as Gf,closeSync as Vf,constants as zr,copyFileSync as Jf,existsSync as k1,mkdirSync as Ht,openSync as Yf,readdirSync as j2,readFileSync as Re,realpathSync as dt,rmSync as Bt,statSync as M2,utimesSync as Kf,writeFileSync as Bn,writeSync as Xf}from"node:fs";import{homedir as Sr}from"node:os";import{basename as U0,dirname as ge,join as N,relative as J5,resolve as _n,sep as Un}from"node:path";g();p1();e1();ie();import{execFile as l9}from"node:child_process";import{copyFileSync as jl,existsSync as Ml,mkdirSync as Ll,mkdtempSync as h9,readdirSync as Fl,readFileSync as $l,renameSync as c9,rmSync as o0,statSync as d9,writeFileSync as or}from"node:fs";import{tmpdir as u9}from"node:os";import{join as R1,resolve as Tl}from"node:path";import{promisify as m9}from"node:util";g();e1();import{createHash as Qq,randomBytes as Am}from"node:crypto";import{execFileSync as Go}from"node:child_process";import{existsSync as y1,mkdirSync as N1,readdirSync as ve,readFileSync as f2,realpathSync as K4,renameSync as Im,rmSync as L1,statfsSync as Rm,statSync as Tm,utimesSync as Om,writeFileSync as tt}from"node:fs";import{createServer as Em}from"node:net";import{basename as _o,dirname as Nm,join as j,resolve as Pm}from"node:path";g();import{spawn as Cm}from"node:child_process";var G4=()=>process.env.SANDBOX_RUNTIME==="1",Ho=()=>!!(process.env.https_proxy||process.env.HTTPS_PROXY||process.env.http_proxy||process.env.HTTP_PROXY);function Bo(){let[e,t]=process.versions.node.split(".").map(Number);return e>=24||e===22&&t>=21}var V4="Node 22.21 or later (or 24 and later)";function J4(e){return`In their Claude Code settings: add "${e}" to sandbox.filesystem.allowWrite, and add the same folder as a working directory (permissions.additionalDirectories, or /add-dir ${e}); set sandbox.network.allowLocalBinding to true, so the checks can run the app on localhost; add any tool the app needs that the sandbox can't run to sandbox.excludedCommands (for example "docker *"); and allow Canary's host when Claude Code asks. Canary changes no settings itself.`}function Y4(){if(process.argv[2]!=="jobs"||!Ho()||!Bo()||process.env.NODE_USE_ENV_PROXY==="1")return!1;let e=Cm(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1"}});for(let t of["SIGINT","SIGTERM","SIGHUP"])process.on(t,()=>e.kill(t));return e.on("exit",(t,n)=>process.exit(t??(n?1:0))),!0}var jm=12*6e4,Mm=720*6e4,Lm=336*60*6e4,Fm=3e3,$m=42e3,Uo=100,X4=40,Kq=2,E=class extends Error{constructor(n,q,r){super(q);this.code=n;this.fix=r;this.name="JobsError"}},B=()=>j(G(),"jobs"),Dm=2.2,Q4=26e8,Wm=1e9;function Vo(e,t,n=null){let q=Math.ceil(n!==null?e+n+Q4:t?e+Wm:e*Dm+Q4),r=Jo();return r<q?{needBytes:q,freeBytes:r}:null}function Jo(){N1(B(),{recursive:!0,mode:448});let{bavail:e,bsize:t}=Rm(B());return e*t}var Hm=e=>(Math.ceil(e/1e8)/10).toFixed(1),Bm=e=>(Math.floor(e/1e8)/10).toFixed(1),Sn=e=>`This batch's copy and the app's dependencies need about ${Hm(e.needBytes)} GB of free disk, and ${Bm(e.freeBytes)} GB is free.`;function el(){let e=B();try{N1(e,{recursive:!0,mode:448});let t=j(e,`.write-check-${process.pid}`);tt(t,""),L1(t,{force:!0})}catch(t){let n=t.code;throw n!=="EPERM"&&n!=="EACCES"&&n!=="EROFS"?t:Zq(n)}}function Zq(e){let t=B();return new E("jobs_folder_blocked",`Canary can't write to ${t} (${e==="EPERM"?"Operation not permitted":e}), probably because Claude Code's sandbox is on. Canary's checks can't run on this machine until that folder is allowed.`,`Ask the user to allow what Canary's checks need. ${J4(t)}`)}function v2(){let e=Number(process.env.CLAUDE_PID);if(!Number.isInteger(e)||e<=0)return null;let t=Oe(e);return t===null?null:{pid:e,startedAt:t}}function qt(e){try{process.kill(e.pid,0)}catch(n){if(n.code==="ESRCH")return"gone"}if(_m(e.pid))return"gone";let t=Oe(e.pid);return t===null?"unknown":Math.abs(t-e.startedAt)<=Fm?"alive":"gone"}function _m(e){try{return Go("ps",["-o","stat=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().startsWith("Z")}catch{return!1}}function u2(e){return!e||qt(e)!=="gone"}var tl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function he(e,t){if(!tl.test(e))throw new E("bad_id",`${JSON.stringify(e)} isn't a ${t} id.`,`Use the ${t} id Canary printed.`);return e}function C1(){let e=process.env.CLAUDE_CODE_SESSION_ID?.trim();if(!e)throw new E("no_session","canary jobs runs only inside a Claude Code session.");return e}function Y(e){try{return JSON.parse(f2(e,"utf8"))}catch{return null}}function F1(e,t,n=384){let q=`${e}.${process.pid}.tmp`;tt(q,JSON.stringify(t,null,2)+`
|
|
3198
|
+
`,{mode:n}),Im(q,e)}function nl(e){try{let t=new Date;Om(e,t,t)}catch{}}var Xq=(e,t)=>{try{return Date.now()-Tm(e).mtimeMs>=t}catch{return!0}},m2=e=>j(B(),"sessions",`${/^[A-Za-z0-9_-]{1,128}$/.test(e)?e:Qq("sha256").update(e).digest("hex").slice(0,32)}.json`);function te(e){return Y(m2(e))??{sessionId:e,runs:{},cursors:{}}}function Ae(e,t){N1(j(B(),"sessions"),{recursive:!0,mode:448});let n=t(te(e));return F1(m2(e),n),n}function Um(){let e=j(B(),"sessions");return y1(e)?ve(e).filter(t=>t.endsWith(".json")).map(t=>Y(j(e,t))).filter(t=>t!==null):[]}function ql(e){let t=`${m2(e)}.watch`,n=`${process.pid} ${Date.now()}`;return N1(j(B(),"sessions"),{recursive:!0,mode:448}),tt(t,n),()=>{try{return f2(t,"utf8")===n}catch{return!1}}}function rl(e){try{return K4(Go("git",["-C",e,"rev-parse","--path-format=absolute","--git-common-dir"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim())}catch{try{return K4(e)}catch{return Pm(e)}}}function Gm(e){let t=n=>Go("git",["-C",e,...n],{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:16777216}).trim();try{let n=t(["rev-parse","--is-shallow-repository"])==="true"?void 0:t(["rev-list","--max-parents=0","HEAD"]).split(`
|
|
3199
|
+
`).filter(Boolean).sort()[0];if(n)return`commit:${n}`}catch{}try{let n=t(["config","--get","remote.origin.url"]);return n?`origin:${n}`:null}catch{return null}}var Vm=(e,t)=>!!e&&!!t&&e!==t&&e.split(":")[0]===t.split(":")[0],et=()=>j(B(),"repos"),p2=e=>`${e.name.replace(/[^\w.-]/g,"_")}-${e.id.slice(0,8)}`;function sl(){return y1(et())?ve(et()).map(e=>Y(j(et(),e,"repo.json"))).filter(e=>e!==null):[]}function Yq(e){return N1(j(et(),p2(e)),{recursive:!0,mode:448}),F1(j(et(),p2(e),"repo.json"),e),e}function $1(e){let t=rl(e);return sl().find(n=>n.path===t)??null}function Et(e,t={}){let n=rl(e),q=sl(),r=q.find(i=>i.path===n);if(r&&!t.verify)return r;let s=Gm(e);if(r){if(!Vm(r.identity,s))return s&&r.identity!==s&&(!r.identity||s.startsWith("commit:"))?Yq({...r,identity:s}):r;Yq({...r,path:""})}let o=s?q.find(i=>i.identity===s&&i.path!==""&&i.path!==n&&!y1(i.path)):void 0;return Yq(o?{...o,path:n}:{id:Am(8).toString("hex"),path:n,identity:s,name:_o(n)===".git"?_o(Nm(n)):_o(n)})}function H1(e){let t=j(et(),p2(e));return{dir:t,canaryMd:j(t,"canary.md"),secrets:j(t,"secrets.env"),scripts:j(t,"scripts")}}var ol=e=>j(et(),e,"scripts"),Ce="## How the app runs here",il=`# Canary
|
|
3170
3200
|
|
|
3171
3201
|
Canary's verifiers read this file before every check and add what they learn after each run.
|
|
3172
3202
|
It stays on this machine, in Canary's own folder: outside the repository, shared by its worktrees, and never uploaded.
|
|
3173
3203
|
Add to the sections below; never rename, replace or remove them.
|
|
3174
3204
|
A verifier may correct or remove an earlier note in the last two sections once it has shown the note wrong, leaving the date and a short reason.
|
|
3175
3205
|
|
|
3176
|
-
Verifiers at a time: ${
|
|
3206
|
+
Verifiers at a time: ${Kq}
|
|
3177
3207
|
|
|
3178
3208
|
## Your instructions to Canary
|
|
3179
3209
|
|
|
@@ -3186,54 +3216,54 @@ Name them here; keep the values in secrets.env beside this file.
|
|
|
3186
3216
|
${Ce}
|
|
3187
3217
|
|
|
3188
3218
|
## What worked and what failed
|
|
3189
|
-
`;function
|
|
3190
|
-
`,{flag:"wx",mode:384}),t}var
|
|
3191
|
-
`).map(r=>r.trim()));return
|
|
3192
|
-
`).map(r=>r.trim()).filter(r=>r&&!q.has(r))}function rt(e){try{let t=$1(e),n=t&&/^\s*Verifiers at a time:\s*(\d+)\s*$/im.exec(f2(H1(t).canaryMd,"utf8")),q=n?Number(n[1]):
|
|
3193
|
-
`)[n]?.trim()||null}catch{return null}}var Xo=(e,t)=>
|
|
3194
|
-
${q}`);function rr(e){let t=j(B(),"approval-waits"),n=`${qr(e)}.`;return y1(t)?ve(t).filter(q=>q.startsWith(n)).flatMap(q=>{let r=Xo("approval-waits",q);return r?[{name:q,call:q.slice(n.length),batchId:r}]:[]}):[]}function
|
|
3195
|
-
`,{mode:384}),
|
|
3219
|
+
`;function g2(e){let t=H1(Et(e,{verify:!0}));return N1(t.scripts,{recursive:!0,mode:448}),y1(t.canaryMd)||tt(t.canaryMd,il,{flag:"wx"}),y1(t.secrets)||tt(t.secrets,`# Test secrets Canary's verifiers may use, as NAME=value. Never uploaded.
|
|
3220
|
+
`,{flag:"wx",mode:384}),t}var y2="notes-before.json",al=e=>e.includes(Ce)?e.slice(0,e.indexOf(Ce)):e;function ll(e){let t=$1(e),n=il;try{t&&(n=f2(H1(t).canaryMd,"utf8"))}catch{}return{at:new Date().toISOString(),notes:al(n)}}function hl(e,t){let n;try{n=f2(t,"utf8")}catch{return[]}let q=new Set(e.notes.split(`
|
|
3221
|
+
`).map(r=>r.trim()));return al(n).split(`
|
|
3222
|
+
`).map(r=>r.trim()).filter(r=>r&&!q.has(r))}function rt(e){try{let t=$1(e),n=t&&/^\s*Verifiers at a time:\s*(\d+)\s*$/im.exec(f2(H1(t).canaryMd,"utf8")),q=n?Number(n[1]):Kq;return q>=1&&q<=8?q:Kq}catch{return Kq}}var s1=e=>j(B(),"runs",he(e,"run"));function er(e){y1(s1(e))&&tt(j(s1(e),"heartbeat"),"")}var c1=e=>j(B(),"batches",he(e,"batch"));function u1(e){return j(B(),"workspaces",e.repoFolder,String(e.slot))}function cl(e){N1(j(B(),"workspaces",e.repoFolder),{recursive:!0,mode:448}),tt(j(B(),"workspaces",e.repoFolder,`${e.slot}.used`),"")}function Jm(e){let t=j(B(),"workspaces");for(let n of y1(t)?ve(t):[]){let q=j(t,n),r=Y(j(et(),n,"repo.json")),s=r!==null&&(r.path===""||!y1(r.path));for(let o of ve(q).filter(i=>/^\d+$/.test(i))){let i=j(q,o),a=y1(j(q,`${o}.used`))?j(q,`${o}.used`):i;e.has(i)||!(s||Xq(a,Lm))||(L1(i,{recursive:!0,force:!0}),L1(j(q,`${o}.used`),{force:!0}))}ve(q).some(o=>/^\d+$/.test(o))||L1(q,{recursive:!0,force:!0})}}var w2=(e,t,n)=>n?j(c1(e),"packs",he(t,"job"),`proof-${n}`):j(c1(e),"packs",he(t,"job")),b2=e=>j(c1(e),"scratch"),nt=e=>j(c1(e),"state.json");function dl(e){N1(j(B(),"batches"),{recursive:!0,mode:448}),ul(e)&&L1(c1(e),{recursive:!0,force:!0});try{N1(c1(e),{mode:448})}catch(t){if(t.code==="EEXIST"){let n=Y(nt(e))?.left;throw n?new E("leftovers",`What an earlier verifier of this batch started is still here: ${n.join("; ")}.`,`Remove it, then run canary jobs finish ${e} to check again.`):new E("already_taken","A verifier on this machine already took this batch.",`If its verifier ended, give the batch back first: canary jobs finish ${e} --give-back`)}throw t}}function st(e){let t=Y(nt(e));if(!t)throw new E("not_taken_here","This batch wasn't taken on this machine.",`Take it first: canary jobs take ${e}`);return nl(nt(e)),t}function Cn(e){F1(nt(e.batchId),e)}function X(){let e=j(B(),"batches");return y1(e)?ve(e).filter(t=>tl.test(t)).map(t=>Y(nt(t))).filter(t=>t!==null):[]}var An=e=>X().some(t=>t.setAside===!0&&t.checkout===e);function k2(e){he(e,"job");let t=X().find(n=>n.jobs.some(q=>q.jobId===e));if(!t)throw new E("not_taken_here","No batch taken on this machine holds this job.","Use the job id take printed.");return nl(nt(t.batchId)),t}var Yo=e=>Qq("sha256").update(e).digest("hex").slice(0,16);function Ko(e,t,n){try{N1(e,{mode:448})}catch(q){if(q.code!=="EEXIST")throw q;if(!n(Y(j(e,"owner.json"))))return!1;L1(e,{recursive:!0,force:!0});try{N1(e,{mode:448})}catch{return!1}}return F1(j(e,"owner.json"),t),!0}var tr=e=>!e?.batchId||ul(e.batchId),Ym=2*6e4;function ul(e){return y1(c1(e))?!y1(nt(e))&&Xq(c1(e),Ym):!0}function ml(e,t){let n=j(B(),"slots");N1(n,{recursive:!0,mode:448});for(let q=0;q<t;q++)if(Ko(j(n,String(q)),{batchId:e},r=>r?.batchId===e||tr(r)))return q;return null}var pl=e=>Y(j(B(),"slots",String(e),"owner.json"))?.batchId??null;function In(e){let t=j(B(),"slots");for(let n=0;n<e;n++)if(!y1(j(t,String(n)))||tr(Y(j(t,String(n),"owner.json"))))return!0;return!1}var fl=e=>j(B(),"waiting",`${he(e,"batch")}.json`);function Rn(e,t,n){N1(j(B(),"waiting"),{recursive:!0,mode:448}),F1(fl(e),{batchId:e,sessionId:t,checkout:n})}var ot=e=>L1(fl(e),{force:!0});function Tn(e){let t=j(B(),"waiting");return y1(t)?ve(t).map(n=>Y(j(t,n))).filter(n=>n!==null&&n.sessionId===e):[]}function nr(e){for(let t of["slots","ports","locks"]){let n=j(B(),t);if(y1(n))for(let q of ve(n))Y(j(n,q,"owner.json"))?.batchId===e&&L1(j(n,q),{recursive:!0,force:!0})}for(let t of Km)for(let n of Qo(t,e))L1(j(B(),t,n),{force:!0});L1(sr(e),{force:!0})}var Km=["verifiers","approval-waits"],qr=e=>/^[A-Za-z0-9_-]{1,96}$/.test(e)?e:Qq("sha256").update(e).digest("hex").slice(0,32);function vl(e,t,n){try{return f2(j(B(),e,t),"utf8").split(`
|
|
3223
|
+
`)[n]?.trim()||null}catch{return null}}var Xo=(e,t)=>vl(e,t,0);function Qo(e,t){let n=j(B(),e);return y1(n)?ve(n).filter(q=>Xo(e,q)===t):[]}function gl(e,t,n){N1(j(B(),e),{recursive:!0,mode:448}),tt(j(B(),e,t),n,{mode:384})}var yl=(e,t)=>gl("verifiers",qr(e),t),ne=e=>Xo("verifiers",qr(e)),wl=e=>Qo("verifiers",e).length>0,bl=(e,t,n,q="")=>gl("approval-waits",`${qr(e)}.${t}`,`${n}
|
|
3224
|
+
${q}`);function rr(e){let t=j(B(),"approval-waits"),n=`${qr(e)}.`;return y1(t)?ve(t).filter(q=>q.startsWith(n)).flatMap(q=>{let r=Xo("approval-waits",q);return r?[{name:q,call:q.slice(n.length),batchId:r}]:[]}):[]}function On(e){for(let t of e)L1(j(B(),"approval-waits",t),{force:!0})}var sr=e=>j(B(),"approval-owed",he(e,"batch"));function Zo(e,t){N1(j(B(),"approval-owed"),{recursive:!0,mode:448}),F1(sr(e),t)}var e0=e=>Y(sr(e));function En(e,t){(!t||e0(e)?.call===t)&&L1(sr(e),{force:!0})}var $e=e=>Qo("approval-waits",e),Nn=e=>vl("approval-waits",e,1),Xm=e=>j(B(),"locks",Qq("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,24));function kl(e,t,n){return N1(j(B(),"locks"),{recursive:!0,mode:448}),Ko(Xm(e),{batchId:t,jobId:n,target:e},q=>tr(q)||q?.batchId===t)}function t0(e,t){let n=j(B(),"locks");if(y1(n))for(let q of ve(n)){let r=Y(j(n,q,"owner.json"));r?.batchId===e&&r.jobId===t&&L1(j(n,q),{recursive:!0,force:!0})}}async function zl(e,t){let n=j(B(),"ports");N1(n,{recursive:!0,mode:448});for(let q=0;q<X4;q++){let r=$m+(t+q)%X4*Uo;if(!Ko(j(n,String(r)),{batchId:e},o=>o?.batchId===e||tr(o)))continue;let s=!0;for(let o=r;o<r+Uo&&s;o++)s=await Qm(o);if(s)return[r,r+Uo-1];L1(j(n,String(r)),{recursive:!0,force:!0})}throw new E("no_ports","No free block of ports for this batch.","Stop what is listening on ports 42000 to 45999, then take the batch again.")}async function Qm(e){return await Z4(e,"127.0.0.1")&&await Z4(e,"::1")}function Z4(e,t){return new Promise((n,q)=>{let r=Em();r.once("error",s=>{if(s.code==="EADDRNOTAVAIL"&&t==="::1")return n(!0);if(s.code!=="EPERM"&&s.code!=="EACCES")return n(!1);q(new E("local_ports_blocked",`Canary can't use ports on localhost here (${s.code}), probably because Claude Code's sandbox is on.`,"Ask the user to set sandbox.network.allowLocalBinding to true in their Claude Code settings, then take the batch again. Canary changes no settings itself."))}),r.listen(e,t,()=>r.close(()=>n(!0)))})}async function xl(e){let t=X();for(let r of t)u2(r.owner)||u2(te(r.sessionId).owner)||!Xq(nt(r.batchId),jm)||await e(r).catch(()=>{});let n=X();try{Jm(new Set(n.map(u1)))}catch{}let q=new Set(n.map(r=>r.runId));for(let r of Um())if(!u2(r.owner)){for(let s of Tn(r.sessionId))ot(s.batchId);try{let s=!1;for(let o of Object.keys(r.runs)){let i=s1(o),a=y1(j(i,"heartbeat"))?j(i,"heartbeat"):i;q.has(o)||y1(i)&&!Xq(a,Mm)||(L1(i,{recursive:!0,force:!0}),delete r.runs[o],s=!0)}if(Object.keys(r.runs).length===0)for(let o of[m2(r.sessionId),`${m2(r.sessionId)}.watch`])L1(o,{force:!0});else s&&F1(m2(r.sessionId),r)}catch{}}}o2();M1();g();e1();Le();import{existsSync as Zm,mkdirSync as e9,readFileSync as t9,readdirSync as n0,renameSync as n9,rmSync as Sl,statSync as q9,writeFileSync as r9}from"node:fs";import{join as qe}from"node:path";var s9=5,o9=336*60*6e4,i9=8,q0=()=>qe(G(),"versions"),Cl=e=>qe(q0(),e);function r0(e){try{let t=JSON.parse(t9(qe(e,"versions.json"),"utf8"));return Array.isArray(t.versions)?t.versions:[]}catch{return[]}}function Al(e,t){let n=qe(e,`versions.json.${process.pid}.tmp`);r9(n,JSON.stringify({versions:t},null,2)+`
|
|
3225
|
+
`,{mode:384}),n9(n,qe(e,"versions.json"))}function s0(e,t){let n=new Map;return e.filter(q=>{let r=JSON.stringify([q.folder,q.branch]),s=(n.get(r)??0)+1;return n.set(r,s),s<=s9&&t-Date.parse(q.at)<o9})}function Il(e,t,n=Date.now()){let q=Cl(e),r=s0(r0(q),n).filter(s=>s.folder===t.root&&s.branch===t.branch);return r.length?{objects:qe(q,"objects"),versions:r.map(({requestId:s,treeHash:o})=>({requestId:s,treeHash:o}))}:null}async function Rl(e,t,n,q=Date.now()){let r=Cl(e);e9(r,{recursive:!0,mode:448});let s=U2(qe(r,"lock"),"the store of earlier versions");try{let o=new ze(r,void 0,!0);Zm(qe(r,"objects"))||await o.run(["init","--bare","--quiet","--template="]),await t.keep(r);let i={requestId:n,treeHash:t.manifest.treeHash,folder:t.root,branch:t.manifest.provenance.branch,at:new Date(q).toISOString()},a=s0([i,...r0(r).filter(c=>c.requestId!==n)],q);Al(r,a);let l=qe(r,"objects","pack");if(n0(l).filter(c=>c.endsWith(".pack")).length>i9){let c=n0(l).filter(m=>m.startsWith("pack-")),h=[...new Set(a.map(m=>jq(m.treeHash)))],d=(await o.run(["pack-objects","--revs","--missing=allow-any","-q",qe(l,"pack")],{input:`${h.join(`
|
|
3196
3226
|
`)}
|
|
3197
|
-
`})).toString("utf8").trim();for(let m of c)m.startsWith(`pack-${d}.`)||
|
|
3198
|
-
`);for(let n=t.length-1;n>=0;n--)if(
|
|
3227
|
+
`})).toString("utf8").trim();for(let m of c)m.startsWith(`pack-${d}.`)||Sl(qe(l,m),{force:!0})}}finally{s()}for(let o of n0(q0()))o!==e&&a9(qe(q0(),o),q)}function a9(e,t){if(!q9(e,{throwIfNoEntry:!1})?.isDirectory())return;let n;try{n=U2(qe(e,"lock"),"the store of earlier versions")}catch{return}try{let q=r0(e),r=s0(q,t);r.length?r.length<q.length&&Al(e,r):Sl(e,{recursive:!0,force:!0})}finally{n()}}Le();Hq();Qe();var p9=m9(l9),f9=1e5,v9=8*6e4,g9=3e4,y9=1440*6e4;function Dl(e,t,n){let q=e[0]==="--json",r=e.length>1&&e[e.length-1]==="--json",s=e.slice(q?1:0,r?-1:void 0),o=q||r;if(s.length===1&&s[0]==="-")return{json:o,words:null};let i=new Set(["--json","--verifier"]);if(e.includes("-")&&e.includes("--verifier")&&e.every(l=>l==="-"||i.has(l))&&e.filter(l=>l==="-").length===1)return{json:e.includes("--json"),words:null,verifier:!0};let a=s[0];return a===void 0||n.has(a)||t.has(a)?null:{json:o,words:s.join(" ")}}var w9=/^[ \t]*-{3,}[ \t]*from the user['’]s agent[ \t]*-{3,}[ \t\r]*$/i;function b9(e){let t=e.split(`
|
|
3228
|
+
`);for(let n=t.length-1;n>=0;n--)if(w9.test(t[n]))return{words:t.slice(0,n).join(`
|
|
3199
3229
|
`),agentContext:t.slice(n+1).join(`
|
|
3200
|
-
`).trim()||null};return{words:e,agentContext:null}}var
|
|
3201
|
-
`),n=o
|
|
3230
|
+
`).trim()||null};return{words:e,agentContext:null}}var Wl=/^[ \t]*#{1,6}[ \t]+(.+?)[ \t#]*$/,Ol=/^since your last\b/i,Hl=/^where it runs$/i,k9=[{start:/^[ \t]*(?:[-*][ \t]+)?the user['’]s words:[ \t]?/i,from:"person"},{start:/^[ \t]*(?:[-*][ \t]+)?the user chose:[ \t]?/i,from:"person"},{start:/^[ \t]*(?:[-*][ \t]+)?i decided:[ \t]?/i,from:"decision"},{start:/^[ \t]*(?:[-*][ \t]+)?spec from[ \t]+(?=[^:\n]+:)/i,from:"source",as:"From "}];function z9(e){if(e===null)return null;let t=e.replace(/\r/g,"").split(`
|
|
3231
|
+
`),n=o=>Wl.exec(o)?.[1]?.trim();if(!t.some(o=>Ol.test(n(o)??"")))return A9(t);let q=[],r=null,s=null;for(let o of t){let i=n(o);if(i!==void 0&&Ol.test(i)){s="said";continue}if(i!==void 0&&Hl.test(i)){s="place",r??=[];continue}if(s==="place"){r.push(o);continue}if(s!=="said")continue;let a=k9.find(l=>l.start.test(o));a?q.push({from:a.from,text:o.replace(a.start,a.as??"")}):q.length>0&&(q[q.length-1].text+=`
|
|
3202
3232
|
${o}`)}return{said:q.map(o=>({...o,text:o.text.trim()})).filter(o=>o.text),place:r===null?null:r.join(`
|
|
3203
|
-
`).trim()}}var
|
|
3233
|
+
`).trim()}}var El={prompts:/^the user['’]s prompts$/i,choices:/^the user['’]s choices$/i,decisions:/^decisions i made$/i,sources:/^specs and tickets$/i,place:Hl},x9=/^[ \t]*the user['’]s words:[ \t]?/i,S9=/^[ \t]*the user chose:[ \t]?/i,Nl=/^[ \t]*from[ \t]+[^:\n]+:/i,C9=/^[ \t]*[-*][ \t]+/;function A9(e){let t={},n=null;for(let i of e){let a=Wl.exec(i)?.[1]?.trim(),l=a===void 0?void 0:Object.keys(El).find(c=>El[c].test(a));if(l){n=l,t[l]??=[];continue}n&&t[n].push(i)}let q=(i,a,l=!1)=>i.reduce((c,h)=>(a.test(h)?c.push(l?h:h.replace(a,"")):c.length>0&&(c[c.length-1]+=`
|
|
3204
3234
|
${h}`),c),[]).map(c=>c.trim()).filter(Boolean),r=(i=[],a)=>i.some(l=>a.test(l))?q(i,a):i.map(l=>l.trim()).filter(Boolean),s=i=>i.join(`
|
|
3205
|
-
`).trim(),o=t.sources??[];return{prompts:r(t.prompts,
|
|
3206
|
-
`).trim();if(s.length<=
|
|
3207
|
-
`,o-1);return s.slice(i>=0?i+1:o).trimStart()}function
|
|
3208
|
-
`)}}var Nt=e=>R1(G(),"requests",e);function
|
|
3235
|
+
`).trim(),o=t.sources??[];return{prompts:r(t.prompts,x9),choices:r(t.choices,S9),decisions:t.decisions?r(t.decisions,C9):null,sources:o.some(i=>Nl.test(i))?q(o,Nl,!0):[s(o)].filter(Boolean),place:t.place?s(t.place):null}}function I9(e,t){return t?b9(e):{words:e,agentContext:null}}var R9="## Your instructions to Canary",T9=new Set([Ce,"## What worked and what failed"]),Pl=16e3;function O9(e){let t=e.split(/\r?\n/),n=t.findIndex(a=>/^ {0,3}(?=#)/.test(a)&&a.trim()===R9);if(n<0||t.slice(0,n).some(a=>/^ {0,3}(?=#)/.test(a)&&T9.has(a.trim())))return null;let q=t.slice(n+1),r=q.findIndex(a=>/^ {0,3}##(?:[ \t]|$)/.test(a)),s=(r<0?q:q.slice(0,r)).join(`
|
|
3236
|
+
`).trim();if(s.length<=Pl)return s||null;let o=s.length-Pl,i=s.indexOf(`
|
|
3237
|
+
`,o-1);return s.slice(i>=0?i+1:o).trimStart()}function E9(e){try{let t=$1(e);return t?O9($l(H1(t).canaryMd,"utf8")):null}catch{return null}}function N9(e,t,n){let q=new Map,r=t.split("\0");for(let i=0;i<r.length;i++){let a=/^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(r[i]);if(!a)continue;let l=a[3]||r[i+=2];l&&q.set(l,{added:a[1]==="-"?null:Number(a[1]),removed:a[2]==="-"?null:Number(a[2])})}let s=[],o=e.split("\0");for(let i=0;i<o.length;i++){let a=o[i];if(!a)continue;if(a[0]==="R"||a[0]==="C"){let h=o[i+=2];h&&s.push({path:h,status:a[0]==="R"?"renamed":"added",...q.get(h)??{added:null,removed:null}});continue}let l=o[++i];if(!l)continue;let c=a[0]==="A"?"added":a[0]==="D"?"deleted":"modified";s.push({path:l,status:c,...q.get(l)??{added:null,removed:null}})}return s.push(...Bl(n)),s}function Bl(e){let t=[],n=e.split("\0");for(let q=0;q<n.length;q++){let r=n[q];if(r.length<4)continue;let s=r.slice(0,2);s.includes("R")||s.includes("C")?q++:s==="??"&&t.push({path:r.slice(3),status:"untracked",added:null,removed:null})}return t}function P9(e,t){return[...e.split("\0").filter(Boolean).map(q=>({path:q,status:"added",added:null,removed:null})),...Bl(t)]}async function it(e,t,n={}){try{return(await p9("git",["-c","core.fsmonitor=false",...t],{cwd:e,env:{...pq(),...n},timeout:g9,maxBuffer:64*1024*1024})).stdout}catch{return null}}async function j9(e){let t=(await it(e,["rev-parse","--git-path","index"]))?.trim();if(!t||!Ml(Tl(e,t)))return{env:{},dispose:()=>{}};let n=h9(R1(u9(),"canary-index-"));return jl(Tl(e,t),R1(n,"index")),{env:{GIT_INDEX_FILE:R1(n,"index")},dispose:()=>o0(n,{recursive:!0,force:!0})}}async function M9(e,t){let n=await za(e).catch(()=>null),q=await j9(e),[r,s,o,i,a]=await Promise.all([it(e,["rev-parse","--abbrev-ref","HEAD"]),it(e,["rev-parse","HEAD"]),it(e,["status","--porcelain=v1","-z","--untracked-files=normal"]),n?it(e,["diff","--name-status","-z","--find-renames",n],q.env):it(e,["ls-files","-z"]),n?it(e,["diff","--numstat","-z","--find-renames",n],q.env):Promise.resolve("")]).finally(q.dispose);if(o===null||i===null||a===null)throw new n1("checkout_unreadable","Canary couldn't read this checkout's changes with git. Check that `git status` works here, then run the command again.");let l=r?.trim();return{repo:{name:t,branch:l&&l!=="HEAD"?l:null,head:s?.trim()||null,uncommitted:o.length>0},changes:{files:n?N9(i,a,o):P9(i,o)}}}var L9=500;async function F9(e,t){return t?(await it(e,["log",`--max-count=${L9}`,"--format=%B%x00",`${t}..HEAD`])??"").split("\0").map(q=>q.trim()).filter(Boolean):[]}function $9(e,t=""){try{let n=R1(G(),"requests");Ll(n,{recursive:!0,mode:448}),or(R1(n,`${e}.asked`),t,{mode:384})}catch(n){process.stderr.write(`Canary couldn't note this request on this machine (${n instanceof Error?n.message:String(n)}); \`canary show\` needs its whole id.
|
|
3238
|
+
`)}}var Nt=e=>R1(G(),"requests",e);function D9(e,t,n,q,r){let s=Nt(e);Ll(s,{recursive:!0,mode:448});let o=R1(G(),"requests");for(let i of Fl(o,{withFileTypes:!0}))if(!(!i.isDirectory()||i.name===e))try{Date.now()-d9(R1(o,i.name)).mtimeMs>y9&&o0(R1(o,i.name),{recursive:!0,force:!0})}catch{}try{c9(t.bundlePath,R1(s,"source.bundle"))}catch(i){if(i.code!=="EXDEV")throw i;jl(t.bundlePath,R1(s,"source.bundle"))}or(R1(s,"source.json"),JSON.stringify(t.manifest,null,2)+`
|
|
3209
3239
|
`,{mode:384}),or(R1(s,"request.json"),JSON.stringify({checkout:n,chat:q,...r})+`
|
|
3210
|
-
`,{mode:384}),or(R1(s,
|
|
3211
|
-
`,{mode:384})}function
|
|
3212
|
-
`:""}Canary \xB7 more to come: canary wait ${l.requestId}`)),process.exitCode=l.exitCode}catch(a){if(r)return;r=!0,_9(n,a)}finally{clearTimeout(s)}}function W9(e,t){let n=kt();return{...n?{"x-canary-session":n}:{},...e?{"x-canary-verifier":"1","x-canary-verifiers":String(rt(t))}:{}}}async function H9(e,t,n,q){let{words:r,agentContext:s}=n.words===null?
|
|
3213
|
-
`)});q.keepFor
|
|
3214
|
-
`||i){t.push(n),n="",i&&s++;continue}if(e.startsWith("2>&1",s)&&/\s/.test(e[s-1]??"")){s+=3;continue}if(/[&|<>`$()\\#]/.test(o))return!1;n+=o}if(q)return!1;let r=[...t,n].map(s=>s.trim()).filter(Boolean);return r.length>0&&r.every(s=>/^canary\s+jobs\s/.test(`${s} `))}var qp=new Set(["cat","head","tail","ls","wc","stat","grep"]),rp=new Set(["head","tail","wc","grep","uniq"]);function
|
|
3240
|
+
`,{mode:384}),or(R1(s,y2),JSON.stringify(ll(n))+`
|
|
3241
|
+
`,{mode:384})}function _l(e){let t=R1(G(),"requests");return(Ml(t)?Fl(t,{withFileTypes:!0}):[]).filter(n=>n.isDirectory()).map(n=>R1(t,n.name)).filter(n=>{try{return JSON.parse($l(R1(n,"request.json"),"utf8")).chat===e}catch{return!1}})}var Ul=e=>_l(e).length>0;function Gl(e){for(let t of _l(e))try{o0(R1(t,"source.bundle"),{force:!0})}catch{}}async function i0(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function Vl(e,t){let{json:n}=t;Q1({cwd:e,agent:n,mode:"request"});let q=Q();if(!q)return $(n,"not_logged_in","Not logged in","run `canary login` first",3);(await Promise.resolve().then(()=>(mq(),E3))).installAgentSkill(),(await Promise.resolve().then(()=>(Ws(),R3))).installAgentPlugin();let r=!1,s,o={requestId:null,creating:null,capturing:null,codeSent:!1,token:q,extend:a=>{clearTimeout(s),s=i(a)}},i=a=>setTimeout(()=>{r||(r=!0,U9(n,o))},a);s=i(f9);try{let a=await H9(e,q,t,o);$9(a.answer.requestId,e);let l=G9(a.answer);if(a.codeMissing&&(l.exitCode=3),r)return;r=!0,n?console.log(JSON.stringify(l)):(l.say&&console.log(l.say),l.ended||console.log(`${l.say?`
|
|
3242
|
+
`:""}Canary \xB7 more to come: canary wait ${l.requestId}`)),process.exitCode=l.exitCode}catch(a){if(r)return;r=!0,_9(n,a)}finally{clearTimeout(s)}}function W9(e,t){let n=kt();return{...n?{"x-canary-session":n}:{},...e?{"x-canary-verifier":"1","x-canary-verifiers":String(rt(t))}:{}}}async function H9(e,t,n,q){let{words:r,agentContext:s}=n.words===null?I9(await i0(),n.json):{words:n.words,agentContext:null},o=je(e,t).then(async l=>({context:l,repository:await Pe({...l,token:t})}));o.catch(()=>{});let i=new AbortController,a=It(e,{signal:i.signal,earlier:async l=>Il((await o).repository.repositoryId,l)});a.catch(()=>{}),q.capturing=a;try{let{context:l,repository:c}=await o,h=E9(e),d=z9(s),m={workspaceId:l.workspaceId,repositoryId:c.repositoryId,words:r,agentContext:s,...h?{instructions:h}:{},...d?{pack:d}:{},...await M9(e,c.name)};q.creating=W("/api/v1/cli/requests",{method:"POST",token:t,body:m,headers:W9(n.verifier===!0,e)}).then(vn);let u=await q.creating;if(!u.needsCode)return{answer:u,codeMissing:!1};q.requestId=u.requestId,q.extend(v9);let p=n.verifier===!0?kt():null,f=await B9(e,u.requestId,a,{context:l,repositoryId:c.repositoryId,token:t,keepFor:p});return q.codeSent=!0,{answer:{...f.answer,say:fn([u.say,f.answer.say]),do:[...u.do,...f.answer.do]},codeMissing:f.codeMissing}}finally{i.abort(),a.then(l=>l.dispose(),()=>{})}}async function B9(e,t,n,q){let r=c=>W(`/api/v1/cli/requests/${t}/source`,{method:"POST",token:q.token,body:c}).then(vn).catch(h=>{throw h instanceof L&&h.status===413?new L(413,"This branch's commit messages are bigger than Canary takes with the code (8 MB).","squash or shorten the longest commit messages",void 0,"commit_messages_too_large"):h}),s;try{s=await n}catch(c){let h=c instanceof W1?c.code:"capture_failed",d=c instanceof W1&&c.fix?`${c.message} To fix it: ${c.fix}.`:c instanceof Error?c.message:String(c);return{answer:await r({unavailable:{code:h,message:d}}),codeMissing:!0}}let o=`request:${t}`,i;try{i=await h2(s,q.context,q.repositoryId,q.token,{requestKey:o,fresh:!0})}catch(c){throw await r({unavailable:{code:"upload_failed",message:"The upload of your code didn't finish."}}).catch(()=>{}),c}let a=Rl(q.repositoryId,s,t).catch(c=>{process.stderr.write(`Canary couldn't keep this code to compare later requests with (${c instanceof Error?c.message:String(c)}); a later request reads the whole change.
|
|
3243
|
+
`)});q.keepFor&&D9(t,s,e,q.keepFor,{workspaceId:q.context.workspaceId,repositoryId:q.repositoryId});let l=await r({source:i,commitMessages:await F9(e,s.manifest.provenance.baseSha),...s.submodules.length?{submodules:[...s.submodules]}:{}}).finally(()=>a);return mn(s.manifest,q.context,q.repositoryId,{requestKey:o,uploadId:i.uploadId}),{answer:l,codeMissing:!1}}function _9(e,t){if(t instanceof n1)return $(e,t.code,t.message,void 0,3);if(t instanceof L)return t.status===413&&t.code==="commit_messages_too_large"?$(e,t.code,t.message,t.fix,3):t.status===413?$(e,"too_large","This request is bigger than Canary takes in one go (8 MB).","send fewer words or less pasted output",3):t.status===401?$(e,"not_logged_in","Your Canary login is no longer valid.","run `canary login`",3):t.code==="source_upload_unavailable"?$(e,t.code,"Canary couldn't store your code just now.","run the same command again in a minute",2):$(e,t.code??"api_error",t.message,t.fix,z1(t)||t.status>=500?2:3);let n=yn(t);if(n)return $(e,"home_not_writable",n.message,n.fix,2);$(e,"internal_error",t instanceof Error?t.message:String(t),void 0,2)}async function U9(e,t){$(e,"timed_out","Canary didn't answer in time.","run the same command again",2);let n=[],q=r=>W(`/api/v1/cli/requests/${r}/source`,{method:"POST",token:t.token,signal:AbortSignal.timeout(5e3),body:{unavailable:{code:"upload_timeout",message:"The upload of your code didn't finish in time."}}}).catch(()=>{});t.requestId&&!t.codeSent?n.push(q(t.requestId)):!t.requestId&&t.creating&&n.push(t.creating.then(r=>r.needsCode?q(r.requestId):void 0,()=>{})),t.capturing&&n.push(t.capturing.then(r=>r.dispose(),()=>{})),await Promise.race([Promise.all(n),new Promise(r=>setTimeout(r,6e3))]),process.stderr.write("",()=>process.stdout.write("",()=>process.exit(2)))}function G9(e){let t=e.ending==="failed"?2:0;return{ok:!0,requestId:e.requestId,say:Fe(e.say),do:e.do,ended:e.ending!==null,exitCode:t}}e1();o2();M1();Le();Wq();g();var a0={session:"x-canary-session",batchKey:"x-canary-batch-key"},Pt=/^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}(\/[A-Za-z0-9_][A-Za-z0-9._-]{0,99}){0,7}$/;g();p1();e1();ie();import{randomUUID as V9}from"node:crypto";bt();function J9(){let e=K().installId;return{[g1.cli]:ke,[g1.command]:"jobs",[g1.harness]:"claude-code",...e&&/^[0-9a-f-]{36}$/.test(e)?{[g1.install]:e}:{}}}var l0=45e3,Y9=6e4;async function Yl(e,t){let n=Q();if(!n)throw new E("not_logged_in","Not logged in to Canary.","Run canary login.");let q=a1().replace(/\/+$/,""),r={...J9(),authorization:`Bearer ${n}`,[a0.session]:t.session};t.batchKey&&(r[a0.batchKey]=t.batchKey),t.json!==void 0&&(r["content-type"]="application/json"),t.bytes&&(r["content-type"]="application/octet-stream");let s=new AbortController,o=setTimeout(()=>s.abort(new Error("timed out")),t.timeoutMs??Y9),i=s.signal,a;try{a=await fetch(`${q}/api/v1${e}`,{method:t.method??(t.json!==void 0||t.bytes?"POST":"GET"),headers:r,body:t.json!==void 0?JSON.stringify(t.json):t.bytes,signal:i})}catch{throw Jl(q)}finally{clearTimeout(o)}if(a.ok)return a;let l=await a.json().catch(()=>null);throw typeof l?.error!="string"?Jl(q):a.status>=500?new L(a.status,at):a.status===401?new E("not_logged_in","Canary no longer accepts this CLI login.","Ask the user to run canary login, then run the command again."):new L(a.status,l.error,typeof l.fix=="string"&&l.fix?l.fix:void 0,void 0,typeof l.code=="string"&&l.code?l.code:void 0)}var at="Canary hit an internal error; retry shortly.";function Jl(e){let t=new URL(e).host,n=Ho()?Bo()?`If Claude Code's sandbox is on, ask the user to allow ${t}: choose "Yes, and don't ask again for ${t}" when Claude Code asks, or add it to sandbox.network.allowedDomains in their Claude Code settings.`:`Node ${process.versions.node} can't send requests through Claude Code's sandbox; ask the user to update to ${V4}.`:"Run it again in a minute.";return new L(0,"Couldn't reach Canary.",n)}async function i1(e,t){let n=await Yl(e,t);return n.status===204?null:await n.json()}async function Kl(e,t){return Buffer.from(await(await Yl(e,t)).arrayBuffer())}var De=e=>z1(e)||e instanceof L&&e.status>=500,K9=new Set(["batch_released","batch_ended","nothing_left","not_found"]),ir=e=>e instanceof L&&!!e.code&&K9.has(e.code);async function U1(e,t=0){let n=Date.now()+t;for(let q=1;;q++)try{return await e()}catch(r){if(!De(r)||q>=3&&Date.now()>=n)throw r;await new Promise(s=>setTimeout(s,Math.min(q*2e3,1e4)))}}function Pn(e,t,n,q){let r=n instanceof Error?n.stack??n.message:String(n),s={reportId:V9(),...t.batchId?{batchId:t.batchId}:{},...t.jobId?{jobId:t.jobId}:{},cause:r.slice(0,8e3)};return U1(()=>i1("/cli/jobs/internal-error",{session:e,batchKey:t.batchKey,json:s,timeoutMs:q}))}g();e1();import{execFile as up,execFileSync as $n}from"node:child_process";import{readdirSync as jh,readFileSync as mp,readlinkSync as Mh,realpathSync as Lh,rmSync as Nh}from"node:fs";import{basename as pp,join as Ph,sep as Fh}from"node:path";import{promisify as fp}from"node:util";g();import{appendFileSync as op,mkdirSync as yh,readFileSync as dr,rmSync as ph,writeFileSync as ip}from"node:fs";import{createHash as wh}from"node:crypto";import{basename as fh,dirname as bh,join as ur}from"node:path";g();e1();import{execFileSync as X9}from"node:child_process";import{mkdirSync as Q9,rmSync as Z9}from"node:fs";import{basename as ep,join as Zl}from"node:path";var eh="Canary's checks run commands on this machine to build and test this project, and Claude Code would ask you to approve each one. Let them run without asking, in this repository?",h0={label:"Run without asking",description:"They work in their own copy of your code and remove what they start. A command that would remove something they didn't create is stopped, or comes to you first. Reading your keys and sign-ins (SSH, cloud, keychain, password managers) is stopped."},th={label:"Keep asking",description:"Claude Code asks you about each command, following your own settings."},c0={label:"Use them",description:"The checks' copy of the app runs with your real keys and reaches the hosted services they point to, where a check may create test data of its own and remove it. What points at this machine is replaced by the checks' own services. What the app shows can appear in the evidence sent to Canary."},nh={label:"Don't use them",description:"The checks set up what they can themselves and ask you for any key they need."};function qh(e){return`This project's env files (${e.length>3?`${e.slice(0,3).join(", ")} and ${e.length-3} more`:e.join(", ")}) hold the keys and service addresses the app runs with. May Canary's checks run their copy of the app with them?`}var lr=e=>Zl(G(),"approvals",`${e}.json`);function rh(e,t){let n=Et(e),q=Y(lr(n.id))??{repo:n.path};t(q),Q9(Zl(G(),"approvals"),{recursive:!0,mode:448}),F1(lr(n.id),q)}function sh(e){let t=$1(e);return t&&Y(lr(t.id))}function jt(e){let t=sh(e);return t?.commands?t:null}function oh(e,t){rh(e,n=>Object.assign(n,{commands:t.trim()===h0.label?"run":"ask",answer:t,at:new Date().toISOString()}))}var hr=e=>sh(e)?.envFiles??null;function ih(e,t,n){rh(e,q=>{q.envFiles={use:n.trim()===c0.label,files:t,answer:n,at:new Date().toISOString()}})}function ah(e){let t=$1(e);t&&Z9(lr(t.id),{force:!0})}var tp=/\.(example|sample|template|dist|defaults?)$/i;function np(e){let t=[];try{t=X9("git",["-C",e,"ls-files","--others","--directory","-z"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],maxBuffer:64*1024*1024}).split("\0")}catch{}return t.filter(n=>n&&!n.endsWith("/")&&/^\.env(\.|$)/.test(ep(n))&&!tp.test(n)).sort()}function lh(e){let t=np(e),n=new Set(hr(e)?.files??[]);return t.every(q=>n.has(q))?[]:t}function Mt(e){e=e.replace(/\s*\|\s*(?:head|tail)(?:\s+-n\s*\d+|\s+-\d+)?\s*$/,"");let t=[],n="",q=null;for(let s=0;s<e.length;s++){let o=e[s];if(q){if(o===q)q=null;else if(q==='"'&&/[$`\\]/.test(o))return!1;continue}if(o==="'"||o==='"'){q=o;continue}let i=(o==="&"||o==="|")&&e[s+1]===o;if(o===";"||o===`
|
|
3244
|
+
`||i){t.push(n),n="",i&&s++;continue}if(e.startsWith("2>&1",s)&&/\s/.test(e[s-1]??"")){s+=3;continue}if(/[&|<>`$()\\#]/.test(o))return!1;n+=o}if(q)return!1;let r=[...t,n].map(s=>s.trim()).filter(Boolean);return r.length>0&&r.every(s=>/^canary\s+jobs\s/.test(`${s} `))}var qp=new Set(["cat","head","tail","ls","wc","stat","grep"]),rp=new Set(["head","tail","wc","grep","uniq"]);function hh(e){let t=[],n=null,q=null;for(let r of e)if(q)if(r===q)q=null;else{if(q==='"'&&/[$`\\]/.test(r))return null;n+=r}else if(r==="'"||r==='"')q=r,n??="";else if(/\s/.test(r))n!==null&&t.push(n),n=null;else{if(/[;&|<>`$()\\#*?[\]{}~]/.test(r)&&!(r==="~"&&n===null))return null;n=(n??"")+r}return q?null:(n!==null&&t.push(n),t)}function ch(e,t){let n=e.replace(/\s2>\s?(?:\/dev\/null|&1)(?=\s|$)/g," ").split("|").map(hh);if(n.some(i=>!i||i.length===0))return!1;let q=i=>i.slice(1).filter(a=>!a.startsWith("-")&&!/^\d+$/.test(a)),[r,...s]=n,o=q(r).slice(r[0]==="grep"?1:0);return qp.has(r[0])&&o.length>0&&o.every(t)&&s.every(i=>rp.has(i[0])&&q(i).length<=(i[0]==="grep"?1:0))}var sp=new Set(["echo","printf","sleep","true",":"]);function dh(e){let t=e.split(/;|&&|\n/).map(n=>n.trim()).filter(Boolean).map(hh);return t.length>0&&t.every(n=>n!==null&&n.length>0&&sp.has(n[0]))}var Xl=(e,t)=>e.replace(/\s+/g," ").trim()===t.replace(/\s+/g," ").trim(),Ql=(e,...t)=>t.some(n=>n.label===e.trim());function uh(e,t){let n={commands:null,envFiles:null},q=!jt(t),r=lh(t);for(let s of[e.tool_response,e.tool_input]){let o=s?.answers;if(!(!o||typeof o!="object"))for(let[i,a]of Object.entries(o))typeof a=="string"&&(q&&Xl(i,eh)&&Ql(a,h0,th)?n.commands??=a:r.length&&Xl(i,qh(r))&&Ql(a,c0,nh)&&(n.envFiles??={files:r,answer:a}))}return n}var ar=e=>`${JSON.stringify(e.label)} (${e.description})`;function d0(e){let t=[];jt(e)||t.push(`header "Approvals": ${JSON.stringify(eh)} Options, in this order: ${ar(h0)} and ${ar(th)}`);let n=lh(e);return n.length&&t.push(`header "Env files": ${JSON.stringify(qh(n))} Options, in this order: ${ar(c0)} and ${ar(nh)}`),t.length===0?null:`Canary: before starting the checks, ask the user ${t.length>1?"these two questions in one dialog":"this once"} with the question tool (AskUserQuestion), word for word and with nothing added. ${t.join(" ")} Canary records each answer from the dialog itself: don't write it down anywhere, and don't ask again once it is recorded.`}function mh(e){let t=[],n=jt(e);n&&t.push(n.commands==="run"?`The checks' commands run without asking in this repository (the user's choice on ${n.at.slice(0,10)}). A command that would remove something the checks didn't create is stopped, and so is reading the user's keys and sign-ins; one that deletes data in a service they didn't start still asks the user.`:`The user chose on ${n.at.slice(0,10)} to approve the checks' commands themselves in this repository.`);let q=hr(e);return q&&t.push(q.use?`The checks may use this project's env files (the user's choice on ${q.at.slice(0,10)}), with their keys and hosted services as they are and what points at this machine replaced by the checks' own services: ${q.files.join(", ")}.`:`The user said on ${q.at.slice(0,10)} that the checks may not use this project's env files.`),t}var vh=500,ap=120,kh=256*1024,lp=3e4,hp=3e5,jn=e=>ur(B(),"records",`${he(e,"batch")}.jsonl`),p0=e=>ur(B(),"records",`${he(e,"batch")}.out`),zh=(e,t)=>ur(p0(e),/^[A-Za-z0-9_-]{1,96}$/.test(t)?t:wh("sha256").update(t).digest("hex").slice(0,32)),u0=e=>e.length>vh?`${e.slice(0,vh-1)}\u2026`:e;function cr(e,t){if(e.length<=t)return e;let n=Math.floor(t/4);return`${e.slice(0,n)}
|
|
3215
3245
|
[... ${e.length-t} characters of this output not shown ...]
|
|
3216
|
-
${e.slice(e.length-(t-n))}`}function
|
|
3217
|
-
`,{mode:384})}var
|
|
3246
|
+
${e.slice(e.length-(t-n))}`}function Mn(e,t){yh(bh(jn(e)),{recursive:!0,mode:448}),op(jn(e),JSON.stringify(t)+`
|
|
3247
|
+
`,{mode:384})}var Ln=()=>new Date().toISOString(),f0=e=>e.split(`
|
|
3218
3248
|
`).map(t=>t.trim()).find(t=>t&&!/^(source|\.|cd|set|export)\b/.test(t))??e.split(`
|
|
3219
|
-
`)[0],
|
|
3220
|
-
`))try{let a=JSON.parse(i);if(a.e==="asked")q.push(a);else if(a.e==="ended")for(let l of[a.call,a.same])l&&r.set(l,a.ended)}catch{}let s=q.slice(-t),o=q.filter(i=>i.bg).at(-1);return o&&!s.includes(o)&&s.unshift(o),s.map(i=>({at:i.at,step:
|
|
3221
|
-
`)[0]??"")}),
|
|
3222
|
-
`).filter(Boolean).flatMap(t=>{try{return[JSON.parse(t)]}catch{return[]}})}catch{return[]}}var
|
|
3223
|
-
`).find(n=>n.startsWith("n"))?.slice(1)??null}catch{return null}}}function
|
|
3224
|
-
`))q.startsWith("p")?n=Number(q.slice(1)):q.startsWith("n")&&n&&e.set(n,q.slice(1));return e}function kp(e,t){let n;try{n=mp(`/proc/${e}/environ`,"utf8").replace(/\0/g," ")}catch{try{n
|
|
3225
|
-
`).filter(Boolean))];a.length&&await
|
|
3226
|
-
`)[0]:String(a)}`)}return n}async function Ft(e,t={}){let n=[],q=[];for(let i of e.processes)await wp(i,e)||(q.push(i),n.push(`process ${i.pid} (${i.what}): it couldn't be confirmed as the one recorded, or didn't stop`));let r=await xp(e);n.push(...r.left);let s=e.left===void 0||e.dockerLeft===!0?await Sp(e.batchId,t.dockerTimeoutMs??6e4):[];n.push(...s),nr(e.batchId);let o=c1(e.batchId);for(let i of Cp(o).filter(a=>a!=="state.json"))try{
|
|
3227
|
-
`)[0]:String(a)}; it may hold files a container created as another user`)}return n.length?(
|
|
3228
|
-
`).map(a=>{let l=/^(\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=)(.*)$/.exec(a);return!l||!l[3].match(
|
|
3229
|
-
`);
|
|
3230
|
-
`),
|
|
3231
|
-
`);for(let r of
|
|
3249
|
+
`)[0],m0=e=>e.say||(e.kind==="file"?`wrote ${fh(bh(e.what))}/${fh(e.what)}`:f0(e.what));function xh(e,t){let n;try{n=dr(jn(e),"utf8")}catch{return[]}let q=[],r=new Map;for(let i of n.trimEnd().split(`
|
|
3250
|
+
`))try{let a=JSON.parse(i);if(a.e==="asked")q.push(a);else if(a.e==="ended")for(let l of[a.call,a.same])l&&r.set(l,a.ended)}catch{}let s=q.slice(-t),o=q.filter(i=>i.bg).at(-1);return o&&!s.includes(o)&&s.unshift(o),s.map(i=>({at:i.at,step:m0(i),command:i.kind==="command"?f0(i.what):null,ended:i.bg?"background":r.get(i.call)??r.get(i.same)??"running"}))}var cp=500,mr=3e4;function pr(e,t){let n=q=>q.slice(0,cp);return X().filter(q=>t.includes(q.batchId)&&q.sessionId===e&&q.claimed&&(!q.ended||q.setAside===!0)&&!x2(q.batchId)).map(q=>{let r=q.keptScripts??[],{fixing:s,done:o,now:i,commands:a}=dp(q.batchId,{copy:u1(q),scratch:c1(q.batchId),kept:r}),l=s?"fixing":r.length>0?"kept":"new";return{batchId:q.batchId,setup:l,ready:q.readyAt??null,done:o&&n(o),now:i&&n(i),commands:a.map(n),...q.setAside?{aside:!0}:{}}})}function dp(e,t){let n=Lt(e),q=new Map(n.flatMap(d=>d.e==="ended"?[d.call,d.same].filter(m=>m!==null).map(m=>[m,d.ended]):[])),r=d=>q.get(d.call)??q.get(d.same),s=n.filter(d=>d.e==="asked"),o=s.some(d=>d.kind==="file"?t.kept.some(m=>d.what===ur(t.copy,m)):r(d)==="failed"&&t.kept.some(m=>d.what.includes(m))),i=n.flatMap(d=>d.e==="output"?[d.path]:[]),a=s.filter(d=>!(d.kind==="command"&&(Mt(d.what)||dh(d.what)))&&!i.some(m=>d.what.includes(m))),l=a.at(-1),c=l!==void 0&&(l.bg===!0||r(l)===void 0),h=a.slice(0,c?-1:a.length).reverse().find(d=>d.bg===!0||r(d)==="ran");return{fixing:o,done:h?m0(h):null,now:c?m0(l):null,commands:a.filter(d=>d.kind==="command").slice(-2).map(d=>[t.copy,t.scratch].reduce((m,u)=>m.split(`${u}/`).join("").split(u).join("."),f0(d.what)))}}var Sh=e=>Lt(e).flatMap(t=>t.e==="asked"&&t.kind==="command"?[t.what]:[]),fr=(e,t,n,q,r="",s=!1)=>Mn(e,{at:Ln(),e:"asked",...t,kind:n,what:n==="command"?cr(q,kh):u0(q),...r?{say:u0(r)}:{},...s?{bg:!0}:{}}),z2=(e,t,n,q="")=>Mn(e,{at:Ln(),e:"ended",call:t.call??null,same:t.same??null,ended:n,detail:u0(q.split(`
|
|
3251
|
+
`)[0]??"")}),v0=(e,t,n,q)=>Mn(e,{at:Ln(),e:t,jobId:n,proof:q}),Ch=(e,t,n)=>Mn(e,{at:Ln(),e:"output",call:t,path:n}),g0=e=>wh("sha256").update(e).digest("hex");function Ah(e,t,n){try{let q=dr(n);Mn(e,{at:Ln(),e:"wrote",sha:g0(q)}),y0(e,t,q.toString("utf8"))}catch{}}function y0(e,t,n){n&&(yh(p0(e),{recursive:!0,mode:448}),ip(zh(e,t),cr(n,kh),{mode:384}))}function Ih(e){ph(jn(e),{force:!0}),ph(p0(e),{recursive:!0,force:!0})}function Rh(e){let t=new Set;for(let n of Lt(e))n.e==="asked"?t.add(n.call):n.e==="ended"&&n.call&&t.delete(n.call);return t}var x2=e=>Lt(e).some(t=>t.e==="start"),Th=e=>Lt(e).find(t=>t.e==="start")?.at??null;function Lt(e){try{return dr(jn(e),"utf8").split(`
|
|
3252
|
+
`).filter(Boolean).flatMap(t=>{try{return[JSON.parse(t)]}catch{return[]}})}catch{return[]}}var gh=e=>{try{return dr(e,"utf8")}catch{return""}};function Oh(e,t,n){let q=Lt(e),r=q.flatMap((h,d)=>h.e==="start"||h.e==="sent"?[{line:h,index:d}]:[]),s=r.filter(({line:h})=>h.e==="start"&&h.jobId===t&&h.proof===n).at(-1),o=s??r.at(-1),i=[];for(let h of q.slice(o?o.index+1:0))if(h.e==="asked")i.push({call:h.call,same:h.same,settled:!1,elsewhere:null,entry:{id:"",at:h.at,kind:h.kind,what:h.what,ended:"not_run",detail:"",output:""}});else if(h.e==="ended"){let d=i.find(m=>!m.settled&&(h.call?m.call===h.call:m.same===h.same));if(!d)continue;Object.assign(d.entry,{ended:h.ended,detail:h.detail}),d.settled=h.ended!=="not_run"}else if(h.e==="output"){let d=i.find(m=>m.call===h.call);d&&(d.elsewhere=h.path)}let a=i.slice(-ap),l=Math.max(2e3,Math.min(lp,Math.floor(hp/Math.max(1,a.length))));a.forEach((h,d)=>{h.entry.id=`${n?`p${n}`:""}c${d+1}`,h.entry.what=cr(h.entry.what,l),h.entry.ended!=="sent_back"&&(h.entry.output=cr(gh(zh(e,h.call))||(h.elsewhere?gh(h.elsewhere):""),l))});let c=r.find(({line:h})=>h.e==="start"&&h.jobId===t);return{calls:a.map(h=>h.entry),earlierCalls:i.length-a.length,minutes:o?Math.round((Date.now()-Date.parse(o.line.at))/6e3)/10:0,startedAt:s?Date.parse(s.line.at):null,jobStartedAt:c?Date.parse(c.line.at):null}}function Eh(e){let t=new Map,n=new Map,q=new Set;for(let r of Lt(e))r.e==="asked"&&r.kind==="file"?t.set(r.call,r.what):r.e==="ended"&&r.ended==="ran"&&r.call&&t.has(r.call)?n.set(t.get(r.call),Date.parse(r.at)):r.e==="wrote"&&q.add(r.sha);return{paths:n,contents:q}}var vp=fp(up),S2=e=>`canary.batch=${e}`,C2=e=>`canary-${e}`;function $h(e,t,n){try{let r=JSON.parse($n("docker",["inspect","--type",t,"--format",t==="container"||t==="image"?"{{json .Config.Labels}}":"{{json .Labels}}",n],{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","pipe"]}));return r?.["canary.batch"]===e||r?.["com.docker.compose.project"]===C2(e)}catch(q){return/no such/i.test(String(q.stderr??""))}}function Fn(e,t){try{return $n("ps",["-o",`${e}=`,"-p",String(t)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function gp(e){try{return Mh(`/proc/${e}/cwd`)}catch{try{return $n("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).split(`
|
|
3253
|
+
`).find(n=>n.startsWith("n"))?.slice(1)??null}catch{return null}}}function b0(e,t){if(e<=1||e===process.pid||e===Number(process.env.CLAUDE_PID))return!1;let n=[u1(t),c1(t.batchId)].flatMap(q=>{try{return[Lh(q)]}catch{return[]}});for(let q=e,r=0;q>1&&r<64;r++){let s=gp(q);if(s!==null&&n.some(o=>s===o||s.startsWith(o+Fh)))return!0;q=Number(Fn("ppid",q)??0)}return!1}function yp(e){return Number(Fn("pgid",e))===e}async function wp(e,t){if(e.pid<=1)return!1;let n=qt(e);return n!=="alive"?n==="gone":b0(e.pid,t)?Dh(e):!1}async function Dh(e){let t=yp(e.pid)?-e.pid:e.pid,n=q=>{try{process.kill(t,q)}catch{}};n("SIGTERM");for(let q=0;q<50&&qt(e)==="alive";q++)await new Promise(r=>setTimeout(r,100));return qt(e)==="alive"&&n("SIGKILL"),await new Promise(q=>setTimeout(q,200)),qt(e)==="gone"}function bp(){let e=new Map;try{for(let q of jh("/proc").filter(r=>/^\d+$/.test(r)))try{e.set(Number(q),Mh(`/proc/${q}/cwd`))}catch{}if(e.size)return e}catch{}let t="";try{t=$n("lsof",["-a","-d","cwd","-u",String(process.getuid?.()??""),"-Fpn"],{encoding:"utf8",timeout:15e3,maxBuffer:16*1024*1024,stdio:["ignore","pipe","ignore"]})}catch(q){t=String(q.stdout??"")}let n=0;for(let q of t.split(`
|
|
3254
|
+
`))q.startsWith("p")?n=Number(q.slice(1)):q.startsWith("n")&&n&&e.set(n,q.slice(1));return e}function kp(e,t){let n;try{n=mp(`/proc/${e}/environ`,"utf8").replace(/\0/g," ")}catch{try{n=$n("ps",["-wwE","-o","command=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]})}catch{return"unknown"}if(!/\s(PATH|HOME)=/.test(n))return"unknown"}return/(?:^|\s)CLAUDE_CODE_SESSION_ID=(\S+)/.exec(n)?.[1]===t?"session":"other"}function zp(e){let t=new Set;for(let n=e,q=0;n>1&&q<64;q++)t.add(n),n=Number(Fn("ppid",n)??0);return t}async function xp(e){let n=[c1(e.batchId),...pl(e.slot)===e.batchId?[u1(e)]:[]].flatMap(o=>{try{return[Lh(o)]}catch{return[]}}),q=zp(process.pid),r=[],s=[];for(let o=0;o<3&&n.length;o++){r=[],s=[];let i=0;for(let[a,l]of bp()){if(a<=1||q.has(a)||!n.some(u=>l===u||l.startsWith(u+Fh)))continue;let c=Oe(a);if(c===null)continue;let h=pp(Fn("comm",a)??"a process"),d=kp(a,e.sessionId),m=Fn("tty",a)??"?";d==="other"||d==="unknown"&&!m.startsWith("?")?s.push(`process ${a} (${h}) runs from this batch's folders, but its session didn't start it, so it was left running`):await Dh({pid:a,startedAt:c})?i++:r.push(`process ${a} (${h}): it didn't stop`)}if(i===0)break}return{left:r,others:s}}async function w0(e,t){let{stdout:n}=await vp("docker",e,{timeout:t});return n.trim()}async function Sp(e,t){let n=[],q=[`label=${S2(e)}`,`label=com.docker.compose.project=${C2(e)}`];try{await w0(["version","--format","{{.Server.Version}}"],t)}catch(s){return s.code==="ENOENT"?n:[`Docker didn't answer, so containers labelled ${S2(e)} couldn't be checked`]}let r=[[["ps","-aq"],["rm","-f","-v"]],[["volume","ls","-q"],["volume","rm","-f"]],[["network","ls","-q"],["network","rm"]],[["image","ls","-q"],["image","rm","-f"]]];for(let[s,o]of r)for(let i of q)try{let a=[...new Set((await w0([...s,"--filter",i],t)).split(`
|
|
3255
|
+
`).filter(Boolean))];a.length&&await w0([...o,...a],t)}catch(a){n.push(`Docker ${s[0]==="ps"?"containers":s[0]+"s"} labelled ${i.slice(6)}: ${a instanceof Error?a.message.split(`
|
|
3256
|
+
`)[0]:String(a)}`)}return n}async function Ft(e,t={}){let n=[],q=[];for(let i of e.processes)await wp(i,e)||(q.push(i),n.push(`process ${i.pid} (${i.what}): it couldn't be confirmed as the one recorded, or didn't stop`));let r=await xp(e);n.push(...r.left);let s=e.left===void 0||e.dockerLeft===!0?await Sp(e.batchId,t.dockerTimeoutMs??6e4):[];n.push(...s),nr(e.batchId);let o=c1(e.batchId);for(let i of Cp(o).filter(a=>a!=="state.json"))try{Nh(Ph(o,i),{recursive:!0,force:!0})}catch(a){n.push(`${Ph(o,i)}: ${a instanceof Error?a.message.split(`
|
|
3257
|
+
`)[0]:String(a)}; it may hold files a container created as another user`)}return n.length?(Cn({...e,processes:q,left:n,dockerLeft:s.length>0}),[...n,...r.others]):(Nh(o,{recursive:!0,force:!0}),Ih(e.batchId),r.others)}function Cp(e){try{return jh(e)}catch{return[]}}async function Wh(e){let t=[];for(let n of X().filter(q=>q.left)){let q=e?await Ft(n,{dockerTimeoutMs:5e3}).catch(()=>n.left):n.left;t.push(...q.map(r=>`batch ${n.batchId}: ${r}`))}return t}g();import{execFile as Ap}from"node:child_process";import{createHash as Ip}from"node:crypto";import{appendFileSync as Gh,copyFileSync as Rp,createReadStream as Tp,existsSync as z0,lstatSync as Vh,mkdirSync as x0,mkdtempSync as Op,readFileSync as Ep,rmSync as k0,statSync as Hh,writeFileSync as Jh}from"node:fs";import{tmpdir as Np}from"node:os";import{basename as Pp,dirname as Yh,isAbsolute as Kh,join as B1,relative as jp}from"node:path";import{promisify as Mp}from"node:util";var S0=Mp(Ap),Bh=1024*1024,_h=1024*1024,Lp=".canary-cache",Dn="refs/canary/head",Xh=["core.hooksPath=/dev/null","core.attributesFile=/dev/null","core.autocrlf=false","core.safecrlf=false","core.fsmonitor=false","core.symlinks=true","core.protectHFS=true","core.protectNTFS=true","gc.auto=0","maintenance.auto=false","protocol.allow=never","commit.gpgsign=false"];function Qh(e={}){return{...Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_"))),GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_ATTR_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0",...e}}async function w1(e,t,n){let{stdout:q}=await S0("git",[...Xh.flatMap(r=>["-c",r]),"-C",e,...t],{env:Qh(n),maxBuffer:67108864});return q}async function Fp(e){let t=Ip("sha256"),n=0;for await(let q of Tp(e))t.update(q),n+=q.length;return{hash:t.digest("hex"),bytes:n}}async function $p(e,t){let n=async s=>{try{return(await S0("git",["-C",e,...s],{env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}})).stdout.trim()}catch{return""}},q=await n(["rev-parse","--path-format=absolute","--git-path","info/exclude"]);q&&z0(q)&&Rp(q,B1(t,".git","info","exclude"));let r=await n(["config","--path","--get","core.excludesFile"]);r&&await w1(t,["config","--local","core.excludesFile",r])}async function Dp(e,t,n,q,r){await t5(t,n,q),await S0("git",["init","--quiet","--template=",r],{env:Qh()}),await n5(e,t,n,r),await w1(r,["checkout","--quiet","-B","canary-copy",n.headSha]),await q5(r,q)}async function Zh(e,t,n,q,r){if(await t5(t,n,q),z0(B1(r,".git")))try{await n5(e,t,n,r),await w1(r,["checkout","--quiet","--force","-B","canary-copy",n.headSha]),await w1(r,["clean","--quiet","--force","-d"]);let s=(await w1(r,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"])).split("\0");for(let o of s.filter(i=>i&&!i.endsWith("/")&&Pp(i).startsWith(".env")))k0(B1(r,o),{force:!0});return await q5(r,q),!0}catch{}return k0(r,{recursive:!0,force:!0}),x0(Yh(r),{recursive:!0,mode:448}),await Dp(e,t,n,q,r),!1}var C0="canary-unset.invalid",Uh=/(?<![\w.-])(?:(?:[\w-]+\.)*localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\]|host\.docker\.internal)(?![\w.-])|(?<![\w:.])::1(?![\w:.])/gi;function e5(e,t,n){let q=[];for(let r of n)if(!(Kh(r)||r.split("/").includes("..")))try{let s=B1(e,r);if(!Hh(s).isFile())continue;if(z0(B1(t,r))){q.push({file:r,repointed:[]});continue}let o=[],i=Ep(s,"utf8").split(`
|
|
3258
|
+
`).map(a=>{let l=/^(\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=)(.*)$/.exec(a);return!l||!l[3].match(Uh)?a:(o.push(l[2]),l[1]+l[3].replace(Uh,C0))}).join(`
|
|
3259
|
+
`);x0(Yh(B1(t,r)),{recursive:!0}),Gh(B1(t,".git","info","exclude"),`/${r}
|
|
3260
|
+
`),Jh(B1(t,r),i,{mode:Hh(s).mode&511}),q.push({file:r,repointed:o})}catch{}return q}async function t5(e,t,n){if(t.treeHash!==n)throw new Error("the kept snapshot isn't the code Canary planned these checks on");let{hash:q,bytes:r}=await Fp(e);if(q!==t.sha256||r!==t.bytes)throw new Error("the kept snapshot doesn't match its receipt")}async function n5(e,t,n,q){await w1(q,["bundle","unbundle",t]),await w1(q,["update-ref","refs/canary/base",n.baseSha]),await w1(q,["update-ref",Dn,n.headSha]),x0(B1(q,".git","info"),{recursive:!0}),Jh(B1(q,".git","info","attributes"),`* -text -eol -ident -filter -working-tree-encoding
|
|
3261
|
+
`);for(let r of Xh){let s=r.indexOf("=");await w1(q,["config","--local",r.slice(0,s),r.slice(s+1)])}await $p(e,q),Gh(B1(q,".git","info","exclude"),`
|
|
3232
3262
|
/${Lp}/
|
|
3233
|
-
`)}async function
|
|
3263
|
+
`)}async function q5(e,t){let n=(await w1(e,["rev-parse","HEAD^{tree}"])).trim(),q=await w1(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(n!==t||q.length>0)throw new Error("the copy doesn't match the snapshot after checkout")}async function r5(e,t){let n=[];for(let q of new Set(t)){let r=jp(e,q);if(!(!r||r.startsWith("..")||Kh(r)))try{await w1(e,["cat-file","-e",`${Dn}:${r}`]),await w1(e,["diff","--quiet",Dn,"--",r]),n.push(r)}catch{}}return n}async function s5(e,t){try{let n=(await w1(e,["ls-tree","-r","-l","--full-tree","-z",t])).split("\0").flatMap(r=>{let s=/^\S+ blob \S+ +(\d+)\t(.+)$/s.exec(r);return s?[{bytes:Number(s[1]),path:s[2]}]:[]}),q=r=>{try{return Vh(B1(e,r)).size}catch{return 0}};return{bytes:n.reduce((r,s)=>r+s.bytes,0),onDisk:n.reduce((r,s)=>r+Math.min(q(s.path),s.bytes),0)}}catch{return null}}async function o5(e){return(await w1(e,["ls-files","--stage","-z"])).split("\0").filter(t=>t.startsWith("160000 ")).map(t=>({commit:t.split(" ")[1],path:t.slice(t.indexOf(" ")+1)}))}async function i5(e){let t=Op(B1(Np(),"canary-diff-"));try{let n={GIT_INDEX_FILE:B1(t,"index")};await w1(e,["read-tree",Dn],n),await w1(e,["add","--update","--","."],n);let q=(await w1(e,["ls-files","--others","--exclude-standard","-z"],n)).split("\0").filter(Boolean),r=[],s=q.filter(l=>{let c=Vh(B1(e,l));return c.isFile()&&c.size>_h&&r.push(`[new file ${l}, ${c.size} bytes, not included]`),!(c.isFile()&&c.size>_h)});for(let l=0;l<s.length;l+=200)await w1(e,["add","--",...s.slice(l,l+200)],n);let o=l=>w1(e,["diff","--cached","--no-color","--no-ext-diff","--no-textconv","-U0",`--diff-filter=${l}`,Dn],n),i=await o("a")+await o("A");return Buffer.byteLength(i)>Bh&&(i=`${Buffer.from(i).subarray(0,Bh).toString("utf8")}
|
|
3234
3264
|
[diff cut at 1 MB]
|
|
3235
3265
|
`),[i,...r].filter(Boolean).join(`
|
|
3236
|
-
`)||null}finally{b0(t,{recursive:!0,force:!0})}}g();import{createHash as tf}from"node:crypto";import{existsSync as nf,lstatSync as qf,readFileSync as A0,realpathSync as R0,statSync as rf}from"node:fs";import{extname as c5,join as We,sep as sf}from"node:path";g();import{execFileSync as Wp}from"node:child_process";import{readFileSync as o5}from"node:fs";import{basename as Hp,join as Bp}from"node:path";var _p=/(^|[_.-])(KEY|SECRET|TOKEN|PASS|PASSWORD|PASSWD|PWD|CREDENTIALS?|SALT|DSN)($|[_.-])/i,Up=8,l5=/^[a-z]+$/;function i5(e){let t=[];for(let n of e.split(/\r?\n/)){let q=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/.exec(n);if(!q)continue;let r=q[2].trim(),s=/^(["'])(.*?)\1\s*(?:#.*)?$/.exec(r);t.push([q[1],s?s[2]:r.replace(/\s+#.*$/,"")])}return t}function Gp(e){return/^[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:([^@\s]+)@/i.exec(e)?.[1]??null}function C0(e){let t=new Map,n=(r,s)=>{s.length>=Up&&!t.has(s)&&t.set(s,r)};try{let r=$1(e);if(r)for(let[s,o]of i5(o5(H1(r).secrets,"utf8")))n(s,o)}catch{}let q=[];try{q=Wp("git",["-C",e,"ls-files","--others","--directory","-z"],{encoding:"utf8",maxBuffer:64*1024*1024}).split("\0")}catch{}for(let r of q.filter(s=>s&&!s.endsWith("/")&&Hp(s).startsWith(".env"))){let s;try{s=o5(Bp(e,r),"utf8")}catch{continue}for(let[o,i]of i5(s)){let a=Gp(i);for(let l of[_p.test(o)?i:null,a])l&&!l5.test(l)&&n(o,l)}}return[...t].map(([r,s])=>({name:s,value:r}))}var Vp=[/\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}/g,/\bAKIA[0-9A-Z]{16}\b/g,/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g],Jp=/\b(?:cnry_|gh[pousr]_|github_pat_|glpat-|npm_|whsec_|xox[abprs]-|sk-(?:ant-)?|[sr]k_(?:live|test)_)[\w+/=-]{16,}/g,Yp=/(["']?)\b([A-Za-z_][\w.-]*)\1(\s*(?::|=(?!=))\s*["']?)([^\s"',;&}<>]{8,})/g,Kp=/(secret|token|passw(or)?d|credentials?|(api|private|access|secret|signing|encryption)[_.-]?key)$/i,a5=e=>/^[A-Za-z_]\w*(?:\??\.[A-Za-z_]\w*)*$/.test(e)&&/(secret|token|key|pass(w(or)?d)?|pwd?|credentials?)$/i.test(e),Xp=/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|token)\s+)?)([\w.~+/=-]{8,})/gi,Qp=/(\b(?:set-)?cookie["']?\s*[:=]\s*["']?)([^\r\n"']+)/gi,Zp=/(\b[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:)([^@\s/]{8,})(?=@)/gi,ef=/([?&](?:code|state|ticket|nonce|token|access_token|id_token|code_challenge|code_verifier|challenge|signature)=)([\w.~+/-]{16,}={0,2})/gi,C2="values that look like tokens or keys";function h5(e){let t=[...e].sort((q,r)=>r.value.length-q.value.length),n=new Map;return q=>{let r=new Set;for(let{name:o,value:i}of t)q.includes(i)&&(q=q.split(i).join(`<${o}>`),r.add(o));let s=o=>o.startsWith("<")||l5.test(o)?o:(n.has(o)||n.set(o,n.size+1),r.add(C2),`<hidden-${n.get(o)}>`);for(let o of Vp)q=q.replace(o,s);q=q.replace(Jp,o=>/\d/.test(o)?s(o):o),q=q.replace(Xp,(o,i,a)=>i+(a5(a)?a:s(a))),q=q.replace(Qp,(o,i,a)=>i+a.replace(/=([^;\s]{16,})/g,(l,c)=>`=${s(c)}`)),q=q.replace(Zp,(o,i,a)=>i+s(a)),q=q.replace(ef,(o,i,a)=>i+s(a)),q=q.replace(Yp,(o,i,a,l,c)=>Kp.test(a)&&!/[$(){}[\]]/.test(c)&&(/["']$/.test(l)||!a5(c))?o.slice(0,o.length-c.length)+s(c):o);for(let[o,i]of[...n].sort(([a],[l])=>l.length-a.length))q.includes(o)&&(q=q.split(o).join(`<hidden-${i}>`),r.add(C2));return{text:q,hidden:[...r]}}}var d5=32*1024*1024,of=256*1024*1024,Dn=e=>(t,n,q)=>{(typeof t!="string"||t.trim().length<e)&&q.push(`${n} must be ${e?"non-empty ":""}text`)},af=(e,t,n)=>{(!Number.isInteger(e)||e<0)&&n.push(`${t} must be a whole number`)},lt=(...e)=>(t,n,q)=>{e.includes(t)||q.push(`${n} must be one of ${e.join(", ")}`)},T0=e=>(t,n,q)=>{t!==null&&e(t,n,q)},re=(e,t=0)=>(n,q,r)=>{if(!Array.isArray(n))return void r.push(`${q} must be a list`);n.length<t&&r.push(`${q} needs at least ${t} item`);for(let s=0;s<n.length;s++)e(n[s],`${q}[${s}]`,r)},ce=e=>(t,n,q)=>{if(!t||typeof t!="object"||Array.isArray(t))return void q.push(`${n||"the file"} must be an object`);for(let[r,s]of Object.entries(e))r in t?s(t[r],n?`${n}.${r}`:r,q):q.push(`${n?`${n}.`:""}${r} is missing`)},t1=Dn(1),lf=ce({steps:re(t1,1),files:re(t1),observe:t1}),hf=ce({id:t1,kind:lt("command","request","ui_action","test","other"),action:t1,output:Dn(0),files:re(t1)}),cf=ce({path:t1,mediaType:t1,bytes:af,caption:Dn(0),frames:re(t1)}),df=ce({name:t1,kind:t1,class:lt("local","staging","production"),access:lt("read","write"),whyAllowed:t1}),uf=ce({part:t1,by:t1,version:t1,cannotShow:t1}),mf=ce({asked:t1,answer:lt("granted","declined","unavailable"),source:lt("asked_this_run","canary_md")}),pf=ce({by:lt("normal_use","put_in_place"),how:t1}),p5={steps:re(hf),files:re(cf),targets:re(df),standIns:re(uf),permissions:re(mf),diff:T0(Dn(0)),reproduction:T0(lf)},ff=ce({jobId:t1,claim:ce({verdict:lt("broken","held","not_reproduced","cannot_run"),summary:t1,stepIds:re(t1)}),ranOn:ce({where:lt("canary_computer","user_machine"),by:t1,environment:t1,commit:t1,target:Dn(0),services:re(t1)}),...p5,couldNotRun:T0(ce({tried:re(t1),proved:re(t1),missing:t1,whoCouldNotProvide:t1}))}),vf=ce({jobId:t1,answer:t1,...p5});function gf(e,t){let n=[];if((t==="pack"?ff:vf)(e,"",n),t==="pack"&&n.length===0){let q=e;q.claim.verdict==="cannot_run"!=(q.couldNotRun!==null)&&n.push("couldNotRun is set exactly when the claim is cannot_run"),q.claim.startingState!=null&&pf(q.claim.startingState,"claim.startingState",n)}return n}var u5={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".mp4":"video/mp4",".webm":"video/webm",".json":"application/json",".txt":"text/plain",".log":"text/plain",".md":"text/markdown",".html":"text/html",".har":"application/json",".zip":"application/zip",".sh":"text/x-shellscript"},m5=e=>e.subarray(0,8e3).includes(0),yf=new Set(["path","id","jobId","commit","mediaType","verdict","kind","class","access","source","where"]);function f5(e,t,n,q,r){let s=t==="pack"?"pack.json":"delta.json",o;try{o=JSON.parse(A0(We(e,s),"utf8"))}catch(v){throw new E("no_pack",`Can't read ${We(e,s)}: ${v instanceof Error?v.message:String(v)}`,"Write it first; canary jobs schema shows its format.")}if(!o||typeof o!="object"||Array.isArray(o))throw new E("invalid_pack",`${s} must hold one JSON object.`);o.jobId=n.jobId,o.diff=n.diff,o.observed=null,t==="pack"&&o.ranOn&&typeof o.ranOn=="object"&&Object.assign(o.ranOn,{where:"user_machine",commit:n.commit,tree:n.tree,uncommitted:n.uncommitted,warmCopy:n.warmCopy});for(let v of Array.isArray(o.files)?o.files:[])v&&typeof v=="object"&&typeof v.path=="string"&&(v.bytes=Pt.test(v.path)&&I0(e,v.path)||0),v&&typeof v=="object"&&(v.frames??=[]);for(let v of Array.isArray(o.steps)?o.steps:[])v&&typeof v=="object"&&(v.files??=[],v.output??="");let i=gf(o,t);if(i.length)throw new E("invalid_pack",`${s} doesn't fit the evidence format: ${i.slice(0,8).join("; ")}`,"Fix it and submit again; canary jobs schema shows the format.");let a=o,l=new Set;for(let v of a.files)[v.path,...v.frames].forEach(w=>l.add(w));for(let v of[...a.steps.flatMap(w=>w.files),...a.reproduction?.files??[],...n.scripts])l.has(v)||(l.add(v),Pt.test(v)&&a.files.push({path:v,mediaType:u5[c5(v).toLowerCase()]??"application/octet-stream",bytes:I0(e,v)??0,caption:"",frames:[]}));if("claim"in a){let v=new Set(a.steps.map(w=>w.id));for(let w of a.claim.stepIds)v.has(w)||i.push(`the claim cites step ${w}, which isn't in the pack`)}"claim"in a&&a.claim.verdict!=="cannot_run"&&!n.stopped&&!a.claim.startingState&&i.push(`claim.startingState is missing: say how the scenario's starting state came about in your run, as { "by": "normal_use" or "put_in_place", "how": "\u2026" }`);let c=new Set(a.files.map(v=>v.path));for(let v of a.files)for(let w of v.frames)c.has(w)||i.push(`frame ${w} of ${v.path} needs its own entry in files`);for(let v of l)!Pt.test(v)||v===s?i.push(`${v} isn't a usable evidence path (plain folder and file names, no leading dot)`):I0(e,v)===null&&i.push(`${v} isn't a file inside ${e} (links that lead out of it don't count)`);if(i.length)throw new E("invalid_pack",`The evidence doesn't hold together: ${i.slice(0,8).join("; ")}`);let h=[...l].sort().map(v=>{let w=A0(We(e,v)),P=rf(We(e,v)).mtimeMs,V=n.scripts.includes(v)?We(n.scriptsFrom,v.slice(v.indexOf("/")+1)):null,o1=n.byHand.paths.get(R0(V&&nf(V)?V:We(e,v)))!==void 0||n.byHand.contents.has(v0(w))?"hand":n.startedAt&&P<n.startedAt-2e3?"before":"run";return{path:v,by:o1,text:!m5(w)}});a.observed={...n.observed,files:h};let d=n.observed.calls.some(v=>v.kind==="command"&&v.output.trim()!=="")||h.some(v=>v.by==="run"&&!v.text);if("claim"in a&&a.claim.verdict!=="cannot_run"&&!n.stopped&&!d)throw new E("nothing_captured","Canary captured no output of any command for this job, and no screenshot, recording or trace a command produced, so nothing stands behind this claim.","Run the scenario, so what it prints is captured, and submit again. If it can't run, send it as cannot_run and say what stopped you: that is a fine result.");let m=new Map(a.files.map(v=>[v.path,v.mediaType])),u=[],p=h5(r),f=(v,w)=>{let P=p(w);for(let V of P.hidden)u.push({name:V,path:v});return P.text},k=[...l].sort().map(v=>{let w=A0(We(e,v));return{path:v,data:w,text:w.length>d5||m5(w)?null:w.toString("utf8")}}),x=new Set(a.steps.map(v=>v.id)),y=v=>JSON.parse(JSON.stringify(a),(w,P)=>typeof P!="string"||yf.has(w)||l.has(P)||x.has(P)?P:v(P));for(let v of k)v.text!==null&&p(v.text);y(v=>p(v).text);let b=new Map;for(let{path:v,data:w,text:P}of k){let V=P===null?P:f(v,P);b.set(v,V===null||V===P?w:Buffer.from(V))}let z=y(v=>f(s,v));for(let v of z.files)v.bytes=b.get(v.path)?.length??v.bytes;let C=new Map([[s,Buffer.from(JSON.stringify(z,null,2))],...b]),I=[...C].map(([v,w])=>({path:v,mediaType:v===s?"application/json":m.get(v)??u5[c5(v).toLowerCase()]??"application/octet-stream",bytes:w.length,sha256:tf("sha256").update(w).digest("hex")})),S=I.filter(v=>v.bytes>d5).map(v=>v.path);if(S.length)throw new E("too_large",`Over 32 MB: ${S.join(", ")}.`,"Leave out what the scenario doesn't need, or trim long recordings.");if(I.reduce((v,w)=>v+w.bytes,0)>of)throw new E("too_large","The evidence is over 256 MB in total.","Leave out what the scenario doesn't need, or trim long recordings.");return{pack:z,upload:{kind:t,proofRequestId:q,files:I},bytes:C,hidden:u}}function I0(e,t){try{let n=R0(e);if(!R0(We(e,t)).startsWith(n+sf))return null;let r=qf(We(e,t));return r.isFile()?r.size:null}catch{return null}}var v5=`Evidence for one job: packs/<job>/pack.json in the batch folder, with any file it names beside it
|
|
3266
|
+
`)||null}finally{k0(t,{recursive:!0,force:!0})}}g();import{createHash as tf}from"node:crypto";import{existsSync as nf,lstatSync as qf,readFileSync as I0,realpathSync as T0,statSync as rf}from"node:fs";import{extname as u5,join as We,sep as sf}from"node:path";g();import{execFileSync as Wp}from"node:child_process";import{readFileSync as a5}from"node:fs";import{basename as Hp,join as Bp}from"node:path";var _p=/(^|[_.-])(KEY|SECRET|TOKEN|PASS|PASSWORD|PASSWD|PWD|CREDENTIALS?|SALT|DSN)($|[_.-])/i,Up=8,c5=/^[a-z]+$/;function l5(e){let t=[];for(let n of e.split(/\r?\n/)){let q=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/.exec(n);if(!q)continue;let r=q[2].trim(),s=/^(["'])(.*?)\1\s*(?:#.*)?$/.exec(r);t.push([q[1],s?s[2]:r.replace(/\s+#.*$/,"")])}return t}function Gp(e){return/^[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:([^@\s]+)@/i.exec(e)?.[1]??null}function A0(e){let t=new Map,n=(r,s)=>{s.length>=Up&&!t.has(s)&&t.set(s,r)};try{let r=$1(e);if(r)for(let[s,o]of l5(a5(H1(r).secrets,"utf8")))n(s,o)}catch{}let q=[];try{q=Wp("git",["-C",e,"ls-files","--others","--directory","-z"],{encoding:"utf8",maxBuffer:64*1024*1024}).split("\0")}catch{}for(let r of q.filter(s=>s&&!s.endsWith("/")&&Hp(s).startsWith(".env"))){let s;try{s=a5(Bp(e,r),"utf8")}catch{continue}for(let[o,i]of l5(s)){let a=Gp(i);for(let l of[_p.test(o)?i:null,a])l&&!c5.test(l)&&n(o,l)}}return[...t].map(([r,s])=>({name:s,value:r}))}var Vp=[/\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}/g,/\bAKIA[0-9A-Z]{16}\b/g,/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g],Jp=/\b(?:cnry_|gh[pousr]_|github_pat_|glpat-|npm_|whsec_|xox[abprs]-|sk-(?:ant-)?|[sr]k_(?:live|test)_)[\w+/=-]{16,}/g,Yp=/(["']?)\b([A-Za-z_][\w.-]*)\1(\s*(?::|=(?!=))\s*["']?)([^\s"',;&}<>]{8,})/g,Kp=/(secret|token|passw(or)?d|credentials?|(api|private|access|secret|signing|encryption)[_.-]?key)$/i,h5=e=>/^[A-Za-z_]\w*(?:\??\.[A-Za-z_]\w*)*$/.test(e)&&/(secret|token|key|pass(w(or)?d)?|pwd?|credentials?)$/i.test(e),Xp=/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|token)\s+)?)([\w.~+/=-]{8,})/gi,Qp=/(\b(?:set-)?cookie["']?\s*[:=]\s*["']?)([^\r\n"']+)/gi,Zp=/(\b[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:)([^@\s/]{8,})(?=@)/gi,ef=/([?&](?:code|state|ticket|nonce|token|access_token|id_token|code_challenge|code_verifier|challenge|signature)=)([\w.~+/-]{16,}={0,2})/gi,A2="values that look like tokens or keys";function d5(e){let t=[...e].sort((q,r)=>r.value.length-q.value.length),n=new Map;return q=>{let r=new Set;for(let{name:o,value:i}of t)q.includes(i)&&(q=q.split(i).join(`<${o}>`),r.add(o));let s=o=>o.startsWith("<")||c5.test(o)?o:(n.has(o)||n.set(o,n.size+1),r.add(A2),`<hidden-${n.get(o)}>`);for(let o of Vp)q=q.replace(o,s);q=q.replace(Jp,o=>/\d/.test(o)?s(o):o),q=q.replace(Xp,(o,i,a)=>i+(h5(a)?a:s(a))),q=q.replace(Qp,(o,i,a)=>i+a.replace(/=([^;\s]{16,})/g,(l,c)=>`=${s(c)}`)),q=q.replace(Zp,(o,i,a)=>i+s(a)),q=q.replace(ef,(o,i,a)=>i+s(a)),q=q.replace(Yp,(o,i,a,l,c)=>Kp.test(a)&&!/[$(){}[\]]/.test(c)&&(/["']$/.test(l)||!h5(c))?o.slice(0,o.length-c.length)+s(c):o);for(let[o,i]of[...n].sort(([a],[l])=>l.length-a.length))q.includes(o)&&(q=q.split(o).join(`<hidden-${i}>`),r.add(A2));return{text:q,hidden:[...r]}}}var m5=32*1024*1024,of=256*1024*1024,Wn=e=>(t,n,q)=>{(typeof t!="string"||t.trim().length<e)&&q.push(`${n} must be ${e?"non-empty ":""}text`)},af=(e,t,n)=>{(!Number.isInteger(e)||e<0)&&n.push(`${t} must be a whole number`)},lt=(...e)=>(t,n,q)=>{e.includes(t)||q.push(`${n} must be one of ${e.join(", ")}`)},O0=e=>(t,n,q)=>{t!==null&&e(t,n,q)},re=(e,t=0)=>(n,q,r)=>{if(!Array.isArray(n))return void r.push(`${q} must be a list`);n.length<t&&r.push(`${q} needs at least ${t} item`);for(let s=0;s<n.length;s++)e(n[s],`${q}[${s}]`,r)},ce=e=>(t,n,q)=>{if(!t||typeof t!="object"||Array.isArray(t))return void q.push(`${n||"the file"} must be an object`);for(let[r,s]of Object.entries(e))r in t?s(t[r],n?`${n}.${r}`:r,q):q.push(`${n?`${n}.`:""}${r} is missing`)},t1=Wn(1),lf=ce({steps:re(t1,1),files:re(t1),observe:t1}),hf=ce({id:t1,kind:lt("command","request","ui_action","test","other"),action:t1,output:Wn(0),files:re(t1)}),cf=ce({path:t1,mediaType:t1,bytes:af,caption:Wn(0),frames:re(t1)}),df=ce({name:t1,kind:t1,class:lt("local","staging","production"),access:lt("read","write"),whyAllowed:t1}),uf=ce({part:t1,by:t1,version:t1,cannotShow:t1}),mf=ce({asked:t1,answer:lt("granted","declined","unavailable"),source:lt("asked_this_run","canary_md")}),pf=ce({by:lt("normal_use","put_in_place"),how:t1}),v5={steps:re(hf),files:re(cf),targets:re(df),standIns:re(uf),permissions:re(mf),diff:O0(Wn(0)),reproduction:O0(lf)},ff=ce({jobId:t1,claim:ce({verdict:lt("broken","held","not_reproduced","cannot_run"),summary:t1,stepIds:re(t1)}),ranOn:ce({where:lt("canary_computer","user_machine"),by:t1,environment:t1,commit:t1,target:Wn(0),services:re(t1)}),...v5,couldNotRun:O0(ce({tried:re(t1),proved:re(t1),missing:t1,whoCouldNotProvide:t1}))}),vf=ce({jobId:t1,answer:t1,...v5});function gf(e,t){let n=[];if((t==="pack"?ff:vf)(e,"",n),t==="pack"&&n.length===0){let q=e;q.claim.verdict==="cannot_run"!=(q.couldNotRun!==null)&&n.push("couldNotRun is set exactly when the claim is cannot_run"),q.claim.startingState!=null&&pf(q.claim.startingState,"claim.startingState",n)}return n}var p5={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".mp4":"video/mp4",".webm":"video/webm",".json":"application/json",".txt":"text/plain",".log":"text/plain",".md":"text/markdown",".html":"text/html",".har":"application/json",".zip":"application/zip",".sh":"text/x-shellscript"},f5=e=>e.subarray(0,8e3).includes(0),yf=new Set(["path","id","jobId","commit","mediaType","verdict","kind","class","access","source","where"]);function g5(e,t,n,q,r){let s=t==="pack"?"pack.json":"delta.json",o;try{o=JSON.parse(I0(We(e,s),"utf8"))}catch(v){throw new E("no_pack",`Can't read ${We(e,s)}: ${v instanceof Error?v.message:String(v)}`,"Write it first; canary jobs schema shows its format.")}if(!o||typeof o!="object"||Array.isArray(o))throw new E("invalid_pack",`${s} must hold one JSON object.`);o.jobId=n.jobId,o.diff=n.diff,o.observed=null,t==="pack"&&o.ranOn&&typeof o.ranOn=="object"&&Object.assign(o.ranOn,{where:"user_machine",commit:n.commit,tree:n.tree,uncommitted:n.uncommitted,warmCopy:n.warmCopy});for(let v of Array.isArray(o.files)?o.files:[])v&&typeof v=="object"&&typeof v.path=="string"&&(v.bytes=Pt.test(v.path)&&R0(e,v.path)||0),v&&typeof v=="object"&&(v.frames??=[]);for(let v of Array.isArray(o.steps)?o.steps:[])v&&typeof v=="object"&&(v.files??=[],v.output??="");let i=gf(o,t);if(i.length)throw new E("invalid_pack",`${s} doesn't fit the evidence format: ${i.slice(0,8).join("; ")}`,"Fix it and submit again; canary jobs schema shows the format.");let a=o,l=new Set;for(let v of a.files)[v.path,...v.frames].forEach(w=>l.add(w));for(let v of[...a.steps.flatMap(w=>w.files),...a.reproduction?.files??[],...n.scripts])l.has(v)||(l.add(v),Pt.test(v)&&a.files.push({path:v,mediaType:p5[u5(v).toLowerCase()]??"application/octet-stream",bytes:R0(e,v)??0,caption:"",frames:[]}));if("claim"in a){let v=new Set(a.steps.map(w=>w.id));for(let w of a.claim.stepIds)v.has(w)||i.push(`the claim cites step ${w}, which isn't in the pack`)}"claim"in a&&a.claim.verdict!=="cannot_run"&&!n.stopped&&!a.claim.startingState&&i.push(`claim.startingState is missing: say how the scenario's starting state came about in your run, as { "by": "normal_use" or "put_in_place", "how": "\u2026" }`);let c=new Set(a.files.map(v=>v.path));for(let v of a.files)for(let w of v.frames)c.has(w)||i.push(`frame ${w} of ${v.path} needs its own entry in files`);for(let v of l)!Pt.test(v)||v===s?i.push(`${v} isn't a usable evidence path (plain folder and file names, no leading dot)`):R0(e,v)===null&&i.push(`${v} isn't a file inside ${e} (links that lead out of it don't count)`);if(i.length)throw new E("invalid_pack",`The evidence doesn't hold together: ${i.slice(0,8).join("; ")}`);let h=[...l].sort().map(v=>{let w=I0(We(e,v)),P=rf(We(e,v)).mtimeMs,V=n.scripts.includes(v)?We(n.scriptsFrom,v.slice(v.indexOf("/")+1)):null,o1=n.byHand.paths.get(T0(V&&nf(V)?V:We(e,v)))!==void 0||n.byHand.contents.has(g0(w))?"hand":n.startedAt&&P<n.startedAt-2e3?"before":"run";return{path:v,by:o1,text:!f5(w)}});a.observed={...n.observed,files:h};let d=n.observed.calls.some(v=>v.kind==="command"&&v.output.trim()!=="")||h.some(v=>v.by==="run"&&!v.text);if("claim"in a&&a.claim.verdict!=="cannot_run"&&!n.stopped&&!d)throw new E("nothing_captured","Canary captured no output of any command for this job, and no screenshot, recording or trace a command produced, so nothing stands behind this claim.","Run the scenario, so what it prints is captured, and submit again. If it can't run, send it as cannot_run and say what stopped you: that is a fine result.");let m=new Map(a.files.map(v=>[v.path,v.mediaType])),u=[],p=d5(r),f=(v,w)=>{let P=p(w);for(let V of P.hidden)u.push({name:V,path:v});return P.text},k=[...l].sort().map(v=>{let w=I0(We(e,v));return{path:v,data:w,text:w.length>m5||f5(w)?null:w.toString("utf8")}}),x=new Set(a.steps.map(v=>v.id)),y=v=>JSON.parse(JSON.stringify(a),(w,P)=>typeof P!="string"||yf.has(w)||l.has(P)||x.has(P)?P:v(P));for(let v of k)v.text!==null&&p(v.text);y(v=>p(v).text);let b=new Map;for(let{path:v,data:w,text:P}of k){let V=P===null?P:f(v,P);b.set(v,V===null||V===P?w:Buffer.from(V))}let z=y(v=>f(s,v));for(let v of z.files)v.bytes=b.get(v.path)?.length??v.bytes;let C=new Map([[s,Buffer.from(JSON.stringify(z,null,2))],...b]),I=[...C].map(([v,w])=>({path:v,mediaType:v===s?"application/json":m.get(v)??p5[u5(v).toLowerCase()]??"application/octet-stream",bytes:w.length,sha256:tf("sha256").update(w).digest("hex")})),S=I.filter(v=>v.bytes>m5).map(v=>v.path);if(S.length)throw new E("too_large",`Over 32 MB: ${S.join(", ")}.`,"Leave out what the scenario doesn't need, or trim long recordings.");if(I.reduce((v,w)=>v+w.bytes,0)>of)throw new E("too_large","The evidence is over 256 MB in total.","Leave out what the scenario doesn't need, or trim long recordings.");return{pack:z,upload:{kind:t,proofRequestId:q,files:I},bytes:C,hidden:u}}function R0(e,t){try{let n=T0(e);if(!T0(We(e,t)).startsWith(n+sf))return null;let r=qf(We(e,t));return r.isFile()?r.size:null}catch{return null}}var y5=`Evidence for one job: packs/<job>/pack.json in the batch folder, with any file it names beside it
|
|
3237
3267
|
(paths relative to that folder, plain names, no leading dot).
|
|
3238
3268
|
|
|
3239
3269
|
What came back is not yours to write. Canary captures what every command you run prints, and notes
|
|
@@ -3276,47 +3306,47 @@ reproduction may be null when nothing broke.
|
|
|
3276
3306
|
An answer to request <n>: packs/<job>/proof-<n>/delta.json, with only new steps and files; a file
|
|
3277
3307
|
needs a path not already sent with the job. Its reproduction, when not null, replaces the job's:
|
|
3278
3308
|
{ "answer": "what was done, or why it couldn't be", "steps": [], "files": [], "targets": [], "standIns": [],
|
|
3279
|
-
"permissions": [], "reproduction": null }`;g();import{homedir as wf}from"node:os";import{basename as vr,isAbsolute as bf,join as kf,resolve as zf}from"node:path";var
|
|
3280
|
-
`,n)+1||e.length+1)-1),r=[],s=t,o=[],i=null,a=null,l="word",c=u=>u.startsWith("~/")?kf(wf(),u.slice(2)):bf(u)?u:s===null?null:zf(s,u),h=u=>{let p=
|
|
3281
|
-
`||p===";"||p==="|"||p==="&"?m():p==="("||p===")"?(m(),p===")"&&s!==t&&(s=null)):/\s/.test(p)?d():i=(i??"")+p}return m(),r}g();import{basename as
|
|
3282
|
-
`),n=[];for(let q=0;q<t.length;q++){n.push(t[q]);let r=/<<-?\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(t[q]),s=r?t.findIndex((i,a)=>a>q&&i.trim()===r[2]):-1;if(!r||s<0)continue;let o=t[q].slice(0,r.index).split(/[|;&]+/).pop().trim().split(/\s+/).find(i=>!yr.test(i)&&!
|
|
3283
|
-
`)}function
|
|
3309
|
+
"permissions": [], "reproduction": null }`;g();import{homedir as wf}from"node:os";import{basename as vr,isAbsolute as bf,join as kf,resolve as zf}from"node:path";var w5=e=>!/[$`*?]/.test(e);function b5(e,t){let n=e.indexOf("<<"),q=n===-1?e:e.slice(0,(e.indexOf(`
|
|
3310
|
+
`,n)+1||e.length+1)-1),r=[],s=t,o=[],i=null,a=null,l="word",c=u=>u.startsWith("~/")?kf(wf(),u.slice(2)):bf(u)?u:s===null?null:zf(s,u),h=u=>{let p=w5(u)?c(u):null;p&&r.push(p)},d=()=>{i!==null&&(l==="target"?h(i):l==="word"&&o.push(i),i=null,l="word")},m=()=>{d();let[u,...p]=o[0]==="sudo"||o[0]==="command"?o.slice(1):o,f=p.filter(y=>!y.startsWith("-")),k=vr(u??"");k==="cd"?s=f[0]&&w5(f[0])?c(f[0]):null:(k==="cp"||k==="mv")&&f.length>1?h(f.at(-1)):(k==="tee"||k==="touch"||k==="mkdir")&&f.forEach(h);let x=o.findIndex(y=>vr(y)==="curl"||vr(y)==="wget");if(x!==-1){let y=vr(o[x])==="wget",b=y?"--output-document":"--output",z=y?/^-[a-zA-Z]*O$/:/^-[a-zA-Z]*o$/,C=o.slice(x+1);C.forEach((I,S)=>{I.startsWith(`${b}=`)?h(I.slice(b.length+1)):(I===b||z.test(I))&&C[S+1]&&C[S+1]!=="-"&&h(C[S+1])})}o=[]};for(let u=0;u<q.length;u++){let p=q[u];if(a)p===a?a=null:i=(i??"")+p;else if(p==="'"||p==='"')a=p,i??="";else if(p==="\\")i=(i??"")+(q[++u]??"");else if(p===">"||p==="<"){for(i!==null&&/^\d+$/.test(i)?i=null:d();q[u+1]===p||q[u+1]==="-";)u++;if(q[u+1]==="&"||q[u+1]==="("){for(;u+1<q.length&&!/[\s;|)]/.test(q[u+1]);)u++;continue}l=p===">"?"target":"skip"}else p===`
|
|
3311
|
+
`||p===";"||p==="|"||p==="&"?m():p==="("||p===")"?(m(),p===")"&&s!==t&&(s=null)):/\s/.test(p)?d():i=(i??"")+p}return m(),r}g();import{basename as I2,dirname as xf,isAbsolute as E0,join as Sf,resolve as gr,sep as N0}from"node:path";var He=e=>({reason:e,shared:!1}),P0=e=>({reason:e,shared:!0}),S5=new Set(["sudo","env","command","exec","time","nohup","nice","xargs"]),C5=new Set(["bash","sh","zsh","source","."]),k5=new Set(["rm","rmdir","unlink","shred","trash"]),Cf=new Set(["node","python","python3","ruby","perl","deno","bun"]),Af=/\b(rmSync|rmdirSync|unlinkSync|rmtree|removedirs|FileUtils\.rm\w*|File\.delete)\b|\b(fs|fsp|os|shutil)\.(rm|rmdir|unlink|remove)\b|\bunlink\s*\(/,If=new Set(["psql","mysql","mariadb","mongosh","mongo","redis-cli","cockroach","clickhouse-client","sqlcmd"]),Rf=new Set(["dropdb","dropuser"]),Tf=/\b(drop\s+(table|database|schema|index|collection)|truncate(\s+table)?\s+\w+|delete\s+from|flushall|flushdb|dropdatabase|deletemany)\b|\.drop\(/i,Of={aws:/\b(delete|remove|terminate|deregister|purge|rm|rb)\b/,gcloud:/\b(delete|remove|purge)\b/,az:/\b(delete|remove|purge)\b/,kubectl:/\bdelete\b/,helm:/\b(uninstall|delete)\b/,terraform:/\bdestroy\b/,pulumi:/\bdestroy\b/,cdk:/\bdestroy\b/,gh:/\bdelete\b/,heroku:/\b(destroy|delete)\b/,fly:/\b(destroy|delete)\b/,flyctl:/\b(destroy|delete)\b/,vercel:/\b(rm|remove)\b/,netlify:/\bdelete\b/,supabase:/\b(delete|reset)\b/},Ef=new Set(["-H","--host","--context","--config","-c","-l","--log-level"]),Nf=new Set(["-p","--project-name","-f","--file","--profile","--env-file","--project-directory"]),z5=new Set(["volume","network","container","image","system","builder"]),R2="",ht="",Pf=new Set(["export","local","readonly","declare","typeset"]),x5=new Set(["{","}","then","do","else","elif","if","while","until","!","fi","done"]),yr=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;function br(e,t){let n=0,q=null;for(let r=t+2;r<e.length;r++){let s=e[r];if(s==="$"&&e[r+1]==="("&&q!=="'"){r=br(e,r)-1;continue}if(q){s===q&&(q=null);continue}if(s==="'"||s==='"')q=s;else if(s==="(")n++;else if(s===")"&&n--===0)return r+1}return e.length}function A5(e){let t=[],n=null;for(let q=0;q<e.length;q++){let r=e[q];if(n==="'"){r==="'"&&(n=null);continue}if(r==="\\"){q++;continue}if(r==="'"&&n===null)n=r;else if(r==='"')n=n?null:r;else if(r==="$"&&e[q+1]==="("){let s=br(e,q);t.push(e.slice(q+2,s-1)),q=s-1}else if(r==="`"){let s=e.indexOf("`",q+1);if(s<0)break;t.push(e.slice(q+1,s)),q=s}}return t}function j0(e){let t=e.split(`
|
|
3312
|
+
`),n=[];for(let q=0;q<t.length;q++){n.push(t[q]);let r=/<<-?\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(t[q]),s=r?t.findIndex((i,a)=>a>q&&i.trim()===r[2]):-1;if(!r||s<0)continue;let o=t[q].slice(0,r.index).split(/[|;&]+/).pop().trim().split(/\s+/).find(i=>!yr.test(i)&&!S5.has(I2(i)));C5.has(I2(o??""))||(q=s)}return n.join(`
|
|
3313
|
+
`)}function M0(e){let t=[],n=[],q=null,r=null,s=()=>{q!==null&&n.push(q),q=null},o=()=>{s(),n.length&&t.push(n),n=[]},i=e.replace(/\\\n/g," ");for(let a=0;a<i.length;a++){let l=i[a];if(l==="$"&&i[a+1]==="("&&r!=="'"){let c=br(i,a);q=(q??"")+i.slice(a,c),a=c-1;continue}if(r){l===r?r=null:q+=r==="'"&&l==="$"?R2:l;continue}if(l==="'"||l==='"'){r=l,q??="";continue}if(l==="("||l===")"){o(),t.push([l]);continue}if(l==="#"&&q===null){for(;a<i.length&&i[a]!==`
|
|
3284
3314
|
`;)a++;o();continue}if(l===`
|
|
3285
|
-
`||l===";"||l==="|"||l==="&"){o();continue}if(l===" "||l===" "){s();continue}q=(q??"")+l}return o(),t}var jf=(e,t)=>e.replace(/\$\{BASH_SOURCE(?:\[0\])?\}|\$BASH_SOURCE(?:\[0\])?|\$\{0\}|\$0(?![0-9])/g,t);function wr(e,t,n=0,q=null,r=new Map){let s=u=>t.roots.some(p=>u===p||u.startsWith(p.endsWith(E0)?p:p+E0)),o=t.cwd,i=new Map([["HOME",t.home],...r]),a=u=>{let p=u.replace(/\$\$/g,"PID");for(let f=p.lastIndexOf("$(");f>=0;f=p.lastIndexOf("$(")){let k=br(p,f);p=p.slice(0,f)+(c(p.slice(f+2,k-1).trim())??ht)+p.slice(k)}return p.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(f,k,x,y)=>{let b=(k??y)==="PWD"?o:i.get(k??y);return typeof b=="string"?b:x===void 0?ht:a(x)}).replace(/\$\{[^}]*\}|`[^`]*`|[$`]/g,ht)},l=u=>{let p=a(u);return p.includes(ht)?null:p.split(I2).join("$")},c=u=>{let p=/^(?:cd\s+(?:--\s+)?(.+?)\s*(?:&&|;)\s*pwd(?:\s+-P)?|dirname\s+(?:--\s+)?(.+)|pwd(?:\s+-P)?)$/s.exec(u);if(!p)return null;let f=p[1]??p[2];if(f===void 0)return o;let k=l(f.replace(/^(["'])(.*)\1$/s,"$2"));if(k===null||o===null&&!O0(k))return null;let x=O0(k)?gr(k):gr(o,k);return p[2]===void 0?x:xf(x)},h=new Set,d=Tf.test(e),m=[];for(let u of j0(P0(q?jf(e,q):e))){if(u[0]==="("){m.push(o);continue}if(u[0]===")"){o=m.pop()??o;continue}let p=u.slice(u.findIndex(R=>!k5.has(R)));if(u.every(R=>k5.has(R)))continue;if(p[0]==="for"&&p[2]==="in"&&p[1]){let R=p.slice(3).map(l);i.set(p[1],R.length>0&&R.every(M=>M!==null&&/^[\w@%+=:,-][\w.@%+=:,-]*$/.test(M))?R[0]:ht);continue}let f=Pf.has(p[0])?p.slice(1).filter(R=>!R.startsWith("-")):p,k=f.findIndex(R=>!yr.test(R)),x=new Map;for(let R of k<0?f:f.slice(0,k)){let[,M,T]=yr.exec(R),D=/^\$\(\s*mktemp\b/.test(T)?Sf(t.roots[0]??t.cwd,".tmp"):a(T);k<0?i.set(M,D):D.includes(ht)||x.set(M,D)}if(k<0)continue;let y=f.slice(k).map(R=>{let M=a(R),T=M.includes(ht);return{text:T?R:M.split(I2).join("$"),opaque:T,known:T?M.slice(0,M.indexOf(ht)):""}}),b=R=>{if(R.opaque)return null;let M=R.text.split(/[*?[{]/)[0],T=M==="~"||M.startsWith("~/")?t.home+M.slice(1):M;return O0(T)?gr(T):o===null?null:gr(o,T)},z=R=>{let M=R.opaque&&R.known&&!/(^|\/)\.\.(\/|$)/.test(R.text)?R.known.slice(0,R.known.lastIndexOf("/")+1)||".":null,T=b(M?{text:M,opaque:!1,known:""}:R);return T===null||!(s(T)||[...h].some(D=>T===D||T.startsWith(D+E0)))},C=y.filter((R,M)=>{let T=/^\d*>>?(.*)$/.exec(R.text),D=/^\d*>>?$/.test(y[M-1]?.text??""),J=T?.[1]?{...R,text:T[1]}:D?R:null,q1=J&&b(J);return q1&&q1!=="/dev/null"&&h.add(q1),!T&&!D&&!/^\d*<</.test(R.text)&&!/^\d*</.test(R.text)});if(C.length===0)continue;let I=C,S=!1;for(;I.length>1&&(z5.has(A2(I[0].text))||yr.test(I[0].text)||I!==C&&I[0].text.startsWith("-"));)S||=A2(I[0].text)==="xargs",I=I.slice(1);let v=A2(I[0].text),w=I.slice(1),P=w.filter(R=>!R.text.startsWith("-")),V=(...R)=>w.some(M=>R.includes(M.text)),J1=I.map(R=>R.text).join(" ");if(v==="cd"){o=P[0]?b(P[0]):null;continue}if(["touch","mkdir","tee","mkfifo"].includes(v)){for(let R of P){let M=b(R);M&&h.add(M)}continue}let T1=()=>new Map(i);if(v==="trap"||v==="eval"){let R=f.slice(k+(C.length-I.length)+1).find(T=>!T.startsWith("-")),M=R===void 0?null:wr(R.split(I2).join("$"),{...t,cwd:o??t.cwd},n+1,q,T1());if(M)return M;continue}if(x5.has(v)){let R=w.findIndex(J=>/^-[a-z]*c[a-z]*$/.test(J.text)),M=R<0&&P[0]?b(P[0]):null,T=R>=0?w[R+1]?.text??null:M&&s(M)&&n<2?t.read(M):null,D=T===null?null:wr(T,{...t,cwd:o??t.cwd},n+1,R>=0?q:M,R>=0?T1():x);if(D)return D;continue}if(w5.has(v)){if(S)return He("it removes whatever files it is handed");let R=P.find(z);if(R)return He(`it removes ${R.text}, which isn't in the checks' own folders`);continue}if(v==="mv"){if(S)return He("it moves away whatever files it is handed");let R=V("-t","--target-directory"),M=(R?P:P.slice(0,-1)).find(z);if(M)return He(`it moves ${M.text} away, which isn't in the checks' own folders`);let T=R?null:P.at(-1)&&b(P.at(-1));T&&h.add(T);continue}if(v==="find"){let R=w.some((D,J)=>D.text==="-delete"||["-exec","-execdir","-ok"].includes(D.text)&&w5.has(A2(w[J+1]?.text??""))),M=w.findIndex(D=>D.text.startsWith("-")||D.text==="("||D.text==="!"),T=M<0?w:w.slice(0,M);if(R&&(T.length===0||T.some(z)))return He("it deletes files it finds outside the checks' own folders");continue}if(Cf.has(v)){let R=w.findIndex(M=>["-e","-c","--eval","-p"].includes(M.text));if(R>=0&&Af.test(w[R+1]?.text??""))return He("it removes files from code given on the command line");continue}if(v==="git"){let R=w.findIndex(J=>J.text==="-C"),M=R>=0&&w[R+1]?b(w[R+1]):o,T=w.filter((J,q1)=>!J.text.startsWith("-")&&!(R>=0&&q1===R+1)).map(J=>J.text);if(T[0]==="push"&&(V("--delete","-d")||T.slice(1).some(J=>J.startsWith(":"))))return N0("it deletes a branch or tag on a remote");if((T[0]==="clean"||T[0]==="restore"||T[0]==="rm"||T[0]==="reset"&&V("--hard")||T[0]==="checkout"&&(V("--","-f","--force")||T.includes("."))||T[0]==="stash"&&["drop","clear"].includes(T[1]??"")||["branch","tag"].includes(T[0]??"")&&V("-D","-d","--delete")||T[0]==="worktree"&&T[1]==="remove")&&(M===null||!s(M)))return He("it discards or deletes git work outside the checks' own copy");continue}if(v==="docker"||v==="podman"||v==="docker-compose"){let R=w.findIndex((d1,Vt)=>!d1.text.startsWith("-")&&!Ef.has(w[Vt-1]?.text??"")),M=v==="docker-compose"||w[R]?.text==="compose",T=M?Nf:new Set(["--filter"]),D=R<0?[]:w.slice(v==="docker-compose"?0:M?R+1:R),J=D.filter((d1,Vt)=>!d1.text.startsWith("-")&&!T.has(D[Vt-1]?.text??"")),q1=J.map(d1=>d1.text),Y1=M?["down","rm"].includes(q1[0]??""):["rm","rmi","prune"].includes(q1[0]??"")||b5.has(q1[0]??"")&&["rm","remove","prune"].includes(q1[1]??""),ye=w.findIndex(d1=>d1.text==="-p"||d1.text==="--project-name"),K1=ye>=0?w[ye+1]?.text:w.find(d1=>d1.text.startsWith("--project-name="))?.text.slice(15),_e=M&&(K1===t.composeProject||K1===void 0&&o!==null&&s(o)),pt=w.some(d1=>d1.text===`label=${t.label}`||d1.text===`--filter=label=${t.label}`),ue=b5.has(q1[0]??""),U=M||(ue?q1[1]:q1[0])==="prune"?null:q1[0]==="rmi"||q1[0]==="image"?"image":q1[0]==="network"||q1[0]==="volume"?q1[0]:"container",se=J.slice(ue?2:1),Gt=v==="docker"&&U!==null&&se.length>0&&se.every(d1=>!d1.opaque&&t.dockerOwn?.(U,d1.text)===!0);if(Y1&&!_e&&!pt&&!Gt)return He("it removes Docker containers, images or volumes that may not be the checks' own");continue}let o1=Rf.has(v)||v==="mysqladmin"&&P.some(R=>R.text==="drop");if(If.has(v)||v==="sqlite3"||o1){let R=v==="sqlite3"?P.length>0&&!z(P[0]):Mf(J1,t.ports)&&!/(?:\s-h|--host)[= ]+(?!localhost\b|127\.0\.0\.1\b)\S/.test(J1);if((d||o1)&&!R)return v==="sqlite3"?He("it drops or deletes data in a database file that isn't the checks' own"):N0("it drops or deletes data in a database the checks didn't start");continue}if(Of[v]?.test(w.map(R=>R.text).join(" ")))return N0(`it deletes something with ${v}`)}return null}function Mf(e,[t,n]){let q=[...e.matchAll(/(?:(?:localhost|127\.0\.0\.1):|\s(?:-p|-P|--port)[= ]?)(\d{2,5})\b/g)].map(r=>Number(r[1]));return q.length>0&&q.every(r=>r>=t&&r<=n)}g();import{join as Lf}from"node:path";var Ff=[".ssh",".gnupg",".aws",".azure",".kube",".config/gcloud",".git-credentials",".config/git/credentials",".docker/config.json",".netrc",".password-store","Library/Keychains",".config/gh/hosts.yml",".config/glab-cli/config.yml",".fly/config.yml",".vault-token",".claude/.credentials.json",".claude.json"],Be=()=>!0,C5=e=>e.some(t=>t==="-t"||t==="--show-token"),M0=e=>h1(e,"config","get")&&e.some(t=>/(_auth(Token)?|_password|npmAuthToken|npmAuthIdent)$/i.test(t)),A5={op:Be,bw:Be,rbw:Be,pass:Be,passage:Be,gopass:Be,lpass:Be,"keepassxc-cli":Be,"kwallet-query":Be,security:e=>h1(e,/^(find-generic-password|find-internet-password|dump-keychain|export)$/),"secret-tool":e=>h1(e,/^(lookup|search)$/),keyring:e=>h1(e,"get"),"aws-vault":e=>h1(e,"export"),git:e=>h1(e,"credential","fill")||h1(e,/^credential-/,"get"),gh:e=>h1(e,"auth","token")||h1(e,"auth","git-credential")||h1(e,"auth","status")&&C5(e)||h1(e,"config","get")&&e.includes("oauth_token"),glab:e=>h1(e,"auth","status")&&C5(e)||h1(e,"config","get")&&e.includes("token"),gcloud:e=>h1(e,"auth",/^print-(access|identity)-token$/)||h1(e,"auth","application-default","print-access-token")||h1(e,"config","config-helper"),az:e=>h1(e,"account","get-access-token"),aws:e=>h1(e,"configure","export-credentials")||h1(e,"configure","get")&&e.some(t=>/(^|\.)aws_(secret_access_key|session_token)$/.test(t)),heroku:e=>h1(e,"auth:token"),fly:e=>h1(e,"auth","token"),flyctl:e=>h1(e,"auth","token"),vault:e=>h1(e,"print","token")||h1(e,"token","lookup"),kubectl:e=>h1(e,"config","view")&&e.includes("--raw"),npm:M0,pnpm:M0,yarn:M0,gpg:e=>e.some(t=>/^--export-secret-(sub)?keys?$/.test(t))},$f=new Set(["{","}","!","if","then","elif","else","while","until","do","time","sudo","doas","env","command","builtin","exec","nohup","nice","ionice","timeout","stdbuf","xargs","caffeinate"]),I5=new Set(["sh","bash","zsh","dash","ksh","fish"]),R5=e=>({reason:e,shared:!1,secret:!0}),Df=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),kr=e=>e.replace(/\\/g,"/").replace(/\/+$/,""),F0=e=>e.split(/[\\/]/).pop().replace(/\.exe$/i,"");function T5(e,t){return[...Ff.map(n=>Lf(e,n)),t]}function O5(e,t){let[n,q]=[kr(e),kr(t)];return n.toLowerCase().startsWith(`${q.toLowerCase()}/`)?n.slice(q.length+1):null}var $0=(e,t)=>{let n=O5(e,t);return n===null?e:`~/${n}`};function Wf(e){let t=kr(e),n=t.slice(0,t.lastIndexOf("/")+1),q=/^([A-Za-z]):\//.exec(t);return["~",`~${t.slice(n.length)}`,"$HOME","${HOME}","$USERPROFILE","${USERPROFILE}","%USERPROFILE%","$env:USERPROFILE","${env:USERPROFILE}","$env:HOME","%HOMEDRIVE%%HOMEPATH%",t,`${n}$USER`,`${n}\${USER}`,...q?[`/${q[1]}${t.slice(2)}`]:[]]}function Hf(e,t,n){let q=s=>Df(kr(s)).replace(/\//g,"[\\\\/]"),r=Wf(t).map(q).join("|");return n.find(s=>{let o=O5(s,t),i=o===null?q(s):`(?:${r})[\\\\/]${q(o)}`;return new RegExp(`${i}(?=$|[\\\\/\\s'"\`;|&)<>])`,"im").test(e)})??null}function h1(e,...t){let n=0;for(let q=0;q<e.length&&n<t.length;q++){let r=t[n];if(typeof r=="string"?e[q]===r:r.test(e[q]))n++;else if(!e[q].startsWith("-")&&!/^-[^=]*$/.test(e[q-1]??""))return!1}return n===t.length}function E5(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="command"&&/^-[vV]$/.test(e[t+1]??""))return e.length;if(!($f.has(F0(n))||/^[A-Za-z_][A-Za-z0-9_]*=/.test(n)||t>0&&(n.startsWith("-")||/^\d+(\.\d+)?[smhd]?$/.test(n))))return t}return e.length}function L0(e,t=0){let n=P0(e),q=j0(n);if(t>3)return q;for(let r of[...q]){let s=E5(r),o=F0(r[s]??""),i=I5.has(o)?r.findIndex((l,c)=>c>s&&/^-[A-Za-z]*c[A-Za-z]*$/.test(l)):/^(pwsh|powershell)$/i.test(o)?r.findIndex((l,c)=>c>s&&/^-(c|command)$/i.test(l)):/^cmd$/i.test(o)?r.findIndex((l,c)=>c>s&&/^\/[ck]$/i.test(l)):-1,a=i<0?o==="eval"?r.slice(s+1).join(" "):null:I5.has(o)?r[i+1]??null:r.slice(i+1).join(" ");a&&q.push(...L0(a.split(I2).join("$"),t+1))}for(let r of S5(n))q.push(...L0(r,t+1));return q}function N5(e,t,n){let q=L0(e),r=Hf([e,...q.map(s=>s.join(" "))].join(`
|
|
3286
|
-
`),t,n);if(r)return
|
|
3287
|
-
`,{flag:"wx"}),{...s,path:o}}throw new E("question_ids","Couldn't number a new question; run the command again.")}function
|
|
3315
|
+
`||l===";"||l==="|"||l==="&"){o();continue}if(l===" "||l===" "){s();continue}q=(q??"")+l}return o(),t}var jf=(e,t)=>e.replace(/\$\{BASH_SOURCE(?:\[0\])?\}|\$BASH_SOURCE(?:\[0\])?|\$\{0\}|\$0(?![0-9])/g,t);function wr(e,t,n=0,q=null,r=new Map){let s=u=>t.roots.some(p=>u===p||u.startsWith(p.endsWith(N0)?p:p+N0)),o=t.cwd,i=new Map([["HOME",t.home],...r]),a=u=>{let p=u.replace(/\$\$/g,"PID");for(let f=p.lastIndexOf("$(");f>=0;f=p.lastIndexOf("$(")){let k=br(p,f);p=p.slice(0,f)+(c(p.slice(f+2,k-1).trim())??ht)+p.slice(k)}return p.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(f,k,x,y)=>{let b=(k??y)==="PWD"?o:i.get(k??y);return typeof b=="string"?b:x===void 0?ht:a(x)}).replace(/\$\{[^}]*\}|`[^`]*`|[$`]/g,ht)},l=u=>{let p=a(u);return p.includes(ht)?null:p.split(R2).join("$")},c=u=>{let p=/^(?:cd\s+(?:--\s+)?(.+?)\s*(?:&&|;)\s*pwd(?:\s+-P)?|dirname\s+(?:--\s+)?(.+)|pwd(?:\s+-P)?)$/s.exec(u);if(!p)return null;let f=p[1]??p[2];if(f===void 0)return o;let k=l(f.replace(/^(["'])(.*)\1$/s,"$2"));if(k===null||o===null&&!E0(k))return null;let x=E0(k)?gr(k):gr(o,k);return p[2]===void 0?x:xf(x)},h=new Set,d=Tf.test(e),m=[];for(let u of M0(j0(q?jf(e,q):e))){if(u[0]==="("){m.push(o);continue}if(u[0]===")"){o=m.pop()??o;continue}let p=u.slice(u.findIndex(R=>!x5.has(R)));if(u.every(R=>x5.has(R)))continue;if(p[0]==="for"&&p[2]==="in"&&p[1]){let R=p.slice(3).map(l);i.set(p[1],R.length>0&&R.every(M=>M!==null&&/^[\w@%+=:,-][\w.@%+=:,-]*$/.test(M))?R[0]:ht);continue}let f=Pf.has(p[0])?p.slice(1).filter(R=>!R.startsWith("-")):p,k=f.findIndex(R=>!yr.test(R)),x=new Map;for(let R of k<0?f:f.slice(0,k)){let[,M,T]=yr.exec(R),D=/^\$\(\s*mktemp\b/.test(T)?Sf(t.roots[0]??t.cwd,".tmp"):a(T);k<0?i.set(M,D):D.includes(ht)||x.set(M,D)}if(k<0)continue;let y=f.slice(k).map(R=>{let M=a(R),T=M.includes(ht);return{text:T?R:M.split(R2).join("$"),opaque:T,known:T?M.slice(0,M.indexOf(ht)):""}}),b=R=>{if(R.opaque)return null;let M=R.text.split(/[*?[{]/)[0],T=M==="~"||M.startsWith("~/")?t.home+M.slice(1):M;return E0(T)?gr(T):o===null?null:gr(o,T)},z=R=>{let M=R.opaque&&R.known&&!/(^|\/)\.\.(\/|$)/.test(R.text)?R.known.slice(0,R.known.lastIndexOf("/")+1)||".":null,T=b(M?{text:M,opaque:!1,known:""}:R);return T===null||!(s(T)||[...h].some(D=>T===D||T.startsWith(D+N0)))},C=y.filter((R,M)=>{let T=/^\d*>>?(.*)$/.exec(R.text),D=/^\d*>>?$/.test(y[M-1]?.text??""),J=T?.[1]?{...R,text:T[1]}:D?R:null,q1=J&&b(J);return q1&&q1!=="/dev/null"&&h.add(q1),!T&&!D&&!/^\d*<</.test(R.text)&&!/^\d*</.test(R.text)});if(C.length===0)continue;let I=C,S=!1;for(;I.length>1&&(S5.has(I2(I[0].text))||yr.test(I[0].text)||I!==C&&I[0].text.startsWith("-"));)S||=I2(I[0].text)==="xargs",I=I.slice(1);let v=I2(I[0].text),w=I.slice(1),P=w.filter(R=>!R.text.startsWith("-")),V=(...R)=>w.some(M=>R.includes(M.text)),J1=I.map(R=>R.text).join(" ");if(v==="cd"){o=P[0]?b(P[0]):null;continue}if(["touch","mkdir","tee","mkfifo"].includes(v)){for(let R of P){let M=b(R);M&&h.add(M)}continue}let T1=()=>new Map(i);if(v==="trap"||v==="eval"){let R=f.slice(k+(C.length-I.length)+1).find(T=>!T.startsWith("-")),M=R===void 0?null:wr(R.split(R2).join("$"),{...t,cwd:o??t.cwd},n+1,q,T1());if(M)return M;continue}if(C5.has(v)){let R=w.findIndex(J=>/^-[a-z]*c[a-z]*$/.test(J.text)),M=R<0&&P[0]?b(P[0]):null,T=R>=0?w[R+1]?.text??null:M&&s(M)&&n<2?t.read(M):null,D=T===null?null:wr(T,{...t,cwd:o??t.cwd},n+1,R>=0?q:M,R>=0?T1():x);if(D)return D;continue}if(k5.has(v)){if(S)return He("it removes whatever files it is handed");let R=P.find(z);if(R)return He(`it removes ${R.text}, which isn't in the checks' own folders`);continue}if(v==="mv"){if(S)return He("it moves away whatever files it is handed");let R=V("-t","--target-directory"),M=(R?P:P.slice(0,-1)).find(z);if(M)return He(`it moves ${M.text} away, which isn't in the checks' own folders`);let T=R?null:P.at(-1)&&b(P.at(-1));T&&h.add(T);continue}if(v==="find"){let R=w.some((D,J)=>D.text==="-delete"||["-exec","-execdir","-ok"].includes(D.text)&&k5.has(I2(w[J+1]?.text??""))),M=w.findIndex(D=>D.text.startsWith("-")||D.text==="("||D.text==="!"),T=M<0?w:w.slice(0,M);if(R&&(T.length===0||T.some(z)))return He("it deletes files it finds outside the checks' own folders");continue}if(Cf.has(v)){let R=w.findIndex(M=>["-e","-c","--eval","-p"].includes(M.text));if(R>=0&&Af.test(w[R+1]?.text??""))return He("it removes files from code given on the command line");continue}if(v==="git"){let R=w.findIndex(J=>J.text==="-C"),M=R>=0&&w[R+1]?b(w[R+1]):o,T=w.filter((J,q1)=>!J.text.startsWith("-")&&!(R>=0&&q1===R+1)).map(J=>J.text);if(T[0]==="push"&&(V("--delete","-d")||T.slice(1).some(J=>J.startsWith(":"))))return P0("it deletes a branch or tag on a remote");if((T[0]==="clean"||T[0]==="restore"||T[0]==="rm"||T[0]==="reset"&&V("--hard")||T[0]==="checkout"&&(V("--","-f","--force")||T.includes("."))||T[0]==="stash"&&["drop","clear"].includes(T[1]??"")||["branch","tag"].includes(T[0]??"")&&V("-D","-d","--delete")||T[0]==="worktree"&&T[1]==="remove")&&(M===null||!s(M)))return He("it discards or deletes git work outside the checks' own copy");continue}if(v==="docker"||v==="podman"||v==="docker-compose"){let R=w.findIndex((d1,Vt)=>!d1.text.startsWith("-")&&!Ef.has(w[Vt-1]?.text??"")),M=v==="docker-compose"||w[R]?.text==="compose",T=M?Nf:new Set(["--filter"]),D=R<0?[]:w.slice(v==="docker-compose"?0:M?R+1:R),J=D.filter((d1,Vt)=>!d1.text.startsWith("-")&&!T.has(D[Vt-1]?.text??"")),q1=J.map(d1=>d1.text),Y1=M?["down","rm"].includes(q1[0]??""):["rm","rmi","prune"].includes(q1[0]??"")||z5.has(q1[0]??"")&&["rm","remove","prune"].includes(q1[1]??""),ye=w.findIndex(d1=>d1.text==="-p"||d1.text==="--project-name"),K1=ye>=0?w[ye+1]?.text:w.find(d1=>d1.text.startsWith("--project-name="))?.text.slice(15),_e=M&&(K1===t.composeProject||K1===void 0&&o!==null&&s(o)),pt=w.some(d1=>d1.text===`label=${t.label}`||d1.text===`--filter=label=${t.label}`),ue=z5.has(q1[0]??""),U=M||(ue?q1[1]:q1[0])==="prune"?null:q1[0]==="rmi"||q1[0]==="image"?"image":q1[0]==="network"||q1[0]==="volume"?q1[0]:"container",se=J.slice(ue?2:1),Gt=v==="docker"&&U!==null&&se.length>0&&se.every(d1=>!d1.opaque&&t.dockerOwn?.(U,d1.text)===!0);if(Y1&&!_e&&!pt&&!Gt)return He("it removes Docker containers, images or volumes that may not be the checks' own");continue}let o1=Rf.has(v)||v==="mysqladmin"&&P.some(R=>R.text==="drop");if(If.has(v)||v==="sqlite3"||o1){let R=v==="sqlite3"?P.length>0&&!z(P[0]):Mf(J1,t.ports)&&!/(?:\s-h|--host)[= ]+(?!localhost\b|127\.0\.0\.1\b)\S/.test(J1);if((d||o1)&&!R)return v==="sqlite3"?He("it drops or deletes data in a database file that isn't the checks' own"):P0("it drops or deletes data in a database the checks didn't start");continue}if(Of[v]?.test(w.map(R=>R.text).join(" ")))return P0(`it deletes something with ${v}`)}return null}function Mf(e,[t,n]){let q=[...e.matchAll(/(?:(?:localhost|127\.0\.0\.1):|\s(?:-p|-P|--port)[= ]?)(\d{2,5})\b/g)].map(r=>Number(r[1]));return q.length>0&&q.every(r=>r>=t&&r<=n)}g();import{join as Lf}from"node:path";var Ff=[".ssh",".gnupg",".aws",".azure",".kube",".config/gcloud",".git-credentials",".config/git/credentials",".docker/config.json",".netrc",".password-store","Library/Keychains",".config/gh/hosts.yml",".config/glab-cli/config.yml",".fly/config.yml",".vault-token",".claude/.credentials.json",".claude.json"],Be=()=>!0,I5=e=>e.some(t=>t==="-t"||t==="--show-token"),L0=e=>h1(e,"config","get")&&e.some(t=>/(_auth(Token)?|_password|npmAuthToken|npmAuthIdent)$/i.test(t)),R5={op:Be,bw:Be,rbw:Be,pass:Be,passage:Be,gopass:Be,lpass:Be,"keepassxc-cli":Be,"kwallet-query":Be,security:e=>h1(e,/^(find-generic-password|find-internet-password|dump-keychain|export)$/),"secret-tool":e=>h1(e,/^(lookup|search)$/),keyring:e=>h1(e,"get"),"aws-vault":e=>h1(e,"export"),git:e=>h1(e,"credential","fill")||h1(e,/^credential-/,"get"),gh:e=>h1(e,"auth","token")||h1(e,"auth","git-credential")||h1(e,"auth","status")&&I5(e)||h1(e,"config","get")&&e.includes("oauth_token"),glab:e=>h1(e,"auth","status")&&I5(e)||h1(e,"config","get")&&e.includes("token"),gcloud:e=>h1(e,"auth",/^print-(access|identity)-token$/)||h1(e,"auth","application-default","print-access-token")||h1(e,"config","config-helper"),az:e=>h1(e,"account","get-access-token"),aws:e=>h1(e,"configure","export-credentials")||h1(e,"configure","get")&&e.some(t=>/(^|\.)aws_(secret_access_key|session_token)$/.test(t)),heroku:e=>h1(e,"auth:token"),fly:e=>h1(e,"auth","token"),flyctl:e=>h1(e,"auth","token"),vault:e=>h1(e,"print","token")||h1(e,"token","lookup"),kubectl:e=>h1(e,"config","view")&&e.includes("--raw"),npm:L0,pnpm:L0,yarn:L0,gpg:e=>e.some(t=>/^--export-secret-(sub)?keys?$/.test(t))},$f=new Set(["{","}","!","if","then","elif","else","while","until","do","time","sudo","doas","env","command","builtin","exec","nohup","nice","ionice","timeout","stdbuf","xargs","caffeinate"]),T5=new Set(["sh","bash","zsh","dash","ksh","fish"]),O5=e=>({reason:e,shared:!1,secret:!0}),Df=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),kr=e=>e.replace(/\\/g,"/").replace(/\/+$/,""),$0=e=>e.split(/[\\/]/).pop().replace(/\.exe$/i,"");function E5(e,t){return[...Ff.map(n=>Lf(e,n)),t]}function N5(e,t){let[n,q]=[kr(e),kr(t)];return n.toLowerCase().startsWith(`${q.toLowerCase()}/`)?n.slice(q.length+1):null}var D0=(e,t)=>{let n=N5(e,t);return n===null?e:`~/${n}`};function Wf(e){let t=kr(e),n=t.slice(0,t.lastIndexOf("/")+1),q=/^([A-Za-z]):\//.exec(t);return["~",`~${t.slice(n.length)}`,"$HOME","${HOME}","$USERPROFILE","${USERPROFILE}","%USERPROFILE%","$env:USERPROFILE","${env:USERPROFILE}","$env:HOME","%HOMEDRIVE%%HOMEPATH%",t,`${n}$USER`,`${n}\${USER}`,...q?[`/${q[1]}${t.slice(2)}`]:[]]}function Hf(e,t,n){let q=s=>Df(kr(s)).replace(/\//g,"[\\\\/]"),r=Wf(t).map(q).join("|");return n.find(s=>{let o=N5(s,t),i=o===null?q(s):`(?:${r})[\\\\/]${q(o)}`;return new RegExp(`${i}(?=$|[\\\\/\\s'"\`;|&)<>])`,"im").test(e)})??null}function h1(e,...t){let n=0;for(let q=0;q<e.length&&n<t.length;q++){let r=t[n];if(typeof r=="string"?e[q]===r:r.test(e[q]))n++;else if(!e[q].startsWith("-")&&!/^-[^=]*$/.test(e[q-1]??""))return!1}return n===t.length}function P5(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="command"&&/^-[vV]$/.test(e[t+1]??""))return e.length;if(!($f.has($0(n))||/^[A-Za-z_][A-Za-z0-9_]*=/.test(n)||t>0&&(n.startsWith("-")||/^\d+(\.\d+)?[smhd]?$/.test(n))))return t}return e.length}function F0(e,t=0){let n=j0(e),q=M0(n);if(t>3)return q;for(let r of[...q]){let s=P5(r),o=$0(r[s]??""),i=T5.has(o)?r.findIndex((l,c)=>c>s&&/^-[A-Za-z]*c[A-Za-z]*$/.test(l)):/^(pwsh|powershell)$/i.test(o)?r.findIndex((l,c)=>c>s&&/^-(c|command)$/i.test(l)):/^cmd$/i.test(o)?r.findIndex((l,c)=>c>s&&/^\/[ck]$/i.test(l)):-1,a=i<0?o==="eval"?r.slice(s+1).join(" "):null:T5.has(o)?r[i+1]??null:r.slice(i+1).join(" ");a&&q.push(...F0(a.split(R2).join("$"),t+1))}for(let r of A5(n))q.push(...F0(r,t+1));return q}function j5(e,t,n){let q=F0(e),r=Hf([e,...q.map(s=>s.join(" "))].join(`
|
|
3316
|
+
`),t,n);if(r)return O5(`it reads ${D0(r,t)}, where the user keeps credentials`);for(let s of q){let o=P5(s),i=$0(s[o]??""),a=s.slice(o+1);if(Object.hasOwn(R5,i)&&R5[i](a)||/^(git|docker)-credential-/.test(i)&&h1(a,/^(get|list)$/))return O5(`it prints the user's credentials with ${i}`)}return null}g();function M5(e){let t=e.replace(/'[^']*'/g,"''"),n=t.split(/&&|\|\||[;|\n]/).map(q=>q.trimStart());return n.some(q=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(q))?"it starts by setting a shell variable":/\$[A-Za-z_{(]|`/.test(t)?"it uses a shell variable or command substitution":n.some(q=>/^cd(\s|$)/.test(q))?"it changes directory":null}var L5=e=>`Canary: not run, because ${e}, which makes Claude Code ask the user to approve it whatever their settings allow. Write every path out in full, read files with your Read, Grep and Glob tools, and put anything that needs variables or several steps in a script in your copy, run with bash and its absolute path.`;g();import{existsSync as Bf,mkdirSync as F5,readdirSync as $5,writeFileSync as W0}from"node:fs";import{join as T2}from"node:path";var H0=e=>T2(s1(e),"questions");function de(e){let t=[];for(let{runId:n}of e){let q=H0(n);if(Bf(q))for(let r of $5(q).filter(s=>/^Q\d+\.json$/.test(s))){let s=Y(T2(q,r));s&&t.push({...s,path:T2(q,r)})}}return t.sort((n,q)=>Number(n.id.slice(1))-Number(q.id.slice(1)))}function D5(e,t){let n=T2(H1(Et(e)).dir,"question-ids");F5(n,{recursive:!0}),F5(H0(t.runId),{recursive:!0});for(let q=0;q<100;q++){let r=Math.max(0,...$5(n).map(i=>Number(/^Q(\d+)$/.exec(i)?.[1]??0)))+1+q;try{W0(T2(n,`Q${r}`),t.runId,{flag:"wx"})}catch(i){if(i.code==="EEXIST")continue;throw i}let s={...t,id:`Q${r}`,askedAt:new Date().toISOString(),status:"open",answer:null,answeredAt:null},o=T2(H0(t.runId),`${s.id}.json`);return W0(o,JSON.stringify(s,null,2)+`
|
|
3317
|
+
`,{flag:"wx"}),{...s,path:o}}throw new E("question_ids","Couldn't number a new question; run the command again.")}function W5(e,t){let n=de(e).find(q=>q.id.toLowerCase()===t.toLowerCase());if(!n)throw new E("no_such_question",`No question ${t} among this session's checks.`,"Use the id the listener printed.");return n}function H5(e,t,n,q=[]){let{path:r,...s}=e,o=new Date().toISOString(),i=[...new Set([...s.userWords??[],...q])],a=s.status==="answered"?{...s,more:[...s.more??[],{text:t,at:o}],userSpoke:s.userSpoke||n,userWords:i}:{...s,status:"answered",answer:t,answeredAt:o,userSpoke:n,userWords:i};return F1(r,a,420),a}function B0(e){let t=Y(e),q=(t?.status==="answered"?[t.answer??"",...(t.more??[]).map(r=>r.text)]:[]).flatMap((r,s)=>{try{return W0(`${e}.given-${s}`,"",{flag:"wx"}),[{text:r,index:s}]}catch{return[]}});return{first:q.some(r=>r.index===0),texts:q.map(r=>r.text)}}function $t(e,t,n){for(let q of de(e).filter(r=>r.batchId===t&&(n==="all"||r.jobId===n)&&r.status==="open")){let{path:r,...s}=q;F1(r,{...s,status:"expired"},420)}}function B5(e){return Y(e)}var G1=6e4,Qf=9.5*G1,Zf=9*G1,ev=5*G1,O2=5e3,Wt=2*G1,Y5=5*G1,Gn=5e3,tv=1500,nv=e=>6e4+Math.ceil(e/131),E2=e=>e.slice(0,8),ei=e=>`verifier-${E2(e)}`,ct=e=>new Promise(t=>setTimeout(t,e)),A=e=>void process.stdout.write(`${e}
|
|
3288
3318
|
`),xr=460;function Dt(e){for(let t of e.split(`
|
|
3289
|
-
`)){let n=t;for(;n.length>xr;){let q=n.lastIndexOf(" ",xr),r=q>xr/2?q:xr;A(`${n.slice(0,r)} \u2026`),n=`\u2026 ${n.slice(r).trimStart()}`}A(n)}}var Cr=e=>e.map(t=>t.trim().replace(/[.!?]+$/,n=>n.includes("?")?"?":"")).join(" | ").replace(/([^?])$/,"$1.");function _t(e=process.cwd()){try{return
|
|
3319
|
+
`)){let n=t;for(;n.length>xr;){let q=n.lastIndexOf(" ",xr),r=q>xr/2?q:xr;A(`${n.slice(0,r)} \u2026`),n=`\u2026 ${n.slice(r).trimStart()}`}A(n)}}var Cr=e=>e.map(t=>t.trim().replace(/[.!?]+$/,n=>n.includes("?")?"?":"")).join(" | ").replace(/([^?])$/,"$1.");function _t(e=process.cwd()){try{return G5("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||e}catch{return e}}var Or=e=>i1("/cli/jobs",{session:e}),V1=e=>Object.entries(te(e).runs).map(([t,{checkout:n}])=>({runId:t,checkout:n}));function K5(e){try{if(!k1(N(s1(e),"source.bundle")))return[];let t=N(s1(e),"results");return j2(t).filter(n=>n.endsWith(".json")).flatMap(n=>{let q=Y(N(t,n));return q?.verdict==="blocked"?[`${JSON.stringify(q.scenario.title)} [${q.jobId}]`]:[]})}catch{return[]}}var Vn=e=>K5(e).length>0;async function qv(){let e=process.env.CLAUDE_CODE_SESSION_ID?.trim();if(!e)return;let t=V1(e).filter(({runId:q})=>k1(N(s1(q),"source.bundle")));if(t.length===0)return;let n=new Set((await i1("/cli/jobs",{session:e,timeoutMs:5e3})).runs.map(q=>q.runId));for(let{runId:q}of t)!n.has(q)&&!Vn(q)&&Bt(N(s1(q),"source.bundle"),{force:!0})}function v1(e,t={}){return async(...n)=>{try{if(t.sweep!==!1){el(),t.urgent||await xl(async q=>void await Ft(q,{dockerTimeoutMs:5e3}));for(let q of await Wh(!t.urgent&&!t.local))console.error(`Canary left in place from ${q}`);t.local||await qv().catch(()=>{})}await e(...n)}catch(q){if(q instanceof E||q instanceof L)console.error(`${ir(q)?"Stop":"Error"}: ${q.message}`),q.fix&&console.error(`Next: ${q.fix}`);else{console.error(`Error: ${at}`);let r=process.env.CLAUDE_CODE_SESSION_ID?.trim();r&&await Pn(r,{},q,5e3).catch(()=>{})}process.exitCode=1}}}function Ie(e,t){let n=st(e);return t(n),Cn(n),n}var rv=["environment_missing","information_unavailable","approval_declined","target_unreachable","tool_install_failed","auto_mode_blocked"],sv={broken:"failed",held:"passed",not_reproduced:"unclear",inconclusive:"unclear",blocked:"couldn't run"},ti=e=>e&&sv[e]||"no verdict",X5=e=>e.blockedReason?.kind==="stopped_by_user"?"stopped by the user":e.blockedReason?.kind==="to_prove"?"not tried yet":e.blockedReason?.kind==="moved"?"moved to the additional findings":ti(e.verdict),Hn=(e,t)=>t.verdict==="blocked"?X5(Y(N(s1(e),"results",`${t.jobId}.json`))??{verdict:t.verdict,blockedReason:null}):ti(t.verdict);function ni(e){let t=$1(e);return(t&&Y(N(H1(t).scripts,Ir)))??{}}function G0(e){let t=V1(C1()).find(q=>q.runId===e)?.checkout,n=Object.entries(t?ni(t):{}).map(([q,r])=>`${q} (${r.what})`);return n.length?` Another try starts setup from what earlier tries kept: ${n.join("; ")}.`:""}function Q5(e){let t=n=>n.length>800?`${n.slice(0,799)}\u2026`:n;return e.blockedReason?`Why it couldn't run: ${t(e.blockedReason.detail)}`:e.summary?`What was run and what came back: ${t(e.summary)}`:"What was run and what came back: nothing the review could tie to what a command printed."}function Z5(e,t){let n=e.appFilesChanged??[];return[...e.verdict==="broken"&&e.forcedCondition?[`How it was shown: with ${e.forcedCondition}.`]:[],...n.length?[`The check changed or added these files of the app in its own copy: ${n.join(", ")}. The user's checkout is unchanged.`]:[],...e.sideProblems?.length?[`Found on the side, outside this check and confirmed by none: ${e.sideProblems.join(" ")}`]:[],...e.verdict==="broken"&&e.whereToLook?[`Where to look: ${e.whereToLook}${ov(t,e.whereToLook)}`]:[]]}function ov(e,t){let n=/^(.+?):(\d+)(?:-(\d+))?$/.exec(t.trim()),q=Y(N(s1(e),"source.json")),r=V1(C1()).find(i=>i.runId===e)?.checkout,s=r?$1(r):null;if(!n||!q?.baseTreeHash||!q.treeHash||q.baseTreeHash===q.treeHash||!s)return"";let o=N(B(),"workspaces",p2(s));for(let i of k1(o)?j2(o).filter(a=>/^\d+$/.test(a)):[]){let a;try{a=G5("git",["-C",N(o,i),"diff","--no-color","-U0",q.baseTreeHash,q.treeHash,"--",n[1]],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{continue}let l=[...a.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gm)].map(d=>[Number(d[1]),Number(d[1])+Math.max(d[2]===void 0?1:Number(d[2]),1)-1]);if(l.length===0)return" (a file this change didn't touch)";let[c,h]=[Number(n[2]),Number(n[3]??n[2])];return l.some(([d,m])=>c<=m+3&&h>=d-3)?"":` (a line this change didn't touch; it changed this file at ${l.map(([d,m])=>d===m?`line ${d}`:`lines ${d}-${m}`).join(", ")})`}return""}function qi(e,t){let n=e.scenario.claim,q=X5(e),r=e.verdict==="held"&&e.scenario.claim!==null?" It didn't happen.":"",s=[`# ${q[0].toUpperCase()}${q.slice(1)}: ${e.scenario.title}${r}`,"",Q5(e),...Z5(e,t),...e.note?["",e.note]:[]];return n&&(s.push("",e.verdict==="broken"?"## How to see it yourself":"## The scenario",`- Start from: ${n.startingState}`),n.entryPoint&&s.push(`- Go in through: ${n.entryPoint}`),s.push(`- Then: ${n.trigger}`,`- What goes wrong: ${n.wrongOutcome}`),n.correctBehaviour&&s.push(`- What should happen: ${n.correctBehaviour}`)),e.reproduction&&(s.push("","## The check's own steps",...e.reproduction.steps.map((o,i)=>`${i+1}. ${o}`),`Look for: ${e.reproduction.observe}`),e.reproduction.files.length&&s.push(`Canary keeps these scripts with the rest of the evidence: ${e.reproduction.files.join(", ")}.`)),e.ranOn&&s.push("","## Ran on",`${e.ranOn.environment.replace(/[^.!?]$/,"$&.")} Commit ${e.ranOn.commit}${e.ranOn.uncommitted?" with uncommitted changes":""}${e.ranOn.tree?`, snapshot ${e.ranOn.tree}`:""}.`),`${s.join(`
|
|
3290
3320
|
`)}
|
|
3291
|
-
`}function
|
|
3292
|
-
`);case"result":{let q=N(s1(e.runId),"results",`${e.record.jobId}.json`);Ht(ge(q),{recursive:!0}),
|
|
3293
|
-
`);let r=q.replace(/\.json$/,".md");if(
|
|
3294
|
-
`)}case"report":{let q=new Map;for(let l of e.finished)q.set(
|
|
3321
|
+
`}function V0(e,t,n){let q=e.jobId?`the check ${JSON.stringify(n.get(e.jobId)??e.jobId)}`:`setting up batch ${e.batchId}`,r=Math.round((Date.now()-Date.parse(e.askedAt))/G1);return`${t?`Reminder (asked ${r} min ago, its checks are stopped until it is answered): `:""}Canary question ${e.id}. Answer with: canary jobs answer ${e.id} "<answer>". Pass on what the user says as soon as they say it, even when it settles only part or asks something back: the verifier reads nothing else. From ${e.verifier}, about ${q}: ${JSON.stringify(e.text)}`}var iv=4*G1;async function av(){let e=C1(),t=v2(),n=ql(e),q=_t();Ae(e,v=>({...v,owner:t??v.owner??null}));let r=v=>te(e).runs[v]?.checkout??q,s=new Map,o=new Map,i={runs:[]},a=0,l=null,c=!1,h=async v=>{try{let w=await v();return c&&A("Canary: reachable again."),l=null,c=!1,w}catch(w){if(!De(w))throw w;return l??=Date.now(),!c&&Date.now()-l>Y5&&(c=!0,A("Canary: can't reach Canary right now; still trying.")),null}},d=async()=>{let v=await h(()=>Or(e));if(!v)return!1;i=v,a=Date.now();for(let w of v.runs){o.set(w.runId,w.code.treeHash);for(let P of[...w.batches.flatMap(V=>V.jobs),...w.computer??[]])s.set(P.jobId,P.title)}return Ae(e,w=>{for(let P of v.runs)w.runs[P.runId]??={checkout:q};return w}),!0};for(;!await d();)await ct(O2);J0(i.runs.map(v=>r(v.runId)));let m=new Set,u=new Map,p=new Map,f=new Map,k=!1,x=async v=>{if(!k){k=!0;try{for(let[w,P]of[...p]){let V=f.get(w)??Wt;if(!v&&Date.now()-P<V)continue;p.delete(w);let J1=X().find(R=>R.batchId===w&&R.sessionId===e&&!R.left);if(!J1)continue;let T1=await Ft(J1),o1=f.has(w)?"finished its setup":"cleaned up";Dt(`Canary: the verifier for batch ${w} hadn't ${o1} ${Math.round(V/G1)} minutes after the batch ended, so Canary stopped what it had started and removed its files. Stop that verifier with TaskStop if it is still running: it has nothing left to do.${T1.length?` Left in place: ${T1.join("; ")}`:" Nothing in this for the user."}`)}}finally{k=!1}}},y=v=>ec(v,i),b=!1,z=async()=>{if(!b){b=!0;try{for(let v of X().filter(w=>w.sessionId===e&&w.claimed&&!w.ended)){let w=e0(v.batchId);w&&await cg(v,w)}}finally{b=!1}}},C=0,I=async()=>{let v=new Map;for(let w of X().filter(P=>P.sessionId===e))v.set(w.runId,[...v.get(w.runId)??[],w.batchId]);for(let[w,P]of v){let V=pr(e,P);V.length>0&&await i1(`/cli/jobs/runs/${w}/setups`,{session:e,method:"POST",json:{setups:V}}).catch(()=>{})}};for(let v of de(V1(e)).filter(y))u.set(v.path,Date.now()),Dt(V0(v,!0,s));let S=setInterval(()=>{if(n()){for(let v of de(V1(e)).filter(y)){let w=u.get(v.path);w!==void 0&&Date.now()-w<iv||(u.set(v.path,Date.now()),Dt(V0(v,w!==void 0,s)))}x(!1),z(),Date.now()-C>=mr&&(C=Date.now(),I());for(let v of Tn(e)){let w=i.runs.flatMap(P=>P.batches).find(P=>P.batchId===v.batchId);if(!w||w.state!=="queued"){ot(v.batchId);continue}!In(rt(v.checkout))||An(v.checkout)||(ot(v.batchId),Dt(`Canary: a verifier on this machine has finished, so batch ${v.batchId} can start: start its verifier now.`))}for(let v of i.runs.flatMap(w=>w.batches))for(let w of $e(v.batchId)){let P=Nn(w);!P||m.has(w)||(m.add(w),Dt(`Canary: a check is waiting for the user to approve a command, because ${P}. Tell them so in a line now: the approval prompt itself doesn't say why they are asked.`))}}},2e3);try{for(;;){if(!n())return A("Canary: this listener was replaced by a newer one.");if(t&&!u2(t))return A("Canary: the Claude Code session ended; this listener stops.");let v=te(e).cursors,w=Object.entries(v).map(([T,D])=>`${T}:${D}`).join(","),P=Date.now(),V=await h(()=>i1(`/cli/jobs/events${w?`?cursors=${w}`:""}`,{session:e,timeoutMs:l0}));if(!V){await ct(O2);continue}if(!n())return A("Canary: this listener was replaced by a newer one.");let J1=0,T1=0,o1=V.events.filter(T=>T.type==="jobs");o1.length&&(await d(),J0(o1.map(T=>r(T.runId))),[...new Set(o1.map(T=>r(T.runId)))].some(T=>d0(T))&&Dt(lv));for(let T of V.events){if(T.type==="wait_over"&&T.batchId&&$t(V1(e),T.batchId,T.jobId),T.type==="batch_ended"&&T.batchId){let J=T.batchId;p.set(J,Date.now());let q1=X().find(Y1=>Y1.batchId===J&&Y1.sessionId===e);T.reason==="set_aside"&&f.set(J,(q1?.setupMinutes??30)*G1),q1&&Jn([J],(f.get(J)??Wt)+3e4)}let D=hv(T,s);D&&Dt(D),T.type==="result"&&J1++,T.type==="report"&&T.final&&(T1++,Vn(T.runId)||Bt(N(s1(T.runId),"source.bundle"),{force:!0}))}Ae(e,T=>{for(let[D,J]of Object.entries(V.cursors))T.cursors[D]=Math.max(T.cursors[D]??0,J);return T});for(let{runId:T}of V1(e))er(T);J1>0&&await cv(V.events,o,r);let R=V.events.length===0,M=R&&Date.now()-P<O2;if(M&&await ct(O2),(T1>0||M||R&&Date.now()-a>2*G1)&&await d(),i.runs.length===0&&(R||T1>0)){let T=()=>[...p].filter(([D])=>X().some(J=>J.batchId===D&&J.sessionId===e&&!J.left));for(;T().some(([,D])=>Date.now()-D<Wt);)await ct(O2);if(await x(!0),!n())return A("Canary: this listener was replaced by a newer one.");if(await d(),i.runs.length>0)continue;return A(T1>0?"Canary: every check for this session has finished.":"Canary: no open checks for this session.")}}}finally{clearInterval(S)}}var lv="Canary: before any verifier starts, the user has a choice to make for this repository. Run canary jobs list now: it prints the exact question to ask them with the question tool.";function ec(e,t){return e.status==="open"&&t.runs.some(n=>n.runId===e.runId&&n.batches.some(q=>q.batchId===e.batchId&&q.state!=="ended"))}function hv(e,t){let n=q=>q?JSON.stringify(t.get(q)??q):"";switch(e.type){case"jobs":return e.batches.map(q=>{let r=[`Canary: ${q.afterError?"checks going once more":q.retried?"checks tried again":"new checks"} in run ${E2(e.runId)}, batch ${q.batchId} (${q.environment}): ${q.jobs.map(s=>JSON.stringify(s.title)).join("; ")}.`];return q.afterError?r.push("Canary hit an internal error with them and tries them once more: start a verifier for this batch as for any other."):q.retried&&r.push("They couldn't run or were stopped before, or hadn't started when the first result went out, and go at the user's word: start a verifier for this batch as for any other, and their results replace any earlier ones."),q.movedFrom&&r.push(`They moved here from batch ${q.movedFrom}, whose time ran out before its verifier could start them: start a verifier for this batch as for any other.`),q.questions.length&&r.push(`Questions to settle first: ${Cr(q.questions)}`),q.permissions.length&&r.push(`Access to ask for: ${Cr(q.permissions)}`),r.join(" ")}).join(`
|
|
3322
|
+
`);case"result":{let q=N(s1(e.runId),"results",`${e.record.jobId}.json`);Ht(ge(q),{recursive:!0}),Bn(q,JSON.stringify(e.record,null,2)+`
|
|
3323
|
+
`);let r=q.replace(/\.json$/,".md");if(Bn(r,qi(e.record,e.runId)),e.record.blockedReason?.kind==="stopped_by_user"||e.record.blockedReason?.kind==="moved")return null;let s=e.record.startingStateRuledOut?" (its starting state can't arise in this code)":e.record.shownOnStandIn?` (shown on ${e.record.shownOnStandIn}, standing in for the real thing that decides the outcome)`:e.record.notShownOn?` (shown on Canary's own copy of the code, not on ${e.record.notShownOn}, which wasn't checked)`:"";return[`Canary result: ${ti(e.record.verdict)}${s}. Check: ${JSON.stringify(e.record.scenario.title)}. Full record: ${r} (print it with canary jobs record ${e.record.jobId})`,Q5(e.record),...Z5(e.record,e.runId),...e.record.note?[`Note: ${e.record.note}`]:[],...e.record.verdict==="blocked"?[`It can be tried again in this run, if the user wants${rv.includes(e.record.blockedReason?.kind??"")?", once what it lacked is in place":""}: canary jobs retry ${e.runId} ${e.record.jobId}.${G0(e.runId)}`]:[]].join(`
|
|
3324
|
+
`)}case"report":{let q=new Map;for(let l of e.finished)q.set(Hn(e.runId,l),(q.get(Hn(e.runId,l))??0)+1);let r=[...q].map(([l,c])=>`${l} ${c}`).join(", ")||"none yet";if(!e.final)return null;if(e.finished.length===0)return`Canary final report for run ${E2(e.runId)}: no part of this run called for a check.`;let s=e.finished.map(l=>`${JSON.stringify(l.title)}: ${Hn(e.runId,l)}`).join("; "),o=new Map;for(let l of e.finished.filter(c=>c.verdict==="broken")){let c=Y(N(s1(e.runId),"results",`${l.jobId}.json`))?.whereToLook?.replace(/:\d[\d-]*$/,"");c&&o.set(c,(o.get(c)??0)+1)}let i=o.size?`
|
|
3295
3325
|
Where the confirmed problems point: ${[...o].map(([l,c])=>`${l} (${c})`).join(", ")}.`:"",a=e.finished.some(l=>l.verdict==="blocked")?`
|
|
3296
|
-
The ones that couldn't run, were stopped or weren't tried yet can be tried again in this run, if the user wants (one that lacked something, once it is in place): canary jobs retry ${e.runId}, naming checks after it to try only those.${
|
|
3326
|
+
The ones that couldn't run, were stopped or weren't tried yet can be tried again in this run, if the user wants (one that lacked something, once it is in place): canary jobs retry ${e.runId}, naming checks after it to try only those.${G0(e.runId)}`:"";return`Canary final report for run ${E2(e.runId)}: all ${e.finished.length} checks have ended: ${r}. Each check's full record is in ${N(s1(e.runId),"results")}.
|
|
3297
3327
|
They were: ${s}.${i}${a}`}case"batch_ended":return null;case"wait_over":{let q=e.jobId?`the check ${n(e.jobId)}`:`the batch ${e.batchId}'s checks not yet run`;if(e.approval){let r=e.jobId?"Tell the user, and start a fresh verifier only once they say to go ahead and canary jobs list still shows checks left in that batch.":"Tell the user; nothing is left in that batch for a verifier to start.";return`Canary: an approval prompt from the verifier for batch ${e.batchId} went unanswered too long, so ${q} timed out; it can be re-checked. Stop that verifier and run canary jobs finish ${e.batchId} --give-back. ${r}`}return`Canary: no answer in time, so ${q} timed out; it can be re-checked. Keep a late answer in canary.md.`}case"verifier_unresponsive":return`Canary: the verifier for batch ${e.batchId} stopped responding, perhaps waiting on an approval. Stop it and run canary jobs finish ${e.batchId}. ${e.requeued===!1?"Tell the user; nothing is left in that batch for a verifier to start.":"Tell the user, and start a fresh verifier only once they say to go ahead."}`;case"setup":return`Canary: an update for the user on checks they asked to prove; show it to them as it is:
|
|
3298
|
-
${e.say}`}}async function cv(e,t,n){let q=[...new Set(e.filter(r=>r.type==="result").map(r=>r.runId))];try{for(let r of q)if(t.has(r)&&t.get(r)!==(await ln(n(r),{likeClone:!0})).treeHash)return A("Canary: your files have changed since these checks were requested; their results are for the code as it was then.")}catch{}}var H5=new Set;function V0(e){for(let t of new Set(e))if(k1(t))try{let n=Zq(t);if(H5.has(n.dir))continue;H5.add(n.dir),A(`Canary: this repository's notes for Canary are in ${n.canaryMd}, and its test secrets in ${n.secrets}.`)}catch(n){n instanceof E&&A(`Canary: ${n.message} ${n.fix??""}`.trim())}}async function dv(){let e=C1(),t=await Or(e),n=new Map(V1(e).map(a=>[a.runId,a.checkout]));V0(t.runs.flatMap(a=>n.get(a.runId)??[]));let q=new Map(X().map(a=>[Yo(a.key),Z0(a.batchId)])),r=a=>a===null?"nobody":q.get(a)?`${q.get(a)} on this machine`:"another verifier",s=de(V1(e)).filter(a=>Q5(a,t));for(let{runId:a}of V1(e).filter(({runId:l})=>!t.runs.some(c=>c.runId===l))){let l=J5(a);l.length&&A(`Run ${a} has ended; ${l.length} of its checks couldn't run, were stopped or weren't tried yet (${l.join("; ")}), and can be tried again in it, if the user wants: canary jobs retry ${a}, naming checks after it to try only those.${U0(a)}`)}if(t.runs.length===0){V1(e).some(({runId:a})=>Gn(a))||A("No open Canary checks for this session.");return}for(let a of t.runs){A(`Run ${a.runId} (${a.kind}, ${a.coverage.run} of ${a.coverage.considered} finished)`);for(let l of a.batches){let c=$e(l.batchId),h=c.map(En).find(p=>p),d=c.length?`; its verifier is waiting on an approval prompt${h?`, which the user is asked about because ${h}`:""}`:"";A(` Batch ${l.batchId} (${l.environment}): ${l.state}, held by ${r(l.holder)}${d}`);let m=l.state==="ended"?void 0:X().find(p=>p.batchId===l.batchId),u=m?(()=>{try{return j2(c1(l.batchId)).birthtimeMs}catch{return null}})():null;if(m&&u!==null){let p=S=>Math.max(0,Math.round((Date.now()-S)/G1)),f=kh(l.batchId,3),k=Ih(l.batchId),x=l.jobs.every(S=>S.state==="queued")?`setting up for ${p(u)} min; `:"",y=k?`set up in ${Math.max(0,Math.round((Date.parse(k)-u)/G1))} min; `:"",b=l.jobs.find(S=>S.state==="queued"),z=l.jobs.some(S=>["running","waiting","stopping","proof"].includes(S.state)),C=!x&&!z&&b?`between checks, the next in order being ${JSON.stringify(b.title)}; `:"",I=f.map(S=>`${S.step} (${S.ended==="background"?"started in the background":S.ended==="running"?"still running":S.ended==="ran"?"ran":S.ended==="failed"?"failed":S.ended==="blocked"?"blocked by Claude Code's auto mode":"didn't run"}, ${p(Date.parse(S.at))} min ago)`);A(` ${x}${y}${C}${I.length?`its verifier's latest steps, oldest first: ${I.join("; ")}`:"no step recorded yet"}`)}l.state==="queued"&&l.questions.length&&A(` Questions to settle first: ${Cr(l.questions)}`),l.state==="queued"&&l.permissions.length&&A(` Access to ask for: ${Cr(l.permissions)}`);for(let p of l.jobs)A(` ${p.jobId} ${p.state}${p.verdict?` (${Wn(a.runId,p)})`:""} ${p.title}`)}if(a.computer?.length){A(" On Canary's computer:");let l=h=>Math.max(0,Math.round((Date.now()-Date.parse(h))/G1)),c=h=>h.map(d=>`${d.step} (${l(d.at)} min ago)`).join("; ");for(let h of a.computerSandboxes??[])h.readyAt?A(` Sandbox ${h.sandbox}: set up in ${Math.max(0,Math.round((Date.parse(h.readyAt)-Date.parse(h.since))/G1))} min`):A(` Sandbox ${h.sandbox}: setting up for ${l(h.since)} min; ${h.steps.length?`its latest steps, oldest first: ${c(h.steps)}`:"no step reported yet"}`);for(let h of a.computer)A(` ${h.jobId} ${h.state}${h.verdict?` (${Wn(a.runId,h)})`:""} ${h.title}${h.sandbox?` (sandbox ${h.sandbox})`:""}`),(h.state==="running"||h.state==="proof")&&h.steps?.length&&A(` its latest steps, oldest first: ${c(h.steps)}`)}}let o=new Map(t.runs.flatMap(a=>[...a.batches.flatMap(l=>l.jobs),...a.computer??[]].map(l=>[l.jobId,l.title])));for(let a of s)A(G0(a,!0,o));let i;for(let a of new Set(t.runs.flatMap(l=>n.get(l.runId)??[]))){for(let c of dh(a))A(c);let l=i?null:c0(a);l&&(A(l),i=a)}Ae(e,a=>({...a,asking:i}))}var J0=e=>e instanceof E||e instanceof L&&!!e.code&&!De(e),E2=45e3,Y0=e=>String(e?.code??""),K0=e=>["ENOSPC","EDQUOT"].includes(Y0(e))||/No space left on device|Disk quota exceeded/.test(String(e?.message));function Z5(e){if(["EACCES","EPERM","EROFS"].includes(Y0(e)))return Y0(e);let t=/Permission denied|Operation not permitted|Read-only file system/.exec(String(e?.message))?.[0];return t==="Permission denied"?"EACCES":t==="Operation not permitted"?"EPERM":t?"EROFS":null}async function uv(e){let t=C1(),q=(await U1(()=>Or(t))).runs.find(o=>o.batches.some(i=>i.batchId===e)),r=q?.batches.find(o=>o.batchId===e);if(!q||!r)throw new E("not_found","No such batch among this session's open checks.","Use a batch id the listener or canary jobs list printed.");if(r.state==="ended")throw new E("batch_ended","This batch has ended.");let s={batchId:e,session:t,receipt:null,resuming:!1,folder:!1,state:null,copied:!1,claimSent:!1};try{await mv(q,s)}catch(o){await pv(s,o)}}async function mv(e,t){let{batchId:n,session:q}=t,r=e.batches.find(z=>z.batchId===n),s=te(q).runs[e.runId]?.checkout??_t(),o=k1(N(c1(n),"state.json"))?st(n):null;o&&!o.claimed&&o.sessionId===q&&(!o.taker||qt(o.taker)==="gone")&&Object.assign(t,{resuming:!0,folder:!0,state:o});let i=Zq(s),a=p2(Et(s)),l=t.receipt=Y(N(s1(e.runId),"source.json")),c=N(s1(e.runId),"source.bundle");if(!l||!k1(c))throw new Error("the run's snapshot isn't on this machine");let h=z=>Vo(l.bytes,k1(N(u1({repoFolder:a,slot:z}),".git"))),d,m={pid:process.pid,startedAt:Oe(process.pid)??Date.now()};if(t.resuming){let z=h(o.slot);z&&await X0(n,q,z,!0),d=t.state=Ie(n,C=>{C.taker=m,C.owner=v2()??C.owner})}else{if(Cn(s))throw In(n,q,s),new E("machine_busy","A verifier on this machine is still setting this app up.","End here with this line. The coding agent's listener says when it has finished; it starts this batch's verifier then, from the setup it kept.");hl(n),t.folder=!0;let z=rt(s),C=dl(n,z);if(C===null)throw In(n,q,s),new E("machine_busy",`${z} verifiers are already working on this machine.`,"End here with this line. The coding agent's listener says when one of them has finished; it starts this batch's verifier then.");let I=h(C);I&&await X0(n,q,I,!1),d={batchId:n,runId:e.runId,sessionId:q,checkout:s,repoFolder:a,key:Uf(24).toString("base64url"),owner:v2(),slot:C,ports:await bl(n,C),code:e.code,jobs:r.jobs.map(S=>({jobId:S.jobId,title:S.title})),claimed:!1,taker:m,stopped:{},finalSent:[],proofs:{},cursor:0,processes:[]},Sn(d),t.state=d}let u=u1(d),p=await Xh(s,c,l,e.code.treeHash,u);t.copied=!0,ll(d),ot(n);let f=hr(s),k=f&&{use:f.use,at:f.at,placed:f.use?Qh(s,u,f.files):[]};Ht(w2(n),{recursive:!0});let x=wv(d,i,u);t.claimSent=!0;let y=await U1(()=>i1(`/cli/jobs/batches/${n}/claim`,{session:q,batchKey:d.key,json:{treeHash:e.code.treeHash}}));d=t.state=Ie(n,z=>{z.claimed=!0,z.cursor=y.cursor,z.code=y.code,z.warm=p,z.keptScripts=x.scripts.map(C=>`${A1}/${C.name}`),z.jobMinutes=y.limits.jobMinutes,z.setupMinutes=y.limits.batchSetupMinutes,z.targets=Object.fromEntries(y.jobs.flatMap(({job:C})=>C.scenario.target?.address?[[C.id,C.scenario.target.address]]:[]))}),Tn($e(n));let b=new Set(y.jobs.map(({job:z})=>z.id));for(let z of X().filter(C=>C.batchId!==n&&C.jobs.some(I=>b.has(I.jobId))))Ie(z.batchId,C=>{C.jobs=C.jobs.filter(I=>!b.has(I.jobId))});Ae(q,z=>(z.runs[e.runId]??={checkout:s},z)),Sv(y,d,i,await r5(u),p,k,x,Y(N(s1(e.runId),g2)))}async function pv(e,t){let{batchId:n,session:q}=e,r=e.state?.claimed===!0,s=e.resuming||e.claimSent,o=(h=!1)=>{!e.folder||r&&!h||(Bt(c1(n),{recursive:!0,force:!0}),nr(n))};if(J0(t))throw(!s||e.claimSent)&&o(),t;if(e.claimSent&&K0(t))throw new E("not_enough_disk","This machine ran out of disk while Canary set up this batch.",`Tell the user, then hand the batch back: canary jobs finish ${n} --give-back`);let i=e.state&&!e.copied&&!e.claimSent?u1(e.state):null,a=i&&e.receipt?await q5(i,e.receipt.headSha):null;if(e.receipt&&!e.claimSent&&(K0(t)||a!==null&&a.bytes-a.onDisk>Jo())){i&&Bt(i,{recursive:!0,force:!0}),e.resuming||o();let h=Vo(e.receipt.bytes,!!e.state&&e.copied,a?.bytes??null);throw h&&await X0(n,q,h,e.resuming),new E("not_enough_disk","This machine ran out of disk while Canary set up this batch's copy of the code.",e.resuming?`Tell the user, then hand the batch back: canary jobs finish ${n} --give-back`:"Tell the user. Take the batch again once more disk is free.")}let l=Z5(t);if(l&&!e.claimSent){if(!e.resuming)try{o()}catch{}throw Qq(l)}if(t instanceof L&&De(t)&&t.status<500)throw s?new E("take_unconfirmed","Couldn't confirm the take with Canary.",`Run canary jobs take ${n} again: it picks the same take back up. Or hand it back: canary jobs finish ${n} --give-back`):(o(),t);let c;try{c=await Nn(q,{batchId:n,batchKey:e.state?.key},t)}catch(h){throw J0(h)?(r||o(),h):r?new E("internal_error",at,`Hand the batch back once Canary can be reached: canary jobs finish ${n} --give-back`):s?new E("internal_error",at,`Run canary jobs take ${n} again: it picks the same take back up. Or hand it back: canary jobs finish ${n} --give-back`):(o(),new E("internal_error",at,`Run canary jobs take ${n} again.`))}throw o(!0),new E("internal_error",c.requeued?"Canary hit an internal error setting up this batch, so it took the batch back to try its checks once more: the coding agent's listener announces them again for a fresh verifier.":"Canary hit an internal error setting up this batch, so its checks ended; they can be tried again.","End here with this line.")}async function X0(e,t,n,q){if(q)throw new E("not_enough_disk",xn(n),`Tell the user how much space the checks need, then hand the batch back: canary jobs finish ${e} --give-back`);if(X().some(o=>o.sessionId===t&&!o.left))throw new E("not_enough_disk",`${xn(n)} This session's other Canary checks are using some of it.`,"Start this batch's verifier again once they finish.");let r=n;throw await U1(()=>i1(`/cli/jobs/batches/${e}/decline`,{session:t,json:r}).then(()=>!0)).catch(()=>!1)?new E("machine_limit",`${xn(n)} So Canary has ended this run's waiting checks as blocked.`,"End here with this line. The results reach the coding agent's listener; they can be re-checked once that much is free."):new E("not_enough_disk",xn(n),"Tell the user how much space the checks need. Take the batch again once they have freed some.")}var A1="canary-scripts",fv=new RegExp(`${A1}/([\\w.-]+(?:/[\\w.-]+)*\\.(?:sh|bash|rb|py|mjs|cjs|js|ts))\\b`,"g");function ec(e){let t=[...e.matchAll(/^\s*(?:export\s+)?(\w+)=.*\bdocker\b/gm)].map(q=>`|"?\\$\\{?${q[1]}\\}?"?`).join(""),n=new RegExp(`(?:\\bdocker${t})\\s+(?:container\\s+)?(?:run|create)\\b`);return e.replace(/\\\n/g," ").split(`
|
|
3299
|
-
`).find(q=>n.test(q)&&!/--label\b|CANARY_DOCKER_LABEL/.test(q))}function vv(e,t){let n=e.map(q=>q.name).filter(q=>
|
|
3300
|
-
`)),Gf(N(n,".git","info","exclude"),`/${A1}/${
|
|
3301
|
-
`);let s=Y(N(t.scripts,Ir))??{},o=[];for(let[i,a]of Object.entries(s))!yv.test(i)||i.split("/").includes("..")||k1(N(q,i))||!k1(N(t.scripts,i))||(Ht(ge(N(q,i)),{recursive:!0}),Jf(N(t.scripts,i),N(q,i)),o.push({name:i,...a}));return{values:r,scripts:o}}function bv(e){return e===void 0?"":e?" It carries changes compared with its main branch.":" It is the same as its main branch, so the checks look at the code as it is now."}function kv(e){return{broken:"the check failed",not_reproduced:"the check ran but couldn't make the problem happen",inconclusive:"the check ran but didn't settle it",blocked:"the check couldn't run"}[e]}function zv(e){if(!e)return[];let t={local:"- reachable only from the user's machine (a local or private address)",public:"- reachable from the internet (a public address)"},n={person:"- the address is in the user's own words",agent:"- the address comes only from the user's coding agent, not from their own words"};return["Running target (the scenario is about this running instance, not a copy of the code):",`- name: ${e.name}`,`- address: ${e.address??"none given"}`,e.reach?t[e.reach]:"",e.addressFrom?n[e.addressFrom]:"",e.quote?`- the user's words naming it: "${e.quote}"`:""].filter(Boolean)}function xv(e){return e.addressFrom==="person"?`The user's own words name this address, which clears reading it and creating, changing and removing this job's own test data there. Load, other data, and anything that contacts real people or spends money still need their clearance under "Targets you've cleared" in canary.md.`:`Using it needs the user's clearance under "Targets you've cleared" in canary.md.`}function Sv(e,t,n,q,r,s,o,i=null){let a=t.batchId,l=e.limits,c=d=>i&&d>=i.at?"during this run":`on ${d.slice(0,10)}${i?", before this run":""}`;if(A(`You hold batch ${a} (run ${e.runId}) as ${
|
|
3328
|
+
${e.say}`}}async function cv(e,t,n){let q=[...new Set(e.filter(r=>r.type==="result").map(r=>r.runId))];try{for(let r of q)if(t.has(r)&&t.get(r)!==(await hn(n(r),{likeClone:!0})).treeHash)return A("Canary: your files have changed since these checks were requested; their results are for the code as it was then.")}catch{}}var _5=new Set;function J0(e){for(let t of new Set(e))if(k1(t))try{let n=g2(t);if(_5.has(n.dir))continue;_5.add(n.dir),A(`Canary: this repository's notes for Canary are in ${n.canaryMd}, and its test secrets in ${n.secrets}.`)}catch(n){n instanceof E&&A(`Canary: ${n.message} ${n.fix??""}`.trim())}}async function dv(){let e=C1(),t=await Or(e),n=new Map(V1(e).map(a=>[a.runId,a.checkout]));J0(t.runs.flatMap(a=>n.get(a.runId)??[]));let q=new Map(X().map(a=>[Yo(a.key),ei(a.batchId)])),r=a=>a===null?"nobody":q.get(a)?`${q.get(a)} on this machine`:"another verifier",s=de(V1(e)).filter(a=>ec(a,t));for(let{runId:a}of V1(e).filter(({runId:l})=>!t.runs.some(c=>c.runId===l))){let l=K5(a);l.length&&A(`Run ${a} has ended; ${l.length} of its checks couldn't run, were stopped or weren't tried yet (${l.join("; ")}), and can be tried again in it, if the user wants: canary jobs retry ${a}, naming checks after it to try only those.${G0(a)}`)}if(t.runs.length===0){V1(e).some(({runId:a})=>Vn(a))||A("No open Canary checks for this session.");return}for(let a of t.runs){A(`Run ${a.runId} (${a.kind}, ${a.coverage.run} of ${a.coverage.considered} finished)`);for(let l of a.batches){let c=$e(l.batchId),h=c.map(Nn).find(p=>p),d=c.length?`; its verifier is waiting on an approval prompt${h?`, which the user is asked about because ${h}`:""}`:"";A(` Batch ${l.batchId} (${l.environment}): ${l.state}, held by ${r(l.holder)}${d}`);let m=l.state==="ended"?void 0:X().find(p=>p.batchId===l.batchId),u=m?(()=>{try{return M2(c1(l.batchId)).birthtimeMs}catch{return null}})():null;if(m&&u!==null){let p=S=>Math.max(0,Math.round((Date.now()-S)/G1)),f=xh(l.batchId,3),k=Th(l.batchId),x=l.jobs.every(S=>S.state==="queued")?`setting up for ${p(u)} min; `:"",y=k?`set up in ${Math.max(0,Math.round((Date.parse(k)-u)/G1))} min; `:"",b=l.jobs.find(S=>S.state==="queued"),z=l.jobs.some(S=>["running","waiting","stopping","proof"].includes(S.state)),C=!x&&!z&&b?`between checks, the next in order being ${JSON.stringify(b.title)}; `:"",I=f.map(S=>`${S.step} (${S.ended==="background"?"started in the background":S.ended==="running"?"still running":S.ended==="ran"?"ran":S.ended==="failed"?"failed":S.ended==="blocked"?"blocked by Claude Code's auto mode":"didn't run"}, ${p(Date.parse(S.at))} min ago)`);A(` ${x}${y}${C}${I.length?`its verifier's latest steps, oldest first: ${I.join("; ")}`:"no step recorded yet"}`)}l.state==="queued"&&l.questions.length&&A(` Questions to settle first: ${Cr(l.questions)}`),l.state==="queued"&&l.permissions.length&&A(` Access to ask for: ${Cr(l.permissions)}`);for(let p of l.jobs)A(` ${p.jobId} ${p.state}${p.verdict?` (${Hn(a.runId,p)})`:""} ${p.title}`)}if(a.computer?.length){A(" On Canary's computer:");let l=h=>Math.max(0,Math.round((Date.now()-Date.parse(h))/G1)),c=h=>h.map(d=>`${d.step} (${l(d.at)} min ago)`).join("; ");for(let h of a.computerSandboxes??[])h.readyAt?A(` Sandbox ${h.sandbox}: set up in ${Math.max(0,Math.round((Date.parse(h.readyAt)-Date.parse(h.since))/G1))} min`):A(` Sandbox ${h.sandbox}: setting up for ${l(h.since)} min; ${h.steps.length?`its latest steps, oldest first: ${c(h.steps)}`:"no step reported yet"}`);for(let h of a.computer)A(` ${h.jobId} ${h.state}${h.verdict?` (${Hn(a.runId,h)})`:""} ${h.title}${h.sandbox?` (sandbox ${h.sandbox})`:""}`),(h.state==="running"||h.state==="proof")&&h.steps?.length&&A(` its latest steps, oldest first: ${c(h.steps)}`)}}let o=new Map(t.runs.flatMap(a=>[...a.batches.flatMap(l=>l.jobs),...a.computer??[]].map(l=>[l.jobId,l.title])));for(let a of s)A(V0(a,!0,o));let i;for(let a of new Set(t.runs.flatMap(l=>n.get(l.runId)??[]))){for(let c of mh(a))A(c);let l=i?null:d0(a);l&&(A(l),i=a)}Ae(e,a=>({...a,asking:i}))}var Y0=e=>e instanceof E||e instanceof L&&!!e.code&&!De(e),N2=45e3,K0=e=>String(e?.code??""),X0=e=>["ENOSPC","EDQUOT"].includes(K0(e))||/No space left on device|Disk quota exceeded/.test(String(e?.message));function tc(e){if(["EACCES","EPERM","EROFS"].includes(K0(e)))return K0(e);let t=/Permission denied|Operation not permitted|Read-only file system/.exec(String(e?.message))?.[0];return t==="Permission denied"?"EACCES":t==="Operation not permitted"?"EPERM":t?"EROFS":null}async function uv(e){let t=C1(),q=(await U1(()=>Or(t))).runs.find(o=>o.batches.some(i=>i.batchId===e)),r=q?.batches.find(o=>o.batchId===e);if(!q||!r)throw new E("not_found","No such batch among this session's open checks.","Use a batch id the listener or canary jobs list printed.");if(r.state==="ended")throw new E("batch_ended","This batch has ended.");let s={batchId:e,session:t,receipt:null,resuming:!1,folder:!1,state:null,copied:!1,claimSent:!1};try{await mv(q,s)}catch(o){await pv(s,o)}}async function mv(e,t){let{batchId:n,session:q}=t,r=e.batches.find(z=>z.batchId===n),s=te(q).runs[e.runId]?.checkout??_t(),o=k1(N(c1(n),"state.json"))?st(n):null;o&&!o.claimed&&o.sessionId===q&&(!o.taker||qt(o.taker)==="gone")&&Object.assign(t,{resuming:!0,folder:!0,state:o});let i=g2(s),a=p2(Et(s)),l=t.receipt=Y(N(s1(e.runId),"source.json")),c=N(s1(e.runId),"source.bundle");if(!l||!k1(c))throw new Error("the run's snapshot isn't on this machine");let h=z=>Vo(l.bytes,k1(N(u1({repoFolder:a,slot:z}),".git"))),d,m={pid:process.pid,startedAt:Oe(process.pid)??Date.now()};if(t.resuming){let z=h(o.slot);z&&await Q0(n,q,z,!0),d=t.state=Ie(n,C=>{C.taker=m,C.owner=v2()??C.owner})}else{if(An(s))throw Rn(n,q,s),new E("machine_busy","A verifier on this machine is still setting this app up.","End here with this line. The coding agent's listener says when it has finished; it starts this batch's verifier then, from the setup it kept.");dl(n),t.folder=!0;let z=rt(s),C=ml(n,z);if(C===null)throw Rn(n,q,s),new E("machine_busy",`${z} verifiers are already working on this machine.`,"End here with this line. The coding agent's listener says when one of them has finished; it starts this batch's verifier then.");let I=h(C);I&&await Q0(n,q,I,!1),d={batchId:n,runId:e.runId,sessionId:q,checkout:s,repoFolder:a,key:Uf(24).toString("base64url"),owner:v2(),slot:C,ports:await zl(n,C),code:e.code,jobs:r.jobs.map(S=>({jobId:S.jobId,title:S.title})),claimed:!1,taker:m,stopped:{},finalSent:[],proofs:{},cursor:0,processes:[]},Cn(d),t.state=d}let u=u1(d),p=await Zh(s,c,l,e.code.treeHash,u);t.copied=!0,cl(d),ot(n);let f=hr(s),k=f&&{use:f.use,at:f.at,placed:f.use?e5(s,u,f.files):[]};Ht(b2(n),{recursive:!0});let x=wv(d,i,u);t.claimSent=!0;let y=await U1(()=>i1(`/cli/jobs/batches/${n}/claim`,{session:q,batchKey:d.key,json:{treeHash:e.code.treeHash}}));d=t.state=Ie(n,z=>{z.claimed=!0,z.cursor=y.cursor,z.code=y.code,z.warm=p,z.keptScripts=x.scripts.map(C=>`${A1}/${C.name}`),z.jobMinutes=y.limits.jobMinutes,z.setupMinutes=y.limits.batchSetupMinutes,z.targets=Object.fromEntries(y.jobs.flatMap(({job:C})=>C.scenario.target?.address?[[C.id,C.scenario.target.address]]:[]))}),On($e(n));let b=new Set(y.jobs.map(({job:z})=>z.id));for(let z of X().filter(C=>C.batchId!==n&&C.jobs.some(I=>b.has(I.jobId))))Ie(z.batchId,C=>{C.jobs=C.jobs.filter(I=>!b.has(I.jobId))});Ae(q,z=>(z.runs[e.runId]??={checkout:s},z)),Sv(y,d,i,await o5(u),p,k,x,Y(N(s1(e.runId),y2)))}async function pv(e,t){let{batchId:n,session:q}=e,r=e.state?.claimed===!0,s=e.resuming||e.claimSent,o=(h=!1)=>{!e.folder||r&&!h||(Bt(c1(n),{recursive:!0,force:!0}),nr(n))};if(Y0(t))throw(!s||e.claimSent)&&o(),t;if(e.claimSent&&X0(t))throw new E("not_enough_disk","This machine ran out of disk while Canary set up this batch.",`Tell the user, then hand the batch back: canary jobs finish ${n} --give-back`);let i=e.state&&!e.copied&&!e.claimSent?u1(e.state):null,a=i&&e.receipt?await s5(i,e.receipt.headSha):null;if(e.receipt&&!e.claimSent&&(X0(t)||a!==null&&a.bytes-a.onDisk>Jo())){i&&Bt(i,{recursive:!0,force:!0}),e.resuming||o();let h=Vo(e.receipt.bytes,!!e.state&&e.copied,a?.bytes??null);throw h&&await Q0(n,q,h,e.resuming),new E("not_enough_disk","This machine ran out of disk while Canary set up this batch's copy of the code.",e.resuming?`Tell the user, then hand the batch back: canary jobs finish ${n} --give-back`:"Tell the user. Take the batch again once more disk is free.")}let l=tc(t);if(l&&!e.claimSent){if(!e.resuming)try{o()}catch{}throw Zq(l)}if(t instanceof L&&De(t)&&t.status<500)throw s?new E("take_unconfirmed","Couldn't confirm the take with Canary.",`Run canary jobs take ${n} again: it picks the same take back up. Or hand it back: canary jobs finish ${n} --give-back`):(o(),t);let c;try{c=await Pn(q,{batchId:n,batchKey:e.state?.key},t)}catch(h){throw Y0(h)?(r||o(),h):r?new E("internal_error",at,`Hand the batch back once Canary can be reached: canary jobs finish ${n} --give-back`):s?new E("internal_error",at,`Run canary jobs take ${n} again: it picks the same take back up. Or hand it back: canary jobs finish ${n} --give-back`):(o(),new E("internal_error",at,`Run canary jobs take ${n} again.`))}throw o(!0),new E("internal_error",c.requeued?"Canary hit an internal error setting up this batch, so it took the batch back to try its checks once more: the coding agent's listener announces them again for a fresh verifier.":"Canary hit an internal error setting up this batch, so its checks ended; they can be tried again.","End here with this line.")}async function Q0(e,t,n,q){if(q)throw new E("not_enough_disk",Sn(n),`Tell the user how much space the checks need, then hand the batch back: canary jobs finish ${e} --give-back`);if(X().some(o=>o.sessionId===t&&!o.left))throw new E("not_enough_disk",`${Sn(n)} This session's other Canary checks are using some of it.`,"Start this batch's verifier again once they finish.");let r=n;throw await U1(()=>i1(`/cli/jobs/batches/${e}/decline`,{session:t,json:r}).then(()=>!0)).catch(()=>!1)?new E("machine_limit",`${Sn(n)} So Canary has ended this run's waiting checks as blocked.`,"End here with this line. The results reach the coding agent's listener; they can be re-checked once that much is free."):new E("not_enough_disk",Sn(n),"Tell the user how much space the checks need. Take the batch again once they have freed some.")}var A1="canary-scripts",fv=new RegExp(`${A1}/([\\w.-]+(?:/[\\w.-]+)*\\.(?:sh|bash|rb|py|mjs|cjs|js|ts))\\b`,"g");function nc(e){let t=[...e.matchAll(/^\s*(?:export\s+)?(\w+)=.*\bdocker\b/gm)].map(q=>`|"?\\$\\{?${q[1]}\\}?"?`).join(""),n=new RegExp(`(?:\\bdocker${t})\\s+(?:container\\s+)?(?:run|create)\\b`);return e.replace(/\\\n/g," ").split(`
|
|
3329
|
+
`).find(q=>n.test(q)&&!/--label\b|CANARY_DOCKER_LABEL/.test(q))}function vv(e,t){let n=e.map(q=>q.name).filter(q=>nc(Re(N(t,q),"utf8")));return n.length?` First, ${n.join(", ")} ${n.length>1?"start":"starts"} a container without this batch's label: add --label "$CANARY_DOCKER_LABEL" to it, and keep the script again once it has run clean.`:""}function gv(e){let t=N(u1(e),A1),n=ol(e.repoFolder);return[...new Set(Sh(e.batchId).flatMap(r=>[...r.matchAll(fv)].map(s=>s[1])).filter(r=>!r.split("/").includes("..")))].filter(r=>k1(N(t,r))&&!(k1(N(n,r))&&Re(N(n,r)).equals(Re(N(t,r)))))}var P2="canary-run.env",yv=/^[\w.-]+(\/[\w.-]+)*$/;function wv(e,t,n){let q=N(n,A1);Bt(q,{recursive:!0,force:!0}),Ht(q,{recursive:!0});let r=N(q,P2);Bn(r,["# This batch's own values, written by Canary at the take. A setup script reads them from here and holds none of them.",`CANARY_BATCH=${e.batchId}`,`CANARY_SHORT=${E2(e.batchId)}`,`CANARY_COPY=${n}`,`CANARY_SCRATCH=${b2(e.batchId)}`,`CANARY_PORT_FIRST=${e.ports[0]}`,`CANARY_PORT_LAST=${e.ports[1]}`,`CANARY_DOCKER_LABEL=${S2(e.batchId)}`,`CANARY_COMPOSE_PROJECT=${C2(e.batchId)}`,`CANARY_SECRETS=${t.secrets}`,""].join(`
|
|
3330
|
+
`)),Gf(N(n,".git","info","exclude"),`/${A1}/${P2}
|
|
3331
|
+
`);let s=Y(N(t.scripts,Ir))??{},o=[];for(let[i,a]of Object.entries(s))!yv.test(i)||i.split("/").includes("..")||k1(N(q,i))||!k1(N(t.scripts,i))||(Ht(ge(N(q,i)),{recursive:!0}),Jf(N(t.scripts,i),N(q,i)),o.push({name:i,...a}));return{values:r,scripts:o}}function bv(e){return e===void 0?"":e?" It carries changes compared with its main branch.":" It is the same as its main branch, so the checks look at the code as it is now."}function kv(e){return{broken:"the check failed",not_reproduced:"the check ran but couldn't make the problem happen",inconclusive:"the check ran but didn't settle it",blocked:"the check couldn't run"}[e]}function zv(e){if(!e)return[];let t={local:"- reachable only from the user's machine (a local or private address)",public:"- reachable from the internet (a public address)"},n={person:"- the address is in the user's own words",agent:"- the address comes only from the user's coding agent, not from their own words"};return["Running target (the scenario is about this running instance, not a copy of the code):",`- name: ${e.name}`,`- address: ${e.address??"none given"}`,e.reach?t[e.reach]:"",e.addressFrom?n[e.addressFrom]:"",e.quote?`- the user's words naming it: "${e.quote}"`:""].filter(Boolean)}function xv(e){return e.addressFrom==="person"?`The user's own words name this address, which clears reading it and creating, changing and removing this job's own test data there. Load, other data, and anything that contacts real people or spends money still need their clearance under "Targets you've cleared" in canary.md.`:`Using it needs the user's clearance under "Targets you've cleared" in canary.md.`}function Sv(e,t,n,q,r,s,o,i=null){let a=t.batchId,l=e.limits,c=d=>i&&d>=i.at?"during this run":`on ${d.slice(0,10)}${i?", before this run":""}`;if(A(`You hold batch ${a} (run ${e.runId}) as ${ei(a)}: ${e.batch.environment}.`),A(`Copy of the code the checks were planned on: ${u1(t)}. Work only there; it is outside the user's checkout.`),A(r?"This copy is kept between checks of this repository: an earlier check's installed dependencies and build output are still in it, and only its code was reset to this snapshot. Run the project's install and build steps anyway, since they redo only what changed; build from clean if files were deleted or renamed since; rebuild from this copy every project package an earlier check left in .canary-cache before using it; and reset any data the app keeps inside the copy.":"This copy is kept after the batch ends, so the next check of this repository reuses what you install and build in it."),A(`The code is commit ${t.code.commit.slice(0,12)}${t.code.branch?` on ${t.code.branch}`:""}${t.code.uncommitted===!1?"":", plus any uncommitted changes the user had"}.${bv(t.code.changed)} Your copy's own git commits are Canary's snapshot bookkeeping: when you name the code, name that commit, never the copy's.`),A(`Ports for this batch: ${t.ports[0]}-${t.ports[1]}. Use only these for anything you start.`),A(`Scratch files and folders, and the data folders of services you start, go in ${b2(a)}: it is removed with the batch.`),s?.use){A(s.placed.length?`The user allowed the checks to use the project's env files ${c(s.at)}. They are in your copy, at the paths the app reads them from, with the user's keys and the addresses of hosted services as they have them: ${s.placed.map(m=>m.file).join(", ")}.`:`The user allowed the checks to use the project's env files ${c(s.at)}, but none is in the checkout now.`);let d=s.placed.filter(m=>m.repointed.length);d.length&&A(`Every value in them that pointed at this machine now names ${C0}, a host that never resolves, so nothing you start can reach a service the user runs here. Have your setup script set each of these to your own services before the app starts: ${d.map(m=>`${m.file}: ${m.repointed.join(", ")}`).join("; ")}.`)}else s&&A(`The checks may not use the project's env files: the user said so ${c(s.at)}. Set the app's environment up yourself, and ask for any key a check needs.`);q.length&&A(`Submodules in your copy are empty: ${q.map(d=>`${d.path} at ${d.commit.slice(0,12)}`).join("; ")}. Fill one only if a check needs it, at that commit: from the user's checkout (${t.checkout}) when the commit is there, reading it without changing anything, otherwise by fetching. Its own uncommitted changes in the user's checkout aren't part of the snapshot.`),A(`Read first: ${n.canaryMd}. Test secrets: ${n.secrets} (canary.md names them).`);let h=i?hl(i,n.canaryMd):[];h.length&&A(`Added to the user's part of canary.md since this run began; an answer among these was given during this run:
|
|
3302
3332
|
${h.map(d=>` ${d}`).join(`
|
|
3303
|
-
`)}`),A(`This batch's own values (its id, copy, scratch folder, ports, Docker label and compose project name, the secrets file) are in ${o.values}, as NAME=value lines: a setup script reads them from there and writes none of them out.`),A(o.scripts.length?`Setup scripts earlier checks of this repository kept are in ${N(u1(t),A1)}: ${o.scripts.map(d=>`${d.name} (${d.what}; last kept ${d.keptAt.slice(0,10)})`).join("; ")}. Run the one that fits as it is before reading the project for setup; change it only where it fails.${vv(o.scripts,N(u1(t),A1))}`:"No setup script has been kept for this repository yet: yours will be the first."),A(`When a setup script of yours has run clean, keep it for the checks after you: canary jobs keep ${a} ${A1}/<file> --what "<what it sets up>"`),A(`Your setup script says when setup is done: once its smoke check passed, its last step runs canary jobs ready with CANARY_BATCH from ${o.values}, never letting that call fail the script. A kept script without that step stays as it is: once it runs clean, run canary jobs ready ${a} yourself, before you work on the checks.`),A(`Label what you start in Docker with --label ${x2(a)}, or use compose project name ${S2(a)}. Register other background processes: canary jobs created ${a} --pid <pid> --what "<what>".`),_4()&&A(`Claude Code's sandbox is on. A tool it blocks (docker, for example) runs only if the user added it to sandbox.excludedCommands, and then only as a command on its own: not inside a script, after cd or &&, or with a redirect. If the sandbox refuses a command you need, ask the user with canary jobs ask --setup ${a}, naming the command.`),A(`Clocks: setup ${l.batchSetupMinutes} min from now (ends when you start the first job); each job ${l.jobMinutes} min of working time; the batch ${l.batchMinutes} min, after which the work in hand finishes and jobs not yet started move to another batch; a wait on the user ${l.userWaitMinutes} min. Waiting on the user doesn't count.`),A(`Keep your listener running as a background command, and start it again each time it returns: canary jobs listen ${a}`),A(`Evidence for a job goes in ${N(c1(a),"packs","<job>")}/pack.json; the format: canary jobs schema`),A(""),A("Jobs, one at a time, in this order:"),e.jobs.forEach(({job:d,brief:m,state:u,earlierFiles:p,earlier:f},k)=>{A(`${k+1}. Job ${d.id}: ${d.scenario.title} [${u}]`),A(` What must hold: ${d.scenario.assertion}`);for(let x of zv(d.scenario.target))A(` ${x}`);d.scenario.target&&A(` ${xv(d.scenario.target)}`),d.scenario.claim&&A(` Claim, where the wrong outcome is the failure: ${Object.entries(d.scenario.claim).filter(([,x])=>x).map(([x,y])=>`${x}: ${y}`).join("; ")}`),A(` How to prove it (${m.method}): ${m.plan}`),A(` Data to set up: ${m.dataSetup}`),A(` Must run for real: ${m.reasons.dependsOn.join("; ")}`),m.reasons.faked.length&&A(` May be faked, only to set up or observe: ${m.reasons.faked.map(x=>`${x.part} (${x.why})`).join("; ")}`),m.reasons.limits.length&&A(` Known limits: ${m.reasons.limits.map(x=>`${x.part} (${x.why})`).join("; ")}`),m.questions.length&&A(` Expected questions: ${m.questions.join(" | ")}`),m.permissions.length&&A(` Access to ask for: ${m.permissions.join(" | ")}`),d.scenario.relatedFiles.length&&A(` Related files: ${d.scenario.relatedFiles.join(", ")}`),d.recheckOf?(A(` Re-check of an earlier result. Last time, ${kv(d.recheckOf.verdict)}.${d.recheckOf.reasoning?` Earlier reasoning: ${d.recheckOf.reasoning}`:""}`),d.recheckOf.scope?.trim()&&A(` The person put part of this check out of scope, in their own words: "${d.recheckOf.scope.trim()}". This re-check is judged only within what they kept: a case their words rule out neither fails nor holds it. Run what they kept, and say what you left out because of their words.`),d.recheckOf.reproduction&&A(` Earlier reproduction: ${d.recheckOf.reproduction.steps.join(" Then ")} Look for: ${d.recheckOf.reproduction.observe}`),p.length&&A(` Earlier files (fetch each into the copy with canary jobs earlier ${d.id} <path>): ${p.join(", ")}`)):f&&(A(` Tried first on Canary's computer, which runs only the code. What it needs from this machine: ${f.needs.replace(/[.\s]+$/,"")}.${f.reasoning?` What that attempt showed: ${f.reasoning}`:""}`),p.length&&A(` Its scripts (fetch each into the copy with canary jobs earlier ${d.id} <path>, and reuse what still fits): ${p.join(", ")}`))})}function Cv(e,t){let n=q=>JSON.stringify(t.jobs.find(r=>r.jobId===q)?.title??q??"");switch(e.type){case"stop":return e.reason==="setup_limit"?"Canary: stop. Setup ran past its limit, so this batch's jobs not yet run have ended. Clean up what you started; the listener will report the batch's end.":`Canary: stop job ${e.jobId} (${n(e.jobId)}): ${e.reason==="time_limit"?"its time ran out":"the batch's time ran out"}. Stop its processes now and send what you already have by ${e.submitBy}: canary jobs submit ${e.jobId}${t.proofs[e.jobId]?` --proof ${t.proofs[e.jobId]}`:""}`;case"time_up":return`Canary: this batch's time is up. Finish the work you have in hand, which keeps its own time, and start nothing else: the jobs you hadn't started moved to another batch for another verifier (${e.jobIds.map(q=>`${q} ${n(q)}`).join("; ")}). The listener will report the batch's end.`;case"proof_request":return`Canary asks for more proof on job ${e.jobId} (${n(e.jobId)}), request ${e.proofRequestId}: ${e.request} When the work in hand is done, pick it up with canary jobs start ${e.jobId} --proof ${e.proofRequestId}, write ${y2(t.batchId,e.jobId,e.proofRequestId)}/delta.json, then canary jobs submit ${e.jobId} --proof ${e.proofRequestId}.`;case"wait_over":return`Canary: no answer from the user in time, so ${e.jobId?`job ${e.jobId} (${n(e.jobId)})`:"the jobs not yet run"} ended; it can be re-checked. Move on.`;case"result":return`Canary result for job ${e.record.jobId} (${n(e.record.jobId)}): ${e.record.verdict??"no verdict"}.`;case"batch_ended":return e.reason==="set_aside"?`Canary: batch ${t.batchId}'s checks were set aside for the user to decide on, so start none of them. Finish setting the app up first, so the checks after you reuse it: once your setup script runs clean, smoke check included, keep it with canary jobs keep ${t.batchId} ${A1}/<file> --what "<what it sets up>", then stop what you started and run: canary jobs finish ${t.batchId}`:`Canary: batch ${t.batchId} has ended. Stop what you started and run: canary jobs finish ${t.batchId}`}}async function Av(e,t){let n=!1;for(let q of de([{runId:e.runId}]).filter(r=>r.batchId===e.batchId&&r.status==="answered")){let r=H0(q.path);r.texts.length!==0&&(r.first&&await i1(`/cli/jobs/batches/${e.batchId}/resume`,{session:t,batchKey:e.key,method:"POST"}).catch(()=>{}),A(r.first?`Canary: ${nc(q)}`:`Canary: more on ${q.id} from the coding agent: ${r.texts.join(" | ")}`),n=!0)}return n}async function Iv(e){let t=C1(),n=st(e),q=Date.now(),r=null,s=!1;for(setInterval(()=>void Av(n,t).then(i=>{i&&process.exit(0)}).catch(()=>{}),2e3).unref();;){if(n.owner&&!u2(n.owner))return A("Canary: the Claude Code session ended; this listener stops.");if(Date.now()-q>Zf){if(r)return A("Canary: can't reach Canary right now; run the listener again.");let a=z2(e)?[]:gv(n);return A(a.length?`Canary: no news yet. Of the scripts you have run, ${a.join(", ")} ${a.length>1?"aren't kept as they stand":"isn't kept as it stands"}, so if setup runs out of time a try after this one starts without ${a.length>1?"them":"it"}. Keep what sets the app up now, with how far it gets, and again as it gets further (a script for one job stays unkept): canary jobs keep ${e} ${A1}/<file> --what "<what it sets up and how far it gets>"`:"Canary: no news yet.")}let i;try{i=await i1(`/cli/jobs/batches/${e}/events?after=${n.cursor}`,{session:t,batchKey:n.key,timeoutMs:a0}),s&&A("Canary: reachable again."),r=null,s=!1}catch(a){if(ir(a))return Ie(e,l=>{l.ended=!0}),A(`Canary: stop working on batch ${e}: ${a.message} Clean up what you started and run: canary jobs finish ${e}`);if(!De(a))throw a;r??=Date.now(),!s&&Date.now()-r>V5&&(s=!0,A("Canary: can't reach Canary right now; still trying.")),await ct(T2);continue}n=Ie(e,a=>{a.cursor=i.cursor;for(let l of i.events)l.type==="stop"&&l.jobId&&(a.stopped[l.jobId]=l.submitBy),l.type==="proof_request"&&l.jobId&&(a.proofs[l.jobId]=l.proofRequestId),l.type==="result"&&delete a.proofs[l.record.jobId],l.type==="batch_ended"&&(a.ended=!0,a.setAside=l.reason==="set_aside")});for(let a of i.events)a.type==="batch_ended"&&$t([{runId:n.runId}],e,"all"),a.type==="wait_over"&&($t([{runId:n.runId}],e,a.jobId),a.jobId&&t0(e,a.jobId));for(let a of i.events)A(Cv(a,n));if(i.events.length>0)return}}var qi=(e,t)=>{if(e.stopped[t])throw new E("job_stopped","Canary stopped this job; only its final evidence can still be sent.",`canary jobs submit ${t}${e.proofs[t]?` --proof ${e.proofs[t]}`:""}`)},tc=e=>{if(e===void 0)return null;if(!/^[1-9]\d*$/.test(e))throw new E("usage","--proof takes the request's number, as the listener printed it.");return Number(e)};async function Rv(e,t){let n=b2(e);qi(n,e),await oc(n);let q=tc(t.proof);await U1(()=>i1(`/cli/jobs/${e}/start`,{session:C1(),batchKey:n.key,json:{proofRequestId:q}}),E2).catch(async s=>{throw s instanceof L&&s.status>=500?await Ar(n,e,s,q?"picking up this request":"starting this job",`canary jobs start ${e}${q?` --proof ${q}`:""}`):s});let r=!z2(n.batchId);f0(n.batchId,"start",e,q),r&&!n.kept?.length&&A(`If the setup script you just ran isn't kept for later checks yet, or you changed a kept one, keep it now: canary jobs keep ${n.batchId} ${A1}/<file> --what "<what it sets up>"`),A(q?`Picked up request ${q} on job ${e}: its 15 minutes run from now. Answer in ${y2(n.batchId,e,q)}/delta.json.`:`Started job ${e}. Its working time is counting; waiting on the user doesn't count.`)}async function Tv(e,t){let n=C1(),q,r;if(t.wait){let i=X().filter(a=>a.sessionId===n).flatMap(a=>de([{runId:a.runId}]).filter(l=>l.id.toLowerCase()===t.wait.toLowerCase()&&l.batchId===a.batchId).map(l=>({q:l,s:a})))[0];if(!i)throw new E("no_such_question",`No question ${t.wait} from a batch taken in this session.`);({q,s:r}=i)}else{if(!e||!!t.job==!!t.setup)throw new E("usage","Ask about one job (--job <job>) or about setting up (--setup <batch>), with the question text.");if(e.length>B5)throw new E("question_too_long",`A question is one need, in a line or two: this one is ${e.length} characters, and ${B5} is the most.`,"Ask for the one thing that blocks you most, with what the check can't show without it. Ask the next once this one is answered.");r=t.job?b2(t.job):st(t.setup);let o=Object.keys(r.stopped).find(l=>!r.finalSent.includes(l));if(o)throw new E("job_stopped",`Job ${o} was stopped and its final evidence is due; no question can hold it up.`,`canary jobs submit ${o}${r.proofs[o]?` --proof ${r.proofs[o]}`:""}`);let i=r;await oc(i);let a=()=>U1(()=>i1(`/cli/jobs/batches/${i.batchId}/pause`,{session:n,batchKey:i.key,json:{jobId:t.job??null}}),E2);try{await a()}catch(l){if(l instanceof L&&l.status>=500)throw await Ar(i,t.job??null,l,"taking your question",`canary jobs ask ${t.job?`--job ${t.job}`:`--setup ${i.batchId}`} "<question>"`);let c=de([{runId:i.runId}]).some(h=>h.batchId===i.batchId&&h.status==="open");if(!(l instanceof L&&l.code==="already_waiting")||c)throw l;await i1(`/cli/jobs/batches/${i.batchId}/resume`,{session:n,batchKey:i.key,method:"POST"}),await a()}try{q=F5(r.checkout,{runId:r.runId,batchId:r.batchId,jobId:t.job??null,verifier:Z0(r.batchId),text:e})}catch(l){throw await i1(`/cli/jobs/batches/${r.batchId}/resume`,{session:n,batchKey:r.key,method:"POST"}).catch(()=>{}),l}A(`Asked ${q.id}; the clock is paused while the user answers. If this command is cut off: canary jobs ask --wait ${q.id}. Nothing else you write reaches the coding agent or the user while you work: only a question, and your last message when you end.`)}let s=Date.now()+Qf;for(;;){let o=X().find(a=>a.batchId===r.batchId);if(!o||o.ended)return $t([{runId:r.runId}],r.batchId,"all"),A(`Canary: batch ${r.batchId} has ended, so ${q.id} needs no answer. Stop what you started and run: canary jobs finish ${r.batchId}`);let i=W5(q.path);if(i?.status==="answered"){let a=H0(q.path).first,l=nc(i),c=!0;try{a&&({resumed:c}=await U1(()=>i1(`/cli/jobs/batches/${r.batchId}/resume`,{session:n,batchKey:r.key,method:"POST"})))}catch(h){if(!ir(h))return A(`${l} Couldn't restart the clock with Canary; run canary jobs ask --wait ${q.id} to try again.`)}return A(c?l:`${l} It came after the wait ran out, so ${q.jobId?"that job":"the jobs not yet run"} already ended.`)}if(i?.status==="expired")return A(`No answer to ${q.id} in time: Canary ended ${q.jobId?`job ${q.jobId}`:"this batch's jobs not yet run"}; it can be re-checked. Move on.`);if(Date.now()>=s)return A(`No answer to ${q.id} yet. The clock stays paused; Canary ends the job when the wait on the user runs out, and your listener will say so. To keep waiting: canary jobs ask --wait ${q.id}`);await ct(2e3)}}var B5=350;function nc(e){let t=e.userWords??[],n=e.userSpoke?t.length?` (passed on by the coding agent; what the user said since you asked: ${t.map(r=>JSON.stringify(r)).join("; ")}. Access or approval counts only as far as their own words give it)`:"":" (from the coding agent, with the user saying nothing in between: it settles facts about the project, not access or approval)",q=(e.more??[]).map(r=>` Added later: ${r.text}`).join("");return`Answer to ${e.id}${n}: ${e.answer}${q} If this leaves part of what you need open, or asks you something back, ask again with one question that carries what was asked for.`}async function Ov(e){let t=N(B(),"runs"),n=(k1(t)?P2(t):[]).flatMap(q=>{try{return P2(N(t,q,"results")).filter(r=>r.endsWith(".md")&&r.startsWith(e.toLowerCase())).map(r=>N(t,q,"results",r))}catch{return[]}});if(n.length!==1)throw new E("not_found",n.length?"More than one check's record starts with that id.":"No record of that check on this machine.","Use the check id its result gave.");A(Re(n[0],"utf8").trimEnd())}var qc=e=>V1(C1()).find(t=>t.runId.startsWith(e))?.runId??e;async function Ev(e){let t=qc(e),{stopped:n}=await i1(`/cli/jobs/runs/${t}/stop`,{session:C1(),method:"POST"});Vn(X().filter(q=>q.runId===t&&q.sessionId===C1()).map(q=>q.batchId),Wt+3e4),A(n?`Stopped ${n} check${n>1?"s":""} of run ${t}: each ends as stopped by the user and can be tried again in this run. Stop the run's verifiers with TaskStop; Canary cleans up what they started.`:`Nothing in run ${t} was still running.`)}async function Nv(e,t){let n=qc(e),q=(()=>{try{return P2(N(s1(n),"results")).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5))}catch{return[]}})(),r=t.map(i=>q.find(a=>a.startsWith(i.toLowerCase()))??i),s=i=>i1(`/cli/jobs/runs/${n}/retry`,{session:C1(),method:"POST",json:{jobIds:r,...i?{source:i}:{}}}),o;try{({retried:o}=await s())}catch(i){if(!(i instanceof L&&i.code==="code_needed"))throw i;({retried:o}=await s(await Pv(n)))}A(o?`${o===1?"1 check":`${o} checks`} of run ${n} that couldn't run or ${o===1?"was stopped goes":"were stopped go"} again in the same run. Start your listener again if it has stopped: it announces their batch. Setup starts from what earlier tries kept.`:`Nothing in run ${n} can be tried again: only a check that couldn't run or was stopped can, and ${r.length?"the ones named are still going":"none of its checks is one"}.`)}async function Pv(e){let t=Y(N(s1(e),"source.json")),n=N(s1(e),"source.bundle");if(!t||!k1(n))throw new E("code_gone","This run's code is no longer on this machine, so its checks can't go again.","Tell the user its checks can't go again in this run; a new request checks the code as it is now.");let q=Q();if(!q)throw new E("not_logged_in","Not logged in to Canary.","Run canary login.");let r=Y(N(s1(e),"request.json")),s=typeof r?.workspaceId=="string"&&typeof r.repositoryId=="string"?{workspaceId:r.workspaceId,repositoryId:r.repositoryId}:null;if(!s){let i=await je(te(C1()).runs[e]?.checkout??_t(),q);s={workspaceId:i.workspaceId,repositoryId:(await Pe({...i,token:q})).repositoryId}}let o=await $q({bundlePath:n,manifest:t,...s,token:q,baseUrl:a1()});return{...o.source,uploadId:o.uploadId}}async function jv(e,t){let n=C1(),q=$5(V1(n),e);if(q.status==="expired")return A(`The wait for ${q.id} had already run out: the check timed out. Keep this answer in canary.md; the check can be re-checked.`);let r=(te(n).userAt??"")>q.askedAt,s=(te(n).said??[]).filter(i=>i.at>q.askedAt).map(i=>i.text),o=q.status==="answered";D5(q,t,r,s),A(o?`Added to the answer to ${q.id}: its verifier gets it with its listener's next news.`:`Answered ${q.id}: its verifier reads it within seconds, from its waiting question or its listener.${r?" If the user's answer gives access or approval, record it in canary.md now, in their words with the date, under the section for that kind of answer: a later check finds it there and doesn't ask again, and this verifier acts on it only once it is there.":""}`)}async function Mv(e,t){let n=C1(),q=b2(e);if(q.finalSent.includes(e))throw new E("final_sent","This job's final evidence after its stop was already sent.");let r=tc(t.proof),s=r?"with this answer":"with this job's evidence",o=`canary jobs submit ${e}${r?` --proof ${r}`:""}`,i=y2(q.batchId,e,r??void 0),a=N(dt(c1(q.batchId)),"packs",e,...r?[`proof-${r}`]:[]);if(k1(i)&&dt(i)!==a)throw new E("pack_folder_link",`${i} is a link, so the evidence would be read from somewhere else.`,"Make it a plain folder holding the evidence files.");let l,c;try{if(!gl(q.batchId))throw new Error("the plugin's hooks saw nothing of this batch's verifier");l=Rh(q.batchId,e,r);let d=l.calls.at(-1);d?.kind==="command"&&d.ended==="not_run"&&/\bcanary\s+jobs\s+submit\b/.test(d.what)&&l.calls.pop();let m=de([{runId:q.runId}]).filter(p=>p.batchId===q.batchId).map(({id:p,jobId:f,text:k,status:x,answer:y,userSpoke:b})=>({id:p,jobId:f,text:k,status:x,answer:y,userSpoke:b??!1})),u=l.calls.filter(p=>p.kind==="file"&&p.ended==="ran").map(p=>p.what);c=f5(i,r?"delta":"pack",{jobId:e,commit:q.code.commit,tree:q.code.treeHash,uncommitted:q.code.uncommitted??null,scripts:Lv(u1(q),q.batchId,e,r),scriptsFrom:N(u1(q),A1),diff:await s5(u1(q)),warmCopy:q.warm??!1,stopped:!!q.stopped[e],startedAt:l.jobStartedAt,observed:{calls:l.calls,earlierCalls:l.earlierCalls,minutes:l.minutes,stopped:!!q.stopped[e],putBack:await n5(dt(u1(q)),u),questions:m},byHand:Th(q.batchId)},r,C0(q.checkout))}catch(d){if(d instanceof E)throw d;if(K0(d))throw new E("not_enough_disk","This machine ran out of disk while Canary put this job's evidence together.",`Tell the user, and send it again once more disk is free: ${o}`);let m=Z5(d);throw m?Qq(m):await Ar(q,e,d,s,o)}$v(q,e,c.pack),Fv(q,e,r,c.pack,l);let h={session:n,batchKey:q.key};try{let d=await U1(()=>i1(`/cli/jobs/${e}/evidence`,{...h,json:c.upload}),E2);for(let m of d.missing){let u=c.bytes.get(m);await U1(()=>i1(`/cli/jobs/${e}/evidence/${d.uploadId}?path=${encodeURIComponent(m)}`,{...h,method:"PUT",bytes:u,timeoutMs:nv(u.length)}),E2)}await U1(()=>i1(`/cli/jobs/${e}/evidence/${d.uploadId}/complete`,{...h,method:"POST"}),E2)}catch(d){throw d instanceof L&&d.status>=500?await Ar(q,e,d,s,o):d}if(q.stopped[e]&&Ie(q.batchId,d=>void d.finalSent.push(e)),f0(q.batchId,"sent",e,r),t0(q.batchId,e),A(`Sent ${r?`the answer to request ${r} on`:"the evidence for"} job ${e}; Canary is judging it, and the result reaches your listener.`),c.hidden.length){let d=new Map;for(let{name:p,path:f}of c.hidden)d.set(p,[...new Set([...d.get(p)??[],f])]);let m=[...d].filter(([p])=>p!==C2).map(([p,f])=>`${p} (in ${f.join(", ")})`),u=d.get(C2);A(`Canary hid secret values before sending: ${[...m.length?[`these by their names: ${m.join("; ")}`]:[],...u?[`${C2} (in ${u.join(", ")})`]:[]].join("; and ")}. That is best effort, so keep secret values out of what you record.`)}}async function Ar(e,t,n,q,r){let s;try{s=await Nn(e.sessionId,t?{jobId:t,batchKey:e.key}:{batchId:e.batchId,batchKey:e.key},n)}catch(o){return J0(o)?o:new E("internal_error",at,`Run it again in a minute: ${r}`)}return s.requeued?new E("internal_error",`Canary hit an internal error ${q}, so it took this batch back to try its checks once more with a fresh verifier.`,`Stop what you started and run canary jobs finish ${e.batchId}.`):s.ended>0?new E("internal_error",`Canary hit an internal error ${q}, so ${t?"this job":"this batch's checks not yet sent"} ended; ${t?"it":"they"} can be tried again.`,t?"Go on with your next job; your listener says if the batch has ended.":`Stop what you started and run canary jobs finish ${e.batchId}.`):new E("internal_error",`Canary hit an internal error ${q}, so Canary judges ${t?"the job":"the batch's checks"} on the evidence it already has.`,t?"Go on with your next job.":`Run canary jobs finish ${e.batchId}.`)}function Lv(e,t,n,q){let r=N(e,A1),s=N(y2(t,n),A1),o=q?N(y2(t,n,q),`proof-${q}-scripts`):s,i=[],a=l=>{for(let c of k1(l)?P2(l,{withFileTypes:!0}):[]){let h=N(l,c.name),d=G5(r,h).split(_n).join("/");if(c.name.startsWith(".")||c.name==="node_modules"||d===N2||i.length>=Bv)continue;if(c.isDirectory()){a(h);continue}if(!c.isFile()||j2(h).size>rc||!Pt.test(`${_0(o)}/${d}`))continue;let m=Re(h);if(m.subarray(0,8e3).includes(0)||q&&k1(N(s,d))&&Re(N(s,d)).equals(m))continue;Ht(ge(N(o,d)),{recursive:!0}),Hn(N(o,d),m);let{atime:u,mtime:p}=j2(h);Kf(N(o,d),u,p),i.push(`${_0(o)}/${d}`)}};return a(r),i}function Fv(e,t,n,q,r){let s=`${t}:${n??0}`;if(e.stopped[t]||e.sentBack?.includes(s))return;let o=r.calls.filter(h=>h.kind==="command"&&(h.ended==="ran"||h.ended==="failed")).length,i=e.jobMinutes??15,a=r.startedAt===null||r.minutes<i/3,l=r.startedAt===null?"It was never started":`It used ${Math.round(r.minutes)} of its ${i} minutes`,c="claim"in q?q.claim.verdict==="cannot_run"&&(o===0||a)&&[`This job is coming back as one that couldn't run. ${l}, and Canary's record shows ${o} command${o===1?"":"s"} run for it.`,"If any part of the scenario can run with what is allowed, run it and send what that shows: a check that never ran tells the user nothing. If nothing can, submit again as it is."]:o===0&&q.steps.length===0&&q.files.length===0&&[`This answer comes with nothing run, no step and no file. ${l}.`,"Run what the request asks, or say in the answer which earlier command already printed it. If neither is possible, say what stands in the way and submit again."];if(c)throw Ie(e.batchId,h=>void(h.sentBack=[...h.sentBack??[],s])),new E("nothing_run",c[0],c[1])}function $v(e,t,n){if(!("claim"in n)||n.claim.verdict==="cannot_run")return;let[q,r]=e.ports,s=e.targets?.[t];for(let o of n.ranOn.target.matchAll(/\b(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0)(?::(\d{1,5}))?|\[::1\](?::(\d{1,5}))?/g)){let i=Number(o[1]??o[2]??NaN);if(!(Number.isNaN(i)||i>=q&&i<=r)&&!(s&&Dv(s)===`${o[0].replace(/:\d+$/,"").toLowerCase()}:${i}`))throw new E("not_this_batch",`The evidence gives ${o[0]} as what was tested, which is outside this batch's ports (${q}-${r}), so it isn't the app in your copy.`,`Run the scenario against the app you started on your own ports and send what that shows. If the address was mistyped, correct ranOn.target${s?`; this job's running target is ${s}, as take printed it`:""}.`)}}function Dv(e){try{let t=new URL(e);return`${t.hostname.toLowerCase()}:${t.port||(t.protocol==="https:"?"443":"80")}`}catch{return null}}async function Wv(e,t){let n=b2(e);if(qi(n,e),!Pt.test(t))throw new E("usage",`${t} isn't a path from the earlier evidence.`,"Use a path take printed under earlier files.");let q=await U1(()=>Jl(`/cli/jobs/${e}/earlier?path=${encodeURIComponent(t)}`,{session:C1(),batchKey:n.key})),r=dt(u1(n)),s=ge(N(r,t));for(;!k1(s);)s=ge(s);if(dt(s)!==r&&!dt(s).startsWith(r+_n))throw new E("outside_copy",`${t} leads outside the copy through a link.`);Ht(ge(N(r,t)),{recursive:!0});let o=N(r,t);k1(o)&&(o=`${o}.earlier`);let i=Yf(o,zr.O_WRONLY|zr.O_CREAT|zr.O_EXCL|zr.O_NOFOLLOW,420);try{Xf(i,q)}finally{Vf(i)}A(`Wrote ${t} from the earlier evidence to ${o}.`)}async function Hv(e,t){let n=st(e),q=Number(t.pid),r=Number.isInteger(q)&&q>1?Oe(q):null;if(r===null)throw new E("no_such_process",`No running process ${t.pid}.`);if(!w0(q,n))throw new E("not_this_batch",`Process ${q} doesn't run from this batch's copy or its folder, so the batch won't stop it. If you found it on one of your ports and it isn't Docker publishing a container you labelled, another program may hold that port.`,"Record only processes this batch started; Docker containers are removed by their label. If your app lost its port, start it on another port from your block.");Ie(e,s=>void s.processes.push({pid:q,startedAt:r,what:t.what??"background process"})),A(`Recorded process ${q}; finish stops it with the batch.`)}var Ir="kept.json",rc=256*1024,Bv=80;async function _v(e,t,n){let q=st(e),r=dt(u1(q)),s=Zq(q.checkout),o=C0(q.checkout),i=[];for(let l of t){let c=b1(Bn(r,l));if(!M2(c,[N(r,A1)])||!j2(c).isFile()||j2(c).size>rc||_0(c)===N2)throw new E("not_a_setup_script",`${l} isn't a script in ${N(r,A1)}.`,"Keep the setup script, and any file it runs, from that folder.");let h=Re(c,"utf8"),d=[...[q.batchId,O2(q.batchId)].filter(u=>h.includes(u)).map(u=>`this batch's id (${u})`),...[r,u1(q),c1(q.batchId),q.checkout,Sr()].filter(u=>h.includes(u)).slice(0,1).map(u=>`a path on this machine (${u})`),...[...h.matchAll(/\b4[2-5]\d{3}\b/g)].slice(0,1).map(u=>`a port written out (${u[0]})`),...o.filter(u=>h.includes(u.value)).slice(0,1).map(u=>`the value of ${u.name}`)];if(d.length)throw new E("holds_this_batch",`${l} holds ${d.join(", ")}, so the next verifier would have to rewrite it.`,`Read those from ${A1}/${N2} (ports as offsets from CANARY_PORT_FIRST, names ending in CANARY_SHORT, secrets from the file CANARY_SECRETS names), run it clean once more, and keep it again.`);let m=ec(h);if(m)throw new E("unlabelled_container",`${l} starts a container without this batch's label (${m.trim().slice(0,100)}), so nothing would remove it if the batch ended while it ran.`,`Start every container with --label "$CANARY_DOCKER_LABEL" (from ${A1}/${N2}), run it clean once more, and keep it again.`);i.push({name:G5(N(r,A1),c).split(_n).join("/"),text:h})}let a=Y(N(s.scripts,Ir))??{};for(let{name:l,text:c}of i)Ht(ge(N(s.scripts,l)),{recursive:!0,mode:448}),Hn(N(s.scripts,l),c,{mode:384}),a[l]={what:n.what,keptAt:new Date().toISOString()};F1(N(s.scripts,Ir),a),Ie(e,l=>void(l.kept=[...new Set([...l.kept??[],...i.map(c=>c.name)])])),A(`Kept ${i.map(l=>l.name).join(", ")} for later checks of this repository: the next take puts ${i.length>1?"them":"it"} in the verifier's copy.`)}async function Uv(e){Ie(e,t=>void(t.readyAt??=new Date().toISOString())),A("Noted: the app is up. The user now sees that setup is over and that you are getting the checks ready.")}async function Gv(e,t){let n=b2(e);qi(n,e);let q=Date.now()+ev;for(;!wl(t,n.batchId,e);){if(Date.now()>=q)throw new E("target_busy",`Another verifier is still writing to ${t}.`,"Work without writing to it, or report why the job couldn't run.");await ct(2e3)}A(`You may write to ${t}; the lock is released when this job's evidence is sent or the batch finishes.`)}async function Vv(e,t){if(!k1(N(c1(e),"state.json")))return Bt(c1(e),{recursive:!0,force:!0}),A(`Nothing of batch ${e} is on this machine.`);let n=st(e),q=C1();if(n.sessionId!==q)throw new E("other_session","This batch was taken by another Claude Code session.");let r=n.ended?void 0:(await Or(q)).runs.flatMap(o=>o.batches).find(o=>o.batchId===n.batchId);if(r&&r.state!=="ended"&&r.holder===Yo(n.key)){if(!t.giveBack)throw new E("batch_open","This batch is still open: Canary may still ask this verifier for more proof, which needs the copy and the running app.",`Wait until the listener reports the batch ended. If its verifier ended and won't come back: canary jobs finish ${e} --give-back`);let o=!1,{requeued:i,ended:a}=await U1(()=>i1(`/cli/jobs/batches/${e}/give-back`,{session:q,batchKey:n.key,method:"POST"}),E2).catch(async l=>{if(!(l instanceof L&&l.status>=500))throw l;return o=!0,Nn(q,{batchId:e,batchKey:n.key},l).catch(()=>{throw new E("internal_error",at,`Run it again in a minute: canary jobs finish ${e} --give-back`)})});A(i?`Gave batch ${e} back: jobs it hadn't sent evidence for will go to a fresh verifier.`:a>0?o?`Canary hit an internal error taking batch ${e} back, so it ended the jobs it hadn't sent evidence for: start no verifier for it, and tell the user they can be tried again.`:`Gave batch ${e} back. It has had all the verifiers it may, so Canary ended the jobs it hadn't sent evidence for: start no verifier for it, and tell the user they can be re-checked.`:`Gave batch ${e} back. Nothing was left in it to start, so start no verifier for it; what it sent is still being judged.`)}let s=await Ft(n);A(`Cleaned up batch ${e}: stopped what was still running from its copy and its folder, and removed its files. The copy of the code stays for later checks of this repository.`);for(let o of s)A(`Left in place: ${o}`)}async function sc(){if(process.stdin.isTTY)return{};let e=[],t=new Promise(n=>{process.stdin.on("end",n),setTimeout(n,300).unref()});process.stdin.on("data",n=>e.push(n)),await t,process.stdin.destroy();try{let n=JSON.parse(Buffer.concat(e).toString("utf8"));return n&&typeof n=="object"?n:{}}catch{return{}}}async function Jv(){try{let e=await sc(),t=e.agent_id,n=e.hook_event_name,q=e.tool_input;if(n==="PreToolUse"&&q?.subagent_type==="canary:verifier"&&(q.isolation||q.name))return A(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:og}}));if(n==="PostToolUse"&&e.tool_name==="AskUserQuestion"&&typeof e.session_id=="string"){let S=te(e.session_id).asking;if(S&&k1(S)){let v=ch(e,S);v.commands!==null&&rh(S,v.commands),v.envFiles&&sh(S,v.envFiles.files,v.envFiles.answer)}return await Tr(e.session_id,Un,hg(e))}if(n==="UserPromptSubmit"&&typeof e.session_id=="string")return typeof e.prompt=="string"&&Kv.test(e.prompt)?void 0:await Tr(e.session_id,tv,typeof e.prompt=="string"?[e.prompt]:[]);let r=e.agent_type==="canary:verifier"&&typeof t=="string"?t:null,s=_f("sha256").update(JSON.stringify([e.tool_name??null,e.tool_input??null])).digest("hex").slice(0,16),o={call:typeof e.tool_use_id=="string"?e.tool_use_id:s,same:s},i=n==="PermissionRequest"?ng(e):null;if(i===!0)return A(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"allow"}}}));if(i&&!i.shared){let S=r&&ne(r);return S&&k2(S,{same:s},"sent_back",i.reason),A(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"deny",message:B0(i)}}}))}if(!r)return;if(n==="PermissionRequest")return await ag(r,s,i?i.reason:"");if(n==="PermissionDenied")return Yv(r,o,e);await lg(r,typeof n=="string"?n:"",s,typeof e.duration_ms=="number"?Math.max(0,Math.round(e.duration_ms)):0);let a=String(e.tool_name),l=e.tool_input,c=Rr.has(a)?l?.file_path??l?.notebook_path:null,h=a==="Bash"&&typeof l?.command=="string"?l.command:null,d=typeof c=="string"||h!==null&&!Mt(h);if(n==="PostToolUse"||n==="PostToolUseFailure"){let S=d?ne(r):null;if(!S)return;k2(S,o,n==="PostToolUse"?"ran":"failed",Qv(e)),h!==null?g0(S,o.call,Zv(e)):typeof c=="string"&&n==="PostToolUse"&&Sh(S,o.call,b1(c));return}if(n==="PostToolBatch")return eg(r,e);if(n!=="PreToolUse")return;let m=(S,v,w)=>{S&&k2(S,o,"sent_back",w),A(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:v}}))};if(typeof c=="string"){let S=ne(r);S&&fr(S,o,"file",b1(c));let v=qg(r,e);v&&m(S,v,v.includes("the user's own word")?"it changes the user's part of the notes":"outside the verifier's own folders");return}let u=S=>!!S&&jt(S)?.commands==="run";if(h===null){let S=ne(r),v=ri.has(a)&&u(S&&X().find(w=>w.batchId===S)?.checkout||(typeof e.cwd=="string"?e.cwd:null))?Q0(e):null;v&&m(null,B0(v),v.reason);return}let p=/\bcanary\s+jobs\s+(?:take|listen)\s+([0-9a-fA-F-]{36})\b/.exec(h)?.[1];p&&ne(r)!==p&&vl(r,p);let f=ne(r);if(f&&d){let S=e.tool_input;fr(f,o,"command",h,typeof S.description=="string"?S.description:"",S.run_in_background===!0)}let k=f?X().find(S=>S.batchId===f):void 0,x=k?.checkout??(typeof e.cwd=="string"?e.cwd:null),y=u(x)?null:P5(h),b=u(x)&&!Mt(h)?Q0(e):null,z=k?tg(h,Er(k,k.checkout),k.checkout):null,C=k?sg(h,k,typeof e.cwd=="string"?e.cwd:k.checkout):null,I=ig(r,h);b?m(f,B0(b),b.reason):I?m(f,I,"the job moved to another batch"):Xv.test(h)?m(f,"Canary: not run. Answering a question, resetting the user's choices and stopping or retrying a run are the coding agent's commands, for what the user said: a verifier asks, and waits for the answer.","it is the coding agent's command"):z?m(f,z,"it names what Canary itself keeps about the checks"):C?m(f,C,"it writes a file outside the verifier's own folders"):y&&m(f,j5(y),y)}catch{}}function Yv(e,t,n){let q=ne(e),r=n.tool_input,s=n.tool_name==="Bash"&&typeof r?.command=="string"?r.command:null;!q||s===null&&!Rr.has(String(n.tool_name))||(s!==null&&Mt(s)&&fr(q,t,"command",s),k2(q,t,"blocked",typeof n.reason=="string"?n.reason:""))}var Kv=/^\s*(?:<task-notification>|<agent-message\b|Another Claude session sent a message)/,Rr=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Xv=/\bcanary\s+(?:jobs\s+(?:answer|approvals|stop|retry)|answer)\b/;function Qv(e){if(typeof e.error=="string")return e.error.trim();let t=e.tool_response;return t?.backgroundTaskId?"started in the background; how it ended isn't recorded":typeof t?.returnCodeInterpretation=="string"?t.returnCodeInterpretation:""}function Zv(e){if(typeof e.error=="string")return e.error;let t=e.tool_response;if(typeof t?.persistedOutputPath=="string")try{return Re(t.persistedOutputPath,"utf8")}catch{}return typeof t?.stdout=="string"?t.stdout:""}function eg(e,t){let n=ne(e),q=Array.isArray(t.tool_calls)?t.tool_calls:[];if(!n||q.length===0)return;let r=Ah(n);for(let s of q){if(typeof s.tool_use_id!="string"||typeof s.tool_response!="string")continue;let o=/^Command running in background .*Output is being written to: (\S+\.output)/.exec(s.tool_response)?.[1];o?xh(n,s.tool_use_id,o):r.has(s.tool_use_id)&&k2(n,{call:s.tool_use_id},"not_run",s.tool_response)}}function tg(e,t,n){let q=$1(n),r=q?[H1(q).dir]:[];for(let s of new Set([B(),b1(B()),N(ge(B()),"approvals"),b1(N(ge(B()),"approvals"))]))for(let o=e.indexOf(s);o!==-1;o=e.indexOf(s,o+1)){let i=/^[^\s'"`;|&<>()]*/.exec(e.slice(o))[0];if(!t.holds(b1(i))&&!M2(b1(i),r))return`Canary: not run. ${i} is part of what Canary itself keeps about the checks, not a file of yours: your own are your copy, your batch's folder, and this repository's notes, secrets and kept scripts.`}return null}function ng(e){let t=e.tool_input,n=String(e.tool_name),q=(n==="Bash"||n==="Monitor")&&typeof t?.command=="string"?t.command:null;if(q!==null&&Mt(q))return!0;let r=t?.file_path??t?.notebook_path??t?.path,s=typeof r=="string"?b1(r):null;if(typeof e.agent_id!="string"){let h=typeof e.cwd=="string"?_t(e.cwd):null,d=h&&$1(h);if(!h||!d)return!1;let m=H1(d),u=[m.dir,N(B(),"runs")];return q!==null?lh(q,p=>M2(b1(p.startsWith("~/")?N(Sr(),p.slice(2)):Bn(e.cwd,p)),u)):s===null?!1:ri.has(n)?M2(s,u):Rr.has(n)&&[m.canaryMd,m.secrets].map(b1).includes(s)&&jt(h)?.commands==="run"}if(e.agent_type!=="canary:verifier")return!1;let o=ne(e.agent_id),i=o?X().find(h=>h.batchId===o):void 0,a=i?.checkout??(typeof e.cwd=="string"?e.cwd:null);if(!a||jt(a)?.commands!=="run")return!1;let l=Er(i,a),c=Q0(e);if(q!==null){let h=d=>{try{return j2(d).size<=262144?Re(d,"utf8"):null}catch{return null}};return c??wr(q,{roots:l.folders.flatMap(d=>[...new Set([d,b1(d)])]),cwd:a,home:Sr(),ports:i?.ports??[0,0],label:x2(i?.batchId??""),composeProject:S2(i?.batchId??""),read:h,dockerOwn:i&&((d,m)=>Lh(i.batchId,d,m))})??!0}return c||(Rr.has(n)?s===null?!1:l.holds(s)||{reason:`it changes ${r}, which isn't one of the checks' own files`,shared:!1}:!0)}var ri=new Set(["Read","Grep","Glob"]);function Q0(e){let t=String(e.tool_name),n=e.tool_input,q=Sr(),r=T5(q,N(G(),"config.json"));if((t==="Bash"||t==="Monitor")&&typeof n?.command=="string")return N5(n.command,q,r);if(!ri.has(t))return null;let s=h=>h.replace(/^~(?=[\\/]|$)/,q),o=n?.file_path??n?.path,i=Bn(typeof e.cwd=="string"?e.cwd:process.cwd(),typeof o=="string"?s(o):"."),a=t==="Glob"&&typeof n?.pattern=="string"?Bn(i,s(n.pattern).replace(/[*?[{].*$/s,"")):null,l=[typeof o=="string"?i:null,a].flatMap(h=>h===null?[]:[b1(h).toLowerCase()]),c=r.find(h=>{let d=b1(h).toLowerCase();return l.some(m=>m===d||m.startsWith(d+_n))});return c?{reason:`it reads ${$0(c,q)}, where the user keeps credentials`,shared:!1,secret:!0}:null}function b1(e){let t=Bn(e);for(let n=t;;n=ge(n))try{return N(dt(n),t.slice(n.length))}catch{if(n===ge(n))return t}}var M2=(e,t)=>t.map(b1).some(n=>e===n||e.startsWith(n+_n));function Er(e,t){let n=$1(t),q=n&&H1(n),r=e?[u1(e),c1(e.batchId)]:[],s=e?b1(N(c1(e.batchId),"state.json")):null;return{folders:r,holds:o=>M2(o,r)&&o!==s||q!==null&&o===b1(q.canaryMd)}}function qg(e,t){let n=t.tool_input,q=n?.file_path??n?.notebook_path,r=ne(e),s=r?X().find(o=>o.batchId===r):void 0;return!s||typeof q!="string"?null:Er(s,s.checkout).holds(b1(q))?rg(s,b1(q),t):`Canary: not written. ${q} is outside your own folders, so nothing would remove it when the batch ends. Write the checks' scripts in your copy (${u1(s)}) and scratch files in ${w2(s.batchId)}; keep a setup script for later checks with canary jobs keep.`}function rg(e,t,n){let q=$1(e.checkout);if(!q||t!==b1(H1(q).canaryMd))return null;let r=n.tool_input,s;try{s=Re(t,"utf8")}catch{return null}let o=Array.isArray(r?.edits)?r.edits:[r??{}],i=typeof r?.content=="string"?r.content:s;if(typeof r?.content!="string")for(let l of o){if(typeof l.old_string!="string"||typeof l.new_string!="string"){i=null;break}i=l.replace_all?i.split(l.old_string).join(l.new_string):i.replace(l.old_string,()=>l.new_string)}let a=l=>l.includes(Ce)?l.slice(0,l.indexOf(Ce)):l;return i!==null&&a(i)===a(s)?null:`Canary: not written. Everything in canary.md above "${Ce.replace(/^#+ /,"")}" is the user's own word (their instructions, the targets they cleared, their test logins), and only the coding agent records it, from what the user said. Add what you learned under "${Ce.replace(/^#+ /,"")}" and "What worked and what failed", and ask a question for anything that needs the user.`}function sg(e,t,n){let q=Er(t,t.checkout).folders,r=y5(e,n).find(s=>!s.startsWith("/dev/")&&!M2(b1(s),q));return r?`Canary: not run. It writes ${r}, which is outside your own folders, so nothing would remove it when the batch ends. Keep every file a command of yours makes in your copy, in ${w2(t.batchId)} or in the job's pack folder; to run something in the background, use your shell tool's own background option on the whole command, which keeps what it prints and tells you when it ends.`:null}var B0=e=>e.secret?`Canary: not run, because ${e.reason}. The user isn't asked about your commands, so they never reach the user's keys and sign-ins. Check what you can without them, and don't reach them another way.`:`Canary: not run, because ${e.reason}. The user isn't asked about your commands, so they may only remove or change what your checks created: files in your copy and your batch's folder, and Docker objects under your batch's label (canary jobs finish removes those). If this is yours, keep it there; otherwise leave it as it is, and don't reach it another way.`,og="Canary: not started. A Canary verifier is started with no `isolation` and no `name`: it builds its own copy of the code outside this checkout and has to run on this machine, in this session. Start it again without them.";function ig(e,t){let n=[...t.matchAll(/\bcanary\s+jobs\s+(?:start|submit|earlier|lock)\s+([0-9a-fA-F-]{36})\b/g),...t.matchAll(/\bcanary\s+jobs\s+ask\b[^\n;&|]*--job[=\s]+([0-9a-fA-F-]{36})\b/g)].map(i=>i[1]),q=ne(e);if(n.length===0||!q)return null;let r=X(),s=r.find(i=>i.batchId===q),o=s&&n.find(i=>!s.jobs.some(a=>a.jobId===i)&&r.some(a=>a.jobs.some(l=>l.jobId===i)));return o?`Canary: not run. Job ${o} is no longer in your batch: it moved to another batch, and another verifier runs it. Finish the work you have in hand, then wait for the listener to report your batch's end.`:null}async function ag(e,t,n=""){let q=ne(e),r=q?X().find(s=>s.batchId===q&&s.claimed):void 0;if(r){yl(e,t,r.batchId,n);try{await i1(`/cli/jobs/batches/${r.batchId}/pause`,{session:r.sessionId,batchKey:r.key,json:{jobId:null,approval:!0},timeoutMs:Un}),On(r.batchId)}catch(s){s instanceof L&&!De(s)?(Tn(rr(e).filter(o=>o.call===t).map(o=>o.name)),On(r.batchId)):Zo(r.batchId,{call:"pause"})}}}async function lg(e,t,n,q){let r=t==="PostToolUse"||t==="PostToolUseFailure";if(!r&&t!=="PostToolBatch"&&t!=="SubagentStop")return;let s=rr(e).filter(i=>!r||i.call===n),o=X().find(i=>s.some(a=>a.batchId===i.batchId))?.sessionId;o&&t!=="SubagentStop"&&await Tr(o);for(let i of new Set(s.map(a=>a.batchId))){let a=s.filter(c=>c.batchId===i);Tn(a.map(c=>c.name));let l=X().find(c=>c.batchId===i);!l||rr(e).some(c=>c.batchId===i)||await ic(l,r?q:0).catch(()=>{})}}function hg(e){let t=e.tool_response?.answers;return t&&typeof t=="object"?Object.values(t).filter(n=>typeof n=="string"):[]}async function Tr(e,t=Un,n=[]){if(Object.keys(te(e).runs).length===0)return;let q=new Date().toISOString(),r=n.map(s=>s.trim()).filter(Boolean).map(s=>({at:q,text:s.length>300?`${s.slice(0,299)}\u2026`:s}));Ae(e,s=>({...s,userAt:q,said:[...s.said??[],...r].slice(-10)})),await i1("/cli/jobs/answered",{session:e,method:"POST",timeoutMs:t}).catch(()=>{})}async function oc(e){$e(e.batchId).length&&await Tr(e.sessionId),await ic(e),Tn($e(e.batchId))}async function ic(e,t=0){try{await i1(`/cli/jobs/batches/${e.batchId}/resume`,{session:e.sessionId,batchKey:e.key,json:{workedMs:t,approval:!0},timeoutMs:Un})}catch(n){if(!(n instanceof L)||De(n))throw Zo(e.batchId,{call:"resume",since:Date.now()-t}),n}On(e.batchId)}async function cg(e,t){let n=$e(e.batchId).length>0,q={session:e.sessionId,batchKey:e.key,timeoutMs:Un};try{t.call==="pause"&&n&&await i1(`/cli/jobs/batches/${e.batchId}/pause`,{...q,json:{jobId:null,approval:!0}}),t.call==="resume"&&!n&&await i1(`/cli/jobs/batches/${e.batchId}/resume`,{...q,json:{workedMs:Math.max(0,Date.now()-t.since),approval:!0}})}catch(r){if(!(r instanceof L)||De(r))return}On(e.batchId,t.call)}function Vn(e,t){e.length!==0&&U5(process.execPath,[process.argv[1],"jobs","clean-ended",...e,"--after",String(t)],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref()}async function dg(e,t){await ct(Number(t.after)||0);let n=C1();for(let q of X().filter(r=>e.includes(r.batchId)&&r.sessionId===n&&!r.left))await Ft(q).catch(()=>{})}async function ug(e){await mg(e).catch(()=>{})}async function mg(e){if(!e.end){let n=(await sc()).session_id,q=(typeof n=="string"?n:null)??process.env.CLAUDE_CODE_SESSION_ID;if(!q||Object.keys(te(q).runs).length===0&&!Bl(q))return;U5(process.execPath,[process.argv[1],"jobs","session-end","--end",q],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref();return}let t=e.end;await U1(()=>i1("/cli/jobs/session-end",{session:t,method:"POST",timeoutMs:1e4})).catch(()=>{});for(let n of X().filter(q=>q.sessionId===t))await Ft(n).catch(()=>{});for(let{runId:n}of V1(t))Bt(N(s1(n),"source.bundle"),{force:!0});_l(t)}function ac(e){let t=e.command("jobs",{hidden:!0}).description("Canary's checks on this machine (run by the Canary plugin's skill and verifiers)");t.command("watch").description("the coding agent's listener: prints new checks, questions and results").action(v1(av)),t.command("list").description("this session's checks, batches and open questions").action(v1(dv)),t.command("take <batch>").description("take a batch: build its copy and claim it").action(v1(uv)),t.command("listen <batch>").description("the verifier's listener: returns after the next news, or about 9 minutes").action(v1(Iv,{urgent:!0})),t.command("start <job>").option("--proof <n>","pick up request <n> for more proof").description("start a job, or pick up a request for more proof").action(v1(Rv,{urgent:!0})),t.command("ask [text]").option("--job <job>","the job the question is about").option("--setup <batch>","a question not about one job").option("--wait <question>","keep waiting for an earlier question").description("ask the coding agent and wait for the answer").action(v1(Tv,{urgent:!0})),t.command("stop <run>").description("stop a run's checks that haven't finished, at the user's word").action(v1(Ev)),t.command("retry <run> [checks...]").description("try again a run's checks that couldn't run, the ones named or all, in the same run, at the user's word").action(v1(Nv)),t.command("record <check>").description("print a check's full record").action(v1(Ov,{local:!0})),t.command("answer <question> <text>").description("answer a verifier's question").action(v1(jv,{local:!0})),t.command("submit <job>").option("--proof <n>","send the answer to request <n>").description("send a job's evidence").action(v1(Mv,{urgent:!0})),t.command("earlier <job> <path>").description("fetch a file of the earlier evidence for a re-check").action(v1(Wv)),t.command("created <batch>").requiredOption("--pid <pid>","the process id").option("--what <what>","what it is").description("record a background process for cleanup").action(v1(Hv,{local:!0})),t.command("keep <batch> <paths...>").requiredOption("--what <what>","what the script sets up, in a few words").description("keep a setup script that ran clean for later checks of this repository").action(v1(_v,{local:!0})),t.command("ready <batch>").description("say the app is up, so the user sees that setup is over").action(v1(Uv,{local:!0})),t.command("lock <job> <target>").description("write to a target marked safe for writes, one verifier at a time").action(v1(Gv,{local:!0})),t.command("finish <batch>").option("--give-back","hand an open batch back first").description("clean up a batch once it has ended").action(v1(Vv)),t.command("session-end").option("--end <session>").description("called by the plugin's session-end hook").action(v1(ug,{sweep:!1})),t.command("clean-ended <batches...>").option("--after <ms>","wait this long first","0").description("clean up ended batches after a wait (started by Canary itself)").action(v1(dg,{sweep:!1,local:!0})),t.command("hook").description("called by the plugin's hooks on a verifier's tool calls").action(Jv),t.command("approvals <action>").description("reset: forget the user's choices for this repository, so they are asked again").action(v1(async n=>{if(n!=="reset")throw new E("usage","The only action is reset.");oh(_t()),A("Forgotten. Canary will say when to ask the user again: before the next verifier starts.")},{local:!0})),t.command("schema").description("the evidence format").action(v1(async()=>A(v5),{sweep:!1}))}g();e1();pq();ie();Le();import{appendFileSync as Og,existsSync as Eg}from"node:fs";import{join as bc}from"node:path";g();Gs();g();var lc=["claude","codex","cursor"];function hc(e,t=0,n=[]){if(typeof e=="string")e&&n.push(e);else if(t<3&&e&&typeof e=="object")for(let q of Object.values(e))hc(q,t+1,n);return n}var ut=e=>typeof e=="string"&&e?e:void 0,pg=new Set(["Bash","PowerShell","Monitor"]);function cc(e,t,n=process.env,q=process.platform){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;if(e==="cursor"){let l=Array.isArray(r.workspace_roots)?r.workspace_roots:[],c=ut(r.cwd)??ut(l[0])??ut(n.CURSOR_PROJECT_DIR)??process.cwd(),h=ut(r.conversation_id)?{chat:ut(r.conversation_id)}:{};return r.hook_event_name==="beforeShellExecution"&&typeof r.command=="string"?{kind:"shell",command:r.command,cwd:c,shell:q==="win32"?"powershell":"posix",...h}:r.hook_event_name==="beforeMCPExecution"&&typeof r.tool_name=="string"?{kind:"tool",toolName:r.tool_name,cwd:c,...h}:null}if(r.hook_event_name!=="PreToolUse"||typeof r.tool_name!="string")return null;let s=ut(r.cwd)??process.cwd(),o=ut(r.session_id)?{chat:ut(r.session_id)}:{},i=r.tool_input&&typeof r.tool_input=="object"?r.tool_input:{};if(pg.has(r.tool_name)&&typeof i.command=="string")return{kind:"shell",command:i.command,cwd:s,shell:r.tool_name==="PowerShell"?"powershell":"posix",...o};let a=e==="codex"&&r.tool_name==="exec"?hc(typeof r.tool_input=="string"?r.tool_input:i):[];return a.length?{kind:"script",toolName:r.tool_name,texts:a,cwd:s,...o}:{kind:"tool",toolName:r.tool_name,cwd:s,...o}}function dc(e,t){if(e==="cursor"){if(t.decision!=="deny")return"";let n=t.message??"Canary held this call.";return JSON.stringify({permission:"deny",user_message:n,agent_message:n})}return t.decision==="deny"?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message??"Canary held this call."}}):t.message?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t.message}}):""}jq();g();p1();var Ut=(e,t)=>({decision:"allow",cause:e,...t?{message:t}:{}}),uc=e=>e.replace(/[\x00-\x1f\x7f]+/g,"?");function Nr(e){if(e.mode==="off")return Ut("mode_off");if(!e.trigger)return Ut("not_a_trigger");if(!e.login)return null;if(!e.login.ok)return Ut(e.login.cause);if(e.chat===void 0)return null;if(e.chat===null)return Ut("no_chat");if(!e.lookup)return null;if(!e.lookup.ok)return Ut(e.lookup.cause,`Canary couldn't be asked about this push (${uc(e.lookup.detail)}), so it went ahead.`);let{hold:t}=e.lookup;return t.state==="clear"?Ut("clear"):t.state==="remind"?{decision:"deny",cause:t.state,message:t.agent}:e.skip===void 0?null:e.skip?Ut("skipped",`Canary: the person chose to continue without verifying (${uc(e.skip.reason)}). Tell them it was pushed without a Canary check.`):{decision:"deny",cause:t.state,message:t.agent}}var fg=new Set(["clear","none","running","open","remind"]);async function mc(e,t,n,q={}){let r=AbortSignal.timeout(q.timeoutMs??Ot);try{let s=new URLSearchParams({workspaceId:e.workspaceId,chat:t,...n?{raised:n}:{}}),o=await W(`/api/v1/cli/hold?${s.toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:Fo(r,q.signal)});return!o||typeof o!="object"||!fg.has(String(o.state))?{ok:!1,cause:"unknown_state",detail:"Canary answered in a way this CLI version does not understand (update the CLI)"}:o.state!=="clear"&&typeof o.agent!="string"?{ok:!1,cause:"unknown_state",detail:"Canary's answer had no words to show"}:{ok:!0,hold:o}}catch(s){return r.aborted?{ok:!1,cause:"lookup_timeout",detail:`Canary did not answer within ${Math.round((q.timeoutMs??Ot)/1e3)} s`}:s instanceof L&&s.status>=400&&s.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${s.status}: ${s.message}${s.fix?` (${s.fix})`:""}`}:s instanceof L&&s.status>=500?{ok:!1,cause:"lookup_error",detail:`Canary answered ${s.status}`}:{ok:!1,cause:"lookup_unreachable",detail:s instanceof Error?s.message:String(s)}}}g();bo();g();import{homedir as vg}from"node:os";import{basename as gg,isAbsolute as yg,resolve as wg}from"node:path";var bg=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),kg=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,pc=e=>e.replace(/\\(.)/g,(t,n)=>n==="n"?`
|
|
3304
|
-
`:n==="t"?" ":n);function
|
|
3333
|
+
`)}`),A(`This batch's own values (its id, copy, scratch folder, ports, Docker label and compose project name, the secrets file) are in ${o.values}, as NAME=value lines: a setup script reads them from there and writes none of them out.`),A(o.scripts.length?`Setup scripts earlier checks of this repository kept are in ${N(u1(t),A1)}: ${o.scripts.map(d=>`${d.name} (${d.what}; last kept ${d.keptAt.slice(0,10)})`).join("; ")}. Run the one that fits as it is before reading the project for setup; change it only where it fails.${vv(o.scripts,N(u1(t),A1))}`:"No setup script has been kept for this repository yet: yours will be the first."),A(`When a setup script of yours has run clean, keep it for the checks after you: canary jobs keep ${a} ${A1}/<file> --what "<what it sets up>"`),A(`Your setup script says when setup is done: once its smoke check passed, its last step runs canary jobs ready with CANARY_BATCH from ${o.values}, never letting that call fail the script. A kept script without that step stays as it is: once it runs clean, run canary jobs ready ${a} yourself, before you work on the checks.`),A(`Label what you start in Docker with --label ${S2(a)}, or use compose project name ${C2(a)}. Register other background processes: canary jobs created ${a} --pid <pid> --what "<what>".`),G4()&&A(`Claude Code's sandbox is on. A tool it blocks (docker, for example) runs only if the user added it to sandbox.excludedCommands, and then only as a command on its own: not inside a script, after cd or &&, or with a redirect. If the sandbox refuses a command you need, ask the user with canary jobs ask --setup ${a}, naming the command.`),A(`Clocks: setup ${l.batchSetupMinutes} min from now (ends when you start the first job); each job ${l.jobMinutes} min of working time; the batch ${l.batchMinutes} min, after which the work in hand finishes and jobs not yet started move to another batch; a wait on the user ${l.userWaitMinutes} min. Waiting on the user doesn't count.`),A(`Keep your listener running as a background command, and start it again each time it returns: canary jobs listen ${a}`),A(`Evidence for a job goes in ${N(c1(a),"packs","<job>")}/pack.json; the format: canary jobs schema`),A(""),A("Jobs, one at a time, in this order:"),e.jobs.forEach(({job:d,brief:m,state:u,earlierFiles:p,earlier:f},k)=>{A(`${k+1}. Job ${d.id}: ${d.scenario.title} [${u}]`),A(` What must hold: ${d.scenario.assertion}`);for(let x of zv(d.scenario.target))A(` ${x}`);d.scenario.target&&A(` ${xv(d.scenario.target)}`),d.scenario.claim&&A(` Claim, where the wrong outcome is the failure: ${Object.entries(d.scenario.claim).filter(([,x])=>x).map(([x,y])=>`${x}: ${y}`).join("; ")}`),A(` How to prove it (${m.method}): ${m.plan}`),A(` Data to set up: ${m.dataSetup}`),A(` Must run for real: ${m.reasons.dependsOn.join("; ")}`),m.reasons.faked.length&&A(` May be faked, only to set up or observe: ${m.reasons.faked.map(x=>`${x.part} (${x.why})`).join("; ")}`),m.reasons.limits.length&&A(` Known limits: ${m.reasons.limits.map(x=>`${x.part} (${x.why})`).join("; ")}`),m.questions.length&&A(` Expected questions: ${m.questions.join(" | ")}`),m.permissions.length&&A(` Access to ask for: ${m.permissions.join(" | ")}`),d.scenario.relatedFiles.length&&A(` Related files: ${d.scenario.relatedFiles.join(", ")}`),d.recheckOf?(A(` Re-check of an earlier result. Last time, ${kv(d.recheckOf.verdict)}.${d.recheckOf.reasoning?` Earlier reasoning: ${d.recheckOf.reasoning}`:""}`),d.recheckOf.scope?.trim()&&A(` The person put part of this check out of scope, in their own words: "${d.recheckOf.scope.trim()}". This re-check is judged only within what they kept: a case their words rule out neither fails nor holds it. Run what they kept, and say what you left out because of their words.`),d.recheckOf.reproduction&&A(` Earlier reproduction: ${d.recheckOf.reproduction.steps.join(" Then ")} Look for: ${d.recheckOf.reproduction.observe}`),p.length&&A(` Earlier files (fetch each into the copy with canary jobs earlier ${d.id} <path>): ${p.join(", ")}`)):f&&(A(` Tried first on Canary's computer, which runs only the code. What it needs from this machine: ${f.needs.replace(/[.\s]+$/,"")}.${f.reasoning?` What that attempt showed: ${f.reasoning}`:""}`),p.length&&A(` Its scripts (fetch each into the copy with canary jobs earlier ${d.id} <path>, and reuse what still fits): ${p.join(", ")}`))})}function Cv(e,t){let n=q=>JSON.stringify(t.jobs.find(r=>r.jobId===q)?.title??q??"");switch(e.type){case"stop":return e.reason==="setup_limit"?"Canary: stop. Setup ran past its limit, so this batch's jobs not yet run have ended. Clean up what you started; the listener will report the batch's end.":`Canary: stop job ${e.jobId} (${n(e.jobId)}): ${e.reason==="time_limit"?"its time ran out":"the batch's time ran out"}. Stop its processes now and send what you already have by ${e.submitBy}: canary jobs submit ${e.jobId}${t.proofs[e.jobId]?` --proof ${t.proofs[e.jobId]}`:""}`;case"time_up":return`Canary: this batch's time is up. Finish the work you have in hand, which keeps its own time, and start nothing else: the jobs you hadn't started moved to another batch for another verifier (${e.jobIds.map(q=>`${q} ${n(q)}`).join("; ")}). The listener will report the batch's end.`;case"proof_request":return`Canary asks for more proof on job ${e.jobId} (${n(e.jobId)}), request ${e.proofRequestId}: ${e.request} When the work in hand is done, pick it up with canary jobs start ${e.jobId} --proof ${e.proofRequestId}, write ${w2(t.batchId,e.jobId,e.proofRequestId)}/delta.json, then canary jobs submit ${e.jobId} --proof ${e.proofRequestId}.`;case"wait_over":return`Canary: no answer from the user in time, so ${e.jobId?`job ${e.jobId} (${n(e.jobId)})`:"the jobs not yet run"} ended; it can be re-checked. Move on.`;case"result":return`Canary result for job ${e.record.jobId} (${n(e.record.jobId)}): ${e.record.verdict??"no verdict"}.`;case"batch_ended":return e.reason==="set_aside"?`Canary: batch ${t.batchId}'s checks were set aside for the user to decide on, so start none of them. Finish setting the app up first, so the checks after you reuse it: once your setup script runs clean, smoke check included, keep it with canary jobs keep ${t.batchId} ${A1}/<file> --what "<what it sets up>", then stop what you started and run: canary jobs finish ${t.batchId}`:`Canary: batch ${t.batchId} has ended. Stop what you started and run: canary jobs finish ${t.batchId}`}}async function Av(e,t){let n=!1;for(let q of de([{runId:e.runId}]).filter(r=>r.batchId===e.batchId&&r.status==="answered")){let r=B0(q.path);r.texts.length!==0&&(r.first&&await i1(`/cli/jobs/batches/${e.batchId}/resume`,{session:t,batchKey:e.key,method:"POST"}).catch(()=>{}),A(r.first?`Canary: ${rc(q)}`:`Canary: more on ${q.id} from the coding agent: ${r.texts.join(" | ")}`),n=!0)}return n}async function Iv(e){let t=C1(),n=st(e),q=Date.now(),r=null,s=!1;for(setInterval(()=>void Av(n,t).then(i=>{i&&process.exit(0)}).catch(()=>{}),2e3).unref();;){if(n.owner&&!u2(n.owner))return A("Canary: the Claude Code session ended; this listener stops.");if(Date.now()-q>Zf){if(r)return A("Canary: can't reach Canary right now; run the listener again.");let a=x2(e)?[]:gv(n);return A(a.length?`Canary: no news yet. Of the scripts you have run, ${a.join(", ")} ${a.length>1?"aren't kept as they stand":"isn't kept as it stands"}, so if setup runs out of time a try after this one starts without ${a.length>1?"them":"it"}. Keep what sets the app up now, with how far it gets, and again as it gets further (a script for one job stays unkept): canary jobs keep ${e} ${A1}/<file> --what "<what it sets up and how far it gets>"`:"Canary: no news yet.")}let i;try{i=await i1(`/cli/jobs/batches/${e}/events?after=${n.cursor}`,{session:t,batchKey:n.key,timeoutMs:l0}),s&&A("Canary: reachable again."),r=null,s=!1}catch(a){if(ir(a))return Ie(e,l=>{l.ended=!0}),A(`Canary: stop working on batch ${e}: ${a.message} Clean up what you started and run: canary jobs finish ${e}`);if(!De(a))throw a;r??=Date.now(),!s&&Date.now()-r>Y5&&(s=!0,A("Canary: can't reach Canary right now; still trying.")),await ct(O2);continue}n=Ie(e,a=>{a.cursor=i.cursor;for(let l of i.events)l.type==="stop"&&l.jobId&&(a.stopped[l.jobId]=l.submitBy),l.type==="proof_request"&&l.jobId&&(a.proofs[l.jobId]=l.proofRequestId),l.type==="result"&&delete a.proofs[l.record.jobId],l.type==="batch_ended"&&(a.ended=!0,a.setAside=l.reason==="set_aside")});for(let a of i.events)a.type==="batch_ended"&&$t([{runId:n.runId}],e,"all"),a.type==="wait_over"&&($t([{runId:n.runId}],e,a.jobId),a.jobId&&t0(e,a.jobId));for(let a of i.events)A(Cv(a,n));if(i.events.length>0)return}}var ri=(e,t)=>{if(e.stopped[t])throw new E("job_stopped","Canary stopped this job; only its final evidence can still be sent.",`canary jobs submit ${t}${e.proofs[t]?` --proof ${e.proofs[t]}`:""}`)},qc=e=>{if(e===void 0)return null;if(!/^[1-9]\d*$/.test(e))throw new E("usage","--proof takes the request's number, as the listener printed it.");return Number(e)};async function Rv(e,t){let n=k2(e);ri(n,e),await ac(n);let q=qc(t.proof);await U1(()=>i1(`/cli/jobs/${e}/start`,{session:C1(),batchKey:n.key,json:{proofRequestId:q}}),N2).catch(async s=>{throw s instanceof L&&s.status>=500?await Ar(n,e,s,q?"picking up this request":"starting this job",`canary jobs start ${e}${q?` --proof ${q}`:""}`):s});let r=!x2(n.batchId);v0(n.batchId,"start",e,q),r&&!n.kept?.length&&A(`If the setup script you just ran isn't kept for later checks yet, or you changed a kept one, keep it now: canary jobs keep ${n.batchId} ${A1}/<file> --what "<what it sets up>"`),A(q?`Picked up request ${q} on job ${e}: its 15 minutes run from now. Answer in ${w2(n.batchId,e,q)}/delta.json.`:`Started job ${e}. Its working time is counting; waiting on the user doesn't count.`)}async function Tv(e,t){let n=C1(),q,r;if(t.wait){let i=X().filter(a=>a.sessionId===n).flatMap(a=>de([{runId:a.runId}]).filter(l=>l.id.toLowerCase()===t.wait.toLowerCase()&&l.batchId===a.batchId).map(l=>({q:l,s:a})))[0];if(!i)throw new E("no_such_question",`No question ${t.wait} from a batch taken in this session.`);({q,s:r}=i)}else{if(!e||!!t.job==!!t.setup)throw new E("usage","Ask about one job (--job <job>) or about setting up (--setup <batch>), with the question text.");if(e.length>U5)throw new E("question_too_long",`A question is one need, in a line or two: this one is ${e.length} characters, and ${U5} is the most.`,"Ask for the one thing that blocks you most, with what the check can't show without it. Ask the next once this one is answered.");r=t.job?k2(t.job):st(t.setup);let o=Object.keys(r.stopped).find(l=>!r.finalSent.includes(l));if(o)throw new E("job_stopped",`Job ${o} was stopped and its final evidence is due; no question can hold it up.`,`canary jobs submit ${o}${r.proofs[o]?` --proof ${r.proofs[o]}`:""}`);let i=r;await ac(i);let a=()=>U1(()=>i1(`/cli/jobs/batches/${i.batchId}/pause`,{session:n,batchKey:i.key,json:{jobId:t.job??null}}),N2);try{await a()}catch(l){if(l instanceof L&&l.status>=500)throw await Ar(i,t.job??null,l,"taking your question",`canary jobs ask ${t.job?`--job ${t.job}`:`--setup ${i.batchId}`} "<question>"`);let c=de([{runId:i.runId}]).some(h=>h.batchId===i.batchId&&h.status==="open");if(!(l instanceof L&&l.code==="already_waiting")||c)throw l;await i1(`/cli/jobs/batches/${i.batchId}/resume`,{session:n,batchKey:i.key,method:"POST"}),await a()}try{q=D5(r.checkout,{runId:r.runId,batchId:r.batchId,jobId:t.job??null,verifier:ei(r.batchId),text:e})}catch(l){throw await i1(`/cli/jobs/batches/${r.batchId}/resume`,{session:n,batchKey:r.key,method:"POST"}).catch(()=>{}),l}A(`Asked ${q.id}; the clock is paused while the user answers. If this command is cut off: canary jobs ask --wait ${q.id}. Nothing else you write reaches the coding agent or the user while you work: only a question, and your last message when you end.`)}let s=Date.now()+Qf;for(;;){let o=X().find(a=>a.batchId===r.batchId);if(!o||o.ended)return $t([{runId:r.runId}],r.batchId,"all"),A(`Canary: batch ${r.batchId} has ended, so ${q.id} needs no answer. Stop what you started and run: canary jobs finish ${r.batchId}`);let i=B5(q.path);if(i?.status==="answered"){let a=B0(q.path).first,l=rc(i),c=!0;try{a&&({resumed:c}=await U1(()=>i1(`/cli/jobs/batches/${r.batchId}/resume`,{session:n,batchKey:r.key,method:"POST"})))}catch(h){if(!ir(h))return A(`${l} Couldn't restart the clock with Canary; run canary jobs ask --wait ${q.id} to try again.`)}return A(c?l:`${l} It came after the wait ran out, so ${q.jobId?"that job":"the jobs not yet run"} already ended.`)}if(i?.status==="expired")return A(`No answer to ${q.id} in time: Canary ended ${q.jobId?`job ${q.jobId}`:"this batch's jobs not yet run"}; it can be re-checked. Move on.`);if(Date.now()>=s)return A(`No answer to ${q.id} yet. The clock stays paused; Canary ends the job when the wait on the user runs out, and your listener will say so. To keep waiting: canary jobs ask --wait ${q.id}`);await ct(2e3)}}var U5=350;function rc(e){let t=e.userWords??[],n=e.userSpoke?t.length?` (passed on by the coding agent; what the user said since you asked: ${t.map(r=>JSON.stringify(r)).join("; ")}. Access or approval counts only as far as their own words give it)`:"":" (from the coding agent, with the user saying nothing in between: it settles facts about the project, not access or approval)",q=(e.more??[]).map(r=>` Added later: ${r.text}`).join("");return`Answer to ${e.id}${n}: ${e.answer}${q} If this leaves part of what you need open, or asks you something back, ask again with one question that carries what was asked for.`}async function Ov(e){let t=N(B(),"runs"),n=(k1(t)?j2(t):[]).flatMap(q=>{try{return j2(N(t,q,"results")).filter(r=>r.endsWith(".md")&&r.startsWith(e.toLowerCase())).map(r=>N(t,q,"results",r))}catch{return[]}});if(n.length!==1)throw new E("not_found",n.length?"More than one check's record starts with that id.":"No record of that check on this machine.","Use the check id its result gave.");A(Re(n[0],"utf8").trimEnd())}var sc=e=>V1(C1()).find(t=>t.runId.startsWith(e))?.runId??e;async function Ev(e){let t=sc(e),{stopped:n}=await i1(`/cli/jobs/runs/${t}/stop`,{session:C1(),method:"POST"});Jn(X().filter(q=>q.runId===t&&q.sessionId===C1()).map(q=>q.batchId),Wt+3e4),A(n?`Stopped ${n} check${n>1?"s":""} of run ${t}: each ends as stopped by the user and can be tried again in this run. Stop the run's verifiers with TaskStop; Canary cleans up what they started.`:`Nothing in run ${t} was still running.`)}async function Nv(e,t){let n=sc(e),q=(()=>{try{return j2(N(s1(n),"results")).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5))}catch{return[]}})(),r=t.map(i=>q.find(a=>a.startsWith(i.toLowerCase()))??i),s=i=>i1(`/cli/jobs/runs/${n}/retry`,{session:C1(),method:"POST",json:{jobIds:r,...i?{source:i}:{}}}),o;try{({retried:o}=await s())}catch(i){if(!(i instanceof L&&i.code==="code_needed"))throw i;({retried:o}=await s(await Pv(n)))}A(o?`${o===1?"1 check":`${o} checks`} of run ${n} that couldn't run or ${o===1?"was stopped goes":"were stopped go"} again in the same run. Start your listener again if it has stopped: it announces their batch. Setup starts from what earlier tries kept.`:`Nothing in run ${n} can be tried again: only a check that couldn't run or was stopped can, and ${r.length?"the ones named are still going":"none of its checks is one"}.`)}async function Pv(e){let t=Y(N(s1(e),"source.json")),n=N(s1(e),"source.bundle");if(!t||!k1(n))throw new E("code_gone","This run's code is no longer on this machine, so its checks can't go again.","Tell the user its checks can't go again in this run; a new request checks the code as it is now.");let q=Q();if(!q)throw new E("not_logged_in","Not logged in to Canary.","Run canary login.");let r=Y(N(s1(e),"request.json")),s=typeof r?.workspaceId=="string"&&typeof r.repositoryId=="string"?{workspaceId:r.workspaceId,repositoryId:r.repositoryId}:null;if(!s){let i=await je(te(C1()).runs[e]?.checkout??_t(),q);s={workspaceId:i.workspaceId,repositoryId:(await Pe({...i,token:q})).repositoryId}}let o=await Dq({bundlePath:n,manifest:t,...s,token:q,baseUrl:a1()});return{...o.source,uploadId:o.uploadId}}async function jv(e,t){let n=C1(),q=W5(V1(n),e);if(q.status==="expired")return A(`The wait for ${q.id} had already run out: the check timed out. Keep this answer in canary.md; the check can be re-checked.`);let r=(te(n).userAt??"")>q.askedAt,s=(te(n).said??[]).filter(i=>i.at>q.askedAt).map(i=>i.text),o=q.status==="answered";H5(q,t,r,s),A(o?`Added to the answer to ${q.id}: its verifier gets it with its listener's next news.`:`Answered ${q.id}: its verifier reads it within seconds, from its waiting question or its listener.${r?" If the user's answer gives access or approval, record it in canary.md now, in their words with the date, under the section for that kind of answer: a later check finds it there and doesn't ask again, and this verifier acts on it only once it is there.":""}`)}async function Mv(e,t){let n=C1(),q=k2(e);if(q.finalSent.includes(e))throw new E("final_sent","This job's final evidence after its stop was already sent.");let r=qc(t.proof),s=r?"with this answer":"with this job's evidence",o=`canary jobs submit ${e}${r?` --proof ${r}`:""}`,i=w2(q.batchId,e,r??void 0),a=N(dt(c1(q.batchId)),"packs",e,...r?[`proof-${r}`]:[]);if(k1(i)&&dt(i)!==a)throw new E("pack_folder_link",`${i} is a link, so the evidence would be read from somewhere else.`,"Make it a plain folder holding the evidence files.");let l,c;try{if(!wl(q.batchId))throw new Error("the plugin's hooks saw nothing of this batch's verifier");l=Oh(q.batchId,e,r);let d=l.calls.at(-1);d?.kind==="command"&&d.ended==="not_run"&&/\bcanary\s+jobs\s+submit\b/.test(d.what)&&l.calls.pop();let m=de([{runId:q.runId}]).filter(p=>p.batchId===q.batchId).map(({id:p,jobId:f,text:k,status:x,answer:y,userSpoke:b})=>({id:p,jobId:f,text:k,status:x,answer:y,userSpoke:b??!1})),u=l.calls.filter(p=>p.kind==="file"&&p.ended==="ran").map(p=>p.what);c=g5(i,r?"delta":"pack",{jobId:e,commit:q.code.commit,tree:q.code.treeHash,uncommitted:q.code.uncommitted??null,scripts:Lv(u1(q),q.batchId,e,r),scriptsFrom:N(u1(q),A1),diff:await i5(u1(q)),warmCopy:q.warm??!1,stopped:!!q.stopped[e],startedAt:l.jobStartedAt,observed:{calls:l.calls,earlierCalls:l.earlierCalls,minutes:l.minutes,stopped:!!q.stopped[e],putBack:await r5(dt(u1(q)),u),questions:m},byHand:Eh(q.batchId)},r,A0(q.checkout))}catch(d){if(d instanceof E)throw d;if(X0(d))throw new E("not_enough_disk","This machine ran out of disk while Canary put this job's evidence together.",`Tell the user, and send it again once more disk is free: ${o}`);let m=tc(d);throw m?Zq(m):await Ar(q,e,d,s,o)}$v(q,e,c.pack),Fv(q,e,r,c.pack,l);let h={session:n,batchKey:q.key};try{let d=await U1(()=>i1(`/cli/jobs/${e}/evidence`,{...h,json:c.upload}),N2);for(let m of d.missing){let u=c.bytes.get(m);await U1(()=>i1(`/cli/jobs/${e}/evidence/${d.uploadId}?path=${encodeURIComponent(m)}`,{...h,method:"PUT",bytes:u,timeoutMs:nv(u.length)}),N2)}await U1(()=>i1(`/cli/jobs/${e}/evidence/${d.uploadId}/complete`,{...h,method:"POST"}),N2)}catch(d){throw d instanceof L&&d.status>=500?await Ar(q,e,d,s,o):d}if(q.stopped[e]&&Ie(q.batchId,d=>void d.finalSent.push(e)),v0(q.batchId,"sent",e,r),t0(q.batchId,e),A(`Sent ${r?`the answer to request ${r} on`:"the evidence for"} job ${e}; Canary is judging it, and the result reaches your listener.`),c.hidden.length){let d=new Map;for(let{name:p,path:f}of c.hidden)d.set(p,[...new Set([...d.get(p)??[],f])]);let m=[...d].filter(([p])=>p!==A2).map(([p,f])=>`${p} (in ${f.join(", ")})`),u=d.get(A2);A(`Canary hid secret values before sending: ${[...m.length?[`these by their names: ${m.join("; ")}`]:[],...u?[`${A2} (in ${u.join(", ")})`]:[]].join("; and ")}. That is best effort, so keep secret values out of what you record.`)}}async function Ar(e,t,n,q,r){let s;try{s=await Pn(e.sessionId,t?{jobId:t,batchKey:e.key}:{batchId:e.batchId,batchKey:e.key},n)}catch(o){return Y0(o)?o:new E("internal_error",at,`Run it again in a minute: ${r}`)}return s.requeued?new E("internal_error",`Canary hit an internal error ${q}, so it took this batch back to try its checks once more with a fresh verifier.`,`Stop what you started and run canary jobs finish ${e.batchId}.`):s.ended>0?new E("internal_error",`Canary hit an internal error ${q}, so ${t?"this job":"this batch's checks not yet sent"} ended; ${t?"it":"they"} can be tried again.`,t?"Go on with your next job; your listener says if the batch has ended.":`Stop what you started and run canary jobs finish ${e.batchId}.`):new E("internal_error",`Canary hit an internal error ${q}, so Canary judges ${t?"the job":"the batch's checks"} on the evidence it already has.`,t?"Go on with your next job.":`Run canary jobs finish ${e.batchId}.`)}function Lv(e,t,n,q){let r=N(e,A1),s=N(w2(t,n),A1),o=q?N(w2(t,n,q),`proof-${q}-scripts`):s,i=[],a=l=>{for(let c of k1(l)?j2(l,{withFileTypes:!0}):[]){let h=N(l,c.name),d=J5(r,h).split(Un).join("/");if(c.name.startsWith(".")||c.name==="node_modules"||d===P2||i.length>=Bv)continue;if(c.isDirectory()){a(h);continue}if(!c.isFile()||M2(h).size>oc||!Pt.test(`${U0(o)}/${d}`))continue;let m=Re(h);if(m.subarray(0,8e3).includes(0)||q&&k1(N(s,d))&&Re(N(s,d)).equals(m))continue;Ht(ge(N(o,d)),{recursive:!0}),Bn(N(o,d),m);let{atime:u,mtime:p}=M2(h);Kf(N(o,d),u,p),i.push(`${U0(o)}/${d}`)}};return a(r),i}function Fv(e,t,n,q,r){let s=`${t}:${n??0}`;if(e.stopped[t]||e.sentBack?.includes(s))return;let o=r.calls.filter(h=>h.kind==="command"&&(h.ended==="ran"||h.ended==="failed")).length,i=e.jobMinutes??15,a=r.startedAt===null||r.minutes<i/3,l=r.startedAt===null?"It was never started":`It used ${Math.round(r.minutes)} of its ${i} minutes`,c="claim"in q?q.claim.verdict==="cannot_run"&&(o===0||a)&&[`This job is coming back as one that couldn't run. ${l}, and Canary's record shows ${o} command${o===1?"":"s"} run for it.`,"If any part of the scenario can run with what is allowed, run it and send what that shows: a check that never ran tells the user nothing. If nothing can, submit again as it is."]:o===0&&q.steps.length===0&&q.files.length===0&&[`This answer comes with nothing run, no step and no file. ${l}.`,"Run what the request asks, or say in the answer which earlier command already printed it. If neither is possible, say what stands in the way and submit again."];if(c)throw Ie(e.batchId,h=>void(h.sentBack=[...h.sentBack??[],s])),new E("nothing_run",c[0],c[1])}function $v(e,t,n){if(!("claim"in n)||n.claim.verdict==="cannot_run")return;let[q,r]=e.ports,s=e.targets?.[t];for(let o of n.ranOn.target.matchAll(/\b(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0)(?::(\d{1,5}))?|\[::1\](?::(\d{1,5}))?/g)){let i=Number(o[1]??o[2]??NaN);if(!(Number.isNaN(i)||i>=q&&i<=r)&&!(s&&Dv(s)===`${o[0].replace(/:\d+$/,"").toLowerCase()}:${i}`))throw new E("not_this_batch",`The evidence gives ${o[0]} as what was tested, which is outside this batch's ports (${q}-${r}), so it isn't the app in your copy.`,`Run the scenario against the app you started on your own ports and send what that shows. If the address was mistyped, correct ranOn.target${s?`; this job's running target is ${s}, as take printed it`:""}.`)}}function Dv(e){try{let t=new URL(e);return`${t.hostname.toLowerCase()}:${t.port||(t.protocol==="https:"?"443":"80")}`}catch{return null}}async function Wv(e,t){let n=k2(e);if(ri(n,e),!Pt.test(t))throw new E("usage",`${t} isn't a path from the earlier evidence.`,"Use a path take printed under earlier files.");let q=await U1(()=>Kl(`/cli/jobs/${e}/earlier?path=${encodeURIComponent(t)}`,{session:C1(),batchKey:n.key})),r=dt(u1(n)),s=ge(N(r,t));for(;!k1(s);)s=ge(s);if(dt(s)!==r&&!dt(s).startsWith(r+Un))throw new E("outside_copy",`${t} leads outside the copy through a link.`);Ht(ge(N(r,t)),{recursive:!0});let o=N(r,t);k1(o)&&(o=`${o}.earlier`);let i=Yf(o,zr.O_WRONLY|zr.O_CREAT|zr.O_EXCL|zr.O_NOFOLLOW,420);try{Xf(i,q)}finally{Vf(i)}A(`Wrote ${t} from the earlier evidence to ${o}.`)}async function Hv(e,t){let n=st(e),q=Number(t.pid),r=Number.isInteger(q)&&q>1?Oe(q):null;if(r===null)throw new E("no_such_process",`No running process ${t.pid}.`);if(!b0(q,n))throw new E("not_this_batch",`Process ${q} doesn't run from this batch's copy or its folder, so the batch won't stop it. If you found it on one of your ports and it isn't Docker publishing a container you labelled, another program may hold that port.`,"Record only processes this batch started; Docker containers are removed by their label. If your app lost its port, start it on another port from your block.");Ie(e,s=>void s.processes.push({pid:q,startedAt:r,what:t.what??"background process"})),A(`Recorded process ${q}; finish stops it with the batch.`)}var Ir="kept.json",oc=256*1024,Bv=80;async function _v(e,t,n){let q=st(e),r=dt(u1(q)),s=g2(q.checkout),o=A0(q.checkout),i=[];for(let l of t){let c=b1(_n(r,l));if(!L2(c,[N(r,A1)])||!M2(c).isFile()||M2(c).size>oc||U0(c)===P2)throw new E("not_a_setup_script",`${l} isn't a script in ${N(r,A1)}.`,"Keep the setup script, and any file it runs, from that folder.");let h=Re(c,"utf8"),d=[...[q.batchId,E2(q.batchId)].filter(u=>h.includes(u)).map(u=>`this batch's id (${u})`),...[r,u1(q),c1(q.batchId),q.checkout,Sr()].filter(u=>h.includes(u)).slice(0,1).map(u=>`a path on this machine (${u})`),...[...h.matchAll(/\b4[2-5]\d{3}\b/g)].slice(0,1).map(u=>`a port written out (${u[0]})`),...o.filter(u=>h.includes(u.value)).slice(0,1).map(u=>`the value of ${u.name}`)];if(d.length)throw new E("holds_this_batch",`${l} holds ${d.join(", ")}, so the next verifier would have to rewrite it.`,`Read those from ${A1}/${P2} (ports as offsets from CANARY_PORT_FIRST, names ending in CANARY_SHORT, secrets from the file CANARY_SECRETS names), run it clean once more, and keep it again.`);let m=nc(h);if(m)throw new E("unlabelled_container",`${l} starts a container without this batch's label (${m.trim().slice(0,100)}), so nothing would remove it if the batch ended while it ran.`,`Start every container with --label "$CANARY_DOCKER_LABEL" (from ${A1}/${P2}), run it clean once more, and keep it again.`);i.push({name:J5(N(r,A1),c).split(Un).join("/"),text:h})}let a=Y(N(s.scripts,Ir))??{};for(let{name:l,text:c}of i)Ht(ge(N(s.scripts,l)),{recursive:!0,mode:448}),Bn(N(s.scripts,l),c,{mode:384}),a[l]={what:n.what,keptAt:new Date().toISOString()};F1(N(s.scripts,Ir),a),Ie(e,l=>void(l.kept=[...new Set([...l.kept??[],...i.map(c=>c.name)])])),A(`Kept ${i.map(l=>l.name).join(", ")} for later checks of this repository: the next take puts ${i.length>1?"them":"it"} in the verifier's copy.`)}async function Uv(e){Ie(e,t=>void(t.readyAt??=new Date().toISOString())),A("Noted: the app is up. The user now sees that setup is over and that you are getting the checks ready.")}async function Gv(e,t){let n=k2(e);ri(n,e);let q=Date.now()+ev;for(;!kl(t,n.batchId,e);){if(Date.now()>=q)throw new E("target_busy",`Another verifier is still writing to ${t}.`,"Work without writing to it, or report why the job couldn't run.");await ct(2e3)}A(`You may write to ${t}; the lock is released when this job's evidence is sent or the batch finishes.`)}async function Vv(e,t){if(!k1(N(c1(e),"state.json")))return Bt(c1(e),{recursive:!0,force:!0}),A(`Nothing of batch ${e} is on this machine.`);let n=st(e),q=C1();if(n.sessionId!==q)throw new E("other_session","This batch was taken by another Claude Code session.");let r=n.ended?void 0:(await Or(q)).runs.flatMap(o=>o.batches).find(o=>o.batchId===n.batchId);if(r&&r.state!=="ended"&&r.holder===Yo(n.key)){if(!t.giveBack)throw new E("batch_open","This batch is still open: Canary may still ask this verifier for more proof, which needs the copy and the running app.",`Wait until the listener reports the batch ended. If its verifier ended and won't come back: canary jobs finish ${e} --give-back`);let o=!1,{requeued:i,ended:a}=await U1(()=>i1(`/cli/jobs/batches/${e}/give-back`,{session:q,batchKey:n.key,method:"POST"}),N2).catch(async l=>{if(!(l instanceof L&&l.status>=500))throw l;return o=!0,Pn(q,{batchId:e,batchKey:n.key},l).catch(()=>{throw new E("internal_error",at,`Run it again in a minute: canary jobs finish ${e} --give-back`)})});A(i?`Gave batch ${e} back: jobs it hadn't sent evidence for will go to a fresh verifier.`:a>0?o?`Canary hit an internal error taking batch ${e} back, so it ended the jobs it hadn't sent evidence for: start no verifier for it, and tell the user they can be tried again.`:`Gave batch ${e} back. It has had all the verifiers it may, so Canary ended the jobs it hadn't sent evidence for: start no verifier for it, and tell the user they can be re-checked.`:`Gave batch ${e} back. Nothing was left in it to start, so start no verifier for it; what it sent is still being judged.`)}let s=await Ft(n);A(`Cleaned up batch ${e}: stopped what was still running from its copy and its folder, and removed its files. The copy of the code stays for later checks of this repository.`);for(let o of s)A(`Left in place: ${o}`)}async function ic(){if(process.stdin.isTTY)return{};let e=[],t=new Promise(n=>{process.stdin.on("end",n),setTimeout(n,300).unref()});process.stdin.on("data",n=>e.push(n)),await t,process.stdin.destroy();try{let n=JSON.parse(Buffer.concat(e).toString("utf8"));return n&&typeof n=="object"?n:{}}catch{return{}}}async function Jv(){try{let e=await ic(),t=e.agent_id,n=e.hook_event_name,q=e.tool_input;if(n==="PreToolUse"&&q?.subagent_type==="canary:verifier"&&(q.isolation||q.name))return A(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:og}}));if(n==="PostToolUse"&&e.tool_name==="AskUserQuestion"&&typeof e.session_id=="string"){let S=te(e.session_id).asking;if(S&&k1(S)){let v=uh(e,S);v.commands!==null&&oh(S,v.commands),v.envFiles&&ih(S,v.envFiles.files,v.envFiles.answer)}return await Tr(e.session_id,Gn,hg(e))}if(n==="UserPromptSubmit"&&typeof e.session_id=="string")return typeof e.prompt=="string"&&Kv.test(e.prompt)?void 0:await Tr(e.session_id,tv,typeof e.prompt=="string"?[e.prompt]:[]);let r=e.agent_type==="canary:verifier"&&typeof t=="string"?t:null,s=_f("sha256").update(JSON.stringify([e.tool_name??null,e.tool_input??null])).digest("hex").slice(0,16),o={call:typeof e.tool_use_id=="string"?e.tool_use_id:s,same:s},i=n==="PermissionRequest"?ng(e):null;if(i===!0)return A(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"allow"}}}));if(i&&!i.shared){let S=r&&ne(r);return S&&z2(S,{same:s},"sent_back",i.reason),A(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"deny",message:_0(i)}}}))}if(!r)return;if(n==="PermissionRequest")return await ag(r,s,i?i.reason:"");if(n==="PermissionDenied")return Yv(r,o,e);await lg(r,typeof n=="string"?n:"",s,typeof e.duration_ms=="number"?Math.max(0,Math.round(e.duration_ms)):0);let a=String(e.tool_name),l=e.tool_input,c=Rr.has(a)?l?.file_path??l?.notebook_path:null,h=a==="Bash"&&typeof l?.command=="string"?l.command:null,d=typeof c=="string"||h!==null&&!Mt(h);if(n==="PostToolUse"||n==="PostToolUseFailure"){let S=d?ne(r):null;if(!S)return;z2(S,o,n==="PostToolUse"?"ran":"failed",Qv(e)),h!==null?y0(S,o.call,Zv(e)):typeof c=="string"&&n==="PostToolUse"&&Ah(S,o.call,b1(c));return}if(n==="PostToolBatch")return eg(r,e);if(n!=="PreToolUse")return;let m=(S,v,w)=>{S&&z2(S,o,"sent_back",w),A(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:v}}))};if(typeof c=="string"){let S=ne(r);S&&fr(S,o,"file",b1(c));let v=qg(r,e);v&&m(S,v,v.includes("the user's own word")?"it changes the user's part of the notes":"outside the verifier's own folders");return}let u=S=>!!S&&jt(S)?.commands==="run";if(h===null){let S=ne(r),v=si.has(a)&&u(S&&X().find(w=>w.batchId===S)?.checkout||(typeof e.cwd=="string"?e.cwd:null))?Z0(e):null;v&&m(null,_0(v),v.reason);return}let p=/\bcanary\s+jobs\s+(?:take|listen)\s+([0-9a-fA-F-]{36})\b/.exec(h)?.[1];p&&ne(r)!==p&&yl(r,p);let f=ne(r);if(f&&d){let S=e.tool_input;fr(f,o,"command",h,typeof S.description=="string"?S.description:"",S.run_in_background===!0)}let k=f?X().find(S=>S.batchId===f):void 0,x=k?.checkout??(typeof e.cwd=="string"?e.cwd:null),y=u(x)?null:M5(h),b=u(x)&&!Mt(h)?Z0(e):null,z=k?tg(h,Er(k,k.checkout),k.checkout):null,C=k?sg(h,k,typeof e.cwd=="string"?e.cwd:k.checkout):null,I=ig(r,h);b?m(f,_0(b),b.reason):I?m(f,I,"the job moved to another batch"):Xv.test(h)?m(f,"Canary: not run. Answering a question, resetting the user's choices and stopping or retrying a run are the coding agent's commands, for what the user said: a verifier asks, and waits for the answer.","it is the coding agent's command"):z?m(f,z,"it names what Canary itself keeps about the checks"):C?m(f,C,"it writes a file outside the verifier's own folders"):y&&m(f,L5(y),y)}catch{}}function Yv(e,t,n){let q=ne(e),r=n.tool_input,s=n.tool_name==="Bash"&&typeof r?.command=="string"?r.command:null;!q||s===null&&!Rr.has(String(n.tool_name))||(s!==null&&Mt(s)&&fr(q,t,"command",s),z2(q,t,"blocked",typeof n.reason=="string"?n.reason:""))}var Kv=/^\s*(?:<task-notification>|<agent-message\b|Another Claude session sent a message)/,Rr=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Xv=/\bcanary\s+(?:jobs\s+(?:answer|approvals|stop|retry)|answer)\b/;function Qv(e){if(typeof e.error=="string")return e.error.trim();let t=e.tool_response;return t?.backgroundTaskId?"started in the background; how it ended isn't recorded":typeof t?.returnCodeInterpretation=="string"?t.returnCodeInterpretation:""}function Zv(e){if(typeof e.error=="string")return e.error;let t=e.tool_response;if(typeof t?.persistedOutputPath=="string")try{return Re(t.persistedOutputPath,"utf8")}catch{}return typeof t?.stdout=="string"?t.stdout:""}function eg(e,t){let n=ne(e),q=Array.isArray(t.tool_calls)?t.tool_calls:[];if(!n||q.length===0)return;let r=Rh(n);for(let s of q){if(typeof s.tool_use_id!="string"||typeof s.tool_response!="string")continue;let o=/^Command running in background .*Output is being written to: (\S+\.output)/.exec(s.tool_response)?.[1];o?Ch(n,s.tool_use_id,o):r.has(s.tool_use_id)&&z2(n,{call:s.tool_use_id},"not_run",s.tool_response)}}function tg(e,t,n){let q=$1(n),r=q?[H1(q).dir]:[];for(let s of new Set([B(),b1(B()),N(ge(B()),"approvals"),b1(N(ge(B()),"approvals"))]))for(let o=e.indexOf(s);o!==-1;o=e.indexOf(s,o+1)){let i=/^[^\s'"`;|&<>()]*/.exec(e.slice(o))[0];if(!t.holds(b1(i))&&!L2(b1(i),r))return`Canary: not run. ${i} is part of what Canary itself keeps about the checks, not a file of yours: your own are your copy, your batch's folder, and this repository's notes, secrets and kept scripts.`}return null}function ng(e){let t=e.tool_input,n=String(e.tool_name),q=(n==="Bash"||n==="Monitor")&&typeof t?.command=="string"?t.command:null;if(q!==null&&Mt(q))return!0;let r=t?.file_path??t?.notebook_path??t?.path,s=typeof r=="string"?b1(r):null;if(typeof e.agent_id!="string"){let h=typeof e.cwd=="string"?_t(e.cwd):null,d=h&&$1(h);if(!h||!d)return!1;let m=H1(d),u=[m.dir,N(B(),"runs")];return q!==null?ch(q,p=>L2(b1(p.startsWith("~/")?N(Sr(),p.slice(2)):_n(e.cwd,p)),u)):s===null?!1:si.has(n)?L2(s,u):Rr.has(n)&&[m.canaryMd,m.secrets].map(b1).includes(s)&&jt(h)?.commands==="run"}if(e.agent_type!=="canary:verifier")return!1;let o=ne(e.agent_id),i=o?X().find(h=>h.batchId===o):void 0,a=i?.checkout??(typeof e.cwd=="string"?e.cwd:null);if(!a||jt(a)?.commands!=="run")return!1;let l=Er(i,a),c=Z0(e);if(q!==null){let h=d=>{try{return M2(d).size<=262144?Re(d,"utf8"):null}catch{return null}};return c??wr(q,{roots:l.folders.flatMap(d=>[...new Set([d,b1(d)])]),cwd:a,home:Sr(),ports:i?.ports??[0,0],label:S2(i?.batchId??""),composeProject:C2(i?.batchId??""),read:h,dockerOwn:i&&((d,m)=>$h(i.batchId,d,m))})??!0}return c||(Rr.has(n)?s===null?!1:l.holds(s)||{reason:`it changes ${r}, which isn't one of the checks' own files`,shared:!1}:!0)}var si=new Set(["Read","Grep","Glob"]);function Z0(e){let t=String(e.tool_name),n=e.tool_input,q=Sr(),r=E5(q,N(G(),"config.json"));if((t==="Bash"||t==="Monitor")&&typeof n?.command=="string")return j5(n.command,q,r);if(!si.has(t))return null;let s=h=>h.replace(/^~(?=[\\/]|$)/,q),o=n?.file_path??n?.path,i=_n(typeof e.cwd=="string"?e.cwd:process.cwd(),typeof o=="string"?s(o):"."),a=t==="Glob"&&typeof n?.pattern=="string"?_n(i,s(n.pattern).replace(/[*?[{].*$/s,"")):null,l=[typeof o=="string"?i:null,a].flatMap(h=>h===null?[]:[b1(h).toLowerCase()]),c=r.find(h=>{let d=b1(h).toLowerCase();return l.some(m=>m===d||m.startsWith(d+Un))});return c?{reason:`it reads ${D0(c,q)}, where the user keeps credentials`,shared:!1,secret:!0}:null}function b1(e){let t=_n(e);for(let n=t;;n=ge(n))try{return N(dt(n),t.slice(n.length))}catch{if(n===ge(n))return t}}var L2=(e,t)=>t.map(b1).some(n=>e===n||e.startsWith(n+Un));function Er(e,t){let n=$1(t),q=n&&H1(n),r=e?[u1(e),c1(e.batchId)]:[],s=e?b1(N(c1(e.batchId),"state.json")):null;return{folders:r,holds:o=>L2(o,r)&&o!==s||q!==null&&o===b1(q.canaryMd)}}function qg(e,t){let n=t.tool_input,q=n?.file_path??n?.notebook_path,r=ne(e),s=r?X().find(o=>o.batchId===r):void 0;return!s||typeof q!="string"?null:Er(s,s.checkout).holds(b1(q))?rg(s,b1(q),t):`Canary: not written. ${q} is outside your own folders, so nothing would remove it when the batch ends. Write the checks' scripts in your copy (${u1(s)}) and scratch files in ${b2(s.batchId)}; keep a setup script for later checks with canary jobs keep.`}function rg(e,t,n){let q=$1(e.checkout);if(!q||t!==b1(H1(q).canaryMd))return null;let r=n.tool_input,s;try{s=Re(t,"utf8")}catch{return null}let o=Array.isArray(r?.edits)?r.edits:[r??{}],i=typeof r?.content=="string"?r.content:s;if(typeof r?.content!="string")for(let l of o){if(typeof l.old_string!="string"||typeof l.new_string!="string"){i=null;break}i=l.replace_all?i.split(l.old_string).join(l.new_string):i.replace(l.old_string,()=>l.new_string)}let a=l=>l.includes(Ce)?l.slice(0,l.indexOf(Ce)):l;return i!==null&&a(i)===a(s)?null:`Canary: not written. Everything in canary.md above "${Ce.replace(/^#+ /,"")}" is the user's own word (their instructions, the targets they cleared, their test logins), and only the coding agent records it, from what the user said. Add what you learned under "${Ce.replace(/^#+ /,"")}" and "What worked and what failed", and ask a question for anything that needs the user.`}function sg(e,t,n){let q=Er(t,t.checkout).folders,r=b5(e,n).find(s=>!s.startsWith("/dev/")&&!L2(b1(s),q));return r?`Canary: not run. It writes ${r}, which is outside your own folders, so nothing would remove it when the batch ends. Keep every file a command of yours makes in your copy, in ${b2(t.batchId)} or in the job's pack folder; to run something in the background, use your shell tool's own background option on the whole command, which keeps what it prints and tells you when it ends.`:null}var _0=e=>e.secret?`Canary: not run, because ${e.reason}. The user isn't asked about your commands, so they never reach the user's keys and sign-ins. Check what you can without them, and don't reach them another way.`:`Canary: not run, because ${e.reason}. The user isn't asked about your commands, so they may only remove or change what your checks created: files in your copy and your batch's folder, and Docker objects under your batch's label (canary jobs finish removes those). If this is yours, keep it there; otherwise leave it as it is, and don't reach it another way.`,og="Canary: not started. A Canary verifier is started with no `isolation` and no `name`: it builds its own copy of the code outside this checkout and has to run on this machine, in this session. Start it again without them.";function ig(e,t){let n=[...t.matchAll(/\bcanary\s+jobs\s+(?:start|submit|earlier|lock)\s+([0-9a-fA-F-]{36})\b/g),...t.matchAll(/\bcanary\s+jobs\s+ask\b[^\n;&|]*--job[=\s]+([0-9a-fA-F-]{36})\b/g)].map(i=>i[1]),q=ne(e);if(n.length===0||!q)return null;let r=X(),s=r.find(i=>i.batchId===q),o=s&&n.find(i=>!s.jobs.some(a=>a.jobId===i)&&r.some(a=>a.jobs.some(l=>l.jobId===i)));return o?`Canary: not run. Job ${o} is no longer in your batch: it moved to another batch, and another verifier runs it. Finish the work you have in hand, then wait for the listener to report your batch's end.`:null}async function ag(e,t,n=""){let q=ne(e),r=q?X().find(s=>s.batchId===q&&s.claimed):void 0;if(r){bl(e,t,r.batchId,n);try{await i1(`/cli/jobs/batches/${r.batchId}/pause`,{session:r.sessionId,batchKey:r.key,json:{jobId:null,approval:!0},timeoutMs:Gn}),En(r.batchId)}catch(s){s instanceof L&&!De(s)?(On(rr(e).filter(o=>o.call===t).map(o=>o.name)),En(r.batchId)):Zo(r.batchId,{call:"pause"})}}}async function lg(e,t,n,q){let r=t==="PostToolUse"||t==="PostToolUseFailure";if(!r&&t!=="PostToolBatch"&&t!=="SubagentStop")return;let s=rr(e).filter(i=>!r||i.call===n),o=X().find(i=>s.some(a=>a.batchId===i.batchId))?.sessionId;o&&t!=="SubagentStop"&&await Tr(o);for(let i of new Set(s.map(a=>a.batchId))){let a=s.filter(c=>c.batchId===i);On(a.map(c=>c.name));let l=X().find(c=>c.batchId===i);!l||rr(e).some(c=>c.batchId===i)||await lc(l,r?q:0).catch(()=>{})}}function hg(e){let t=e.tool_response?.answers;return t&&typeof t=="object"?Object.values(t).filter(n=>typeof n=="string"):[]}async function Tr(e,t=Gn,n=[]){if(Object.keys(te(e).runs).length===0)return;let q=new Date().toISOString(),r=n.map(s=>s.trim()).filter(Boolean).map(s=>({at:q,text:s.length>300?`${s.slice(0,299)}\u2026`:s}));Ae(e,s=>({...s,userAt:q,said:[...s.said??[],...r].slice(-10)})),await i1("/cli/jobs/answered",{session:e,method:"POST",timeoutMs:t}).catch(()=>{})}async function ac(e){$e(e.batchId).length&&await Tr(e.sessionId),await lc(e),On($e(e.batchId))}async function lc(e,t=0){try{await i1(`/cli/jobs/batches/${e.batchId}/resume`,{session:e.sessionId,batchKey:e.key,json:{workedMs:t,approval:!0},timeoutMs:Gn})}catch(n){if(!(n instanceof L)||De(n))throw Zo(e.batchId,{call:"resume",since:Date.now()-t}),n}En(e.batchId)}async function cg(e,t){let n=$e(e.batchId).length>0,q={session:e.sessionId,batchKey:e.key,timeoutMs:Gn};try{t.call==="pause"&&n&&await i1(`/cli/jobs/batches/${e.batchId}/pause`,{...q,json:{jobId:null,approval:!0}}),t.call==="resume"&&!n&&await i1(`/cli/jobs/batches/${e.batchId}/resume`,{...q,json:{workedMs:Math.max(0,Date.now()-t.since),approval:!0}})}catch(r){if(!(r instanceof L)||De(r))return}En(e.batchId,t.call)}function Jn(e,t){e.length!==0&&V5(process.execPath,[process.argv[1],"jobs","clean-ended",...e,"--after",String(t)],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref()}async function dg(e,t){await ct(Number(t.after)||0);let n=C1();for(let q of X().filter(r=>e.includes(r.batchId)&&r.sessionId===n&&!r.left))await Ft(q).catch(()=>{})}async function ug(e){await mg(e).catch(()=>{})}async function mg(e){if(!e.end){let n=(await ic()).session_id,q=(typeof n=="string"?n:null)??process.env.CLAUDE_CODE_SESSION_ID;if(!q||Object.keys(te(q).runs).length===0&&!Ul(q))return;V5(process.execPath,[process.argv[1],"jobs","session-end","--end",q],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref();return}let t=e.end;await U1(()=>i1("/cli/jobs/session-end",{session:t,method:"POST",timeoutMs:1e4})).catch(()=>{});for(let n of X().filter(q=>q.sessionId===t))await Ft(n).catch(()=>{});for(let{runId:n}of V1(t))Bt(N(s1(n),"source.bundle"),{force:!0});Gl(t)}function hc(e){let t=e.command("jobs",{hidden:!0}).description("Canary's checks on this machine (run by the Canary plugin's skill and verifiers)");t.command("watch").description("the coding agent's listener: prints new checks, questions and results").action(v1(av)),t.command("list").description("this session's checks, batches and open questions").action(v1(dv)),t.command("take <batch>").description("take a batch: build its copy and claim it").action(v1(uv)),t.command("listen <batch>").description("the verifier's listener: returns after the next news, or about 9 minutes").action(v1(Iv,{urgent:!0})),t.command("start <job>").option("--proof <n>","pick up request <n> for more proof").description("start a job, or pick up a request for more proof").action(v1(Rv,{urgent:!0})),t.command("ask [text]").option("--job <job>","the job the question is about").option("--setup <batch>","a question not about one job").option("--wait <question>","keep waiting for an earlier question").description("ask the coding agent and wait for the answer").action(v1(Tv,{urgent:!0})),t.command("stop <run>").description("stop a run's checks that haven't finished, at the user's word").action(v1(Ev)),t.command("retry <run> [checks...]").description("try again a run's checks that couldn't run, the ones named or all, in the same run, at the user's word").action(v1(Nv)),t.command("record <check>").description("print a check's full record").action(v1(Ov,{local:!0})),t.command("answer <question> <text>").description("answer a verifier's question").action(v1(jv,{local:!0})),t.command("submit <job>").option("--proof <n>","send the answer to request <n>").description("send a job's evidence").action(v1(Mv,{urgent:!0})),t.command("earlier <job> <path>").description("fetch a file of the earlier evidence for a re-check").action(v1(Wv)),t.command("created <batch>").requiredOption("--pid <pid>","the process id").option("--what <what>","what it is").description("record a background process for cleanup").action(v1(Hv,{local:!0})),t.command("keep <batch> <paths...>").requiredOption("--what <what>","what the script sets up, in a few words").description("keep a setup script that ran clean for later checks of this repository").action(v1(_v,{local:!0})),t.command("ready <batch>").description("say the app is up, so the user sees that setup is over").action(v1(Uv,{local:!0})),t.command("lock <job> <target>").description("write to a target marked safe for writes, one verifier at a time").action(v1(Gv,{local:!0})),t.command("finish <batch>").option("--give-back","hand an open batch back first").description("clean up a batch once it has ended").action(v1(Vv)),t.command("session-end").option("--end <session>").description("called by the plugin's session-end hook").action(v1(ug,{sweep:!1})),t.command("clean-ended <batches...>").option("--after <ms>","wait this long first","0").description("clean up ended batches after a wait (started by Canary itself)").action(v1(dg,{sweep:!1,local:!0})),t.command("hook").description("called by the plugin's hooks on a verifier's tool calls").action(Jv),t.command("approvals <action>").description("reset: forget the user's choices for this repository, so they are asked again").action(v1(async n=>{if(n!=="reset")throw new E("usage","The only action is reset.");ah(_t()),A("Forgotten. Canary will say when to ask the user again: before the next verifier starts.")},{local:!0})),t.command("schema").description("the evidence format").action(v1(async()=>A(y5),{sweep:!1}))}g();e1();fq();ie();Le();import{appendFileSync as Og,existsSync as Eg}from"node:fs";import{join as zc}from"node:path";g();Gs();g();var cc=["claude","codex","cursor"];function dc(e,t=0,n=[]){if(typeof e=="string")e&&n.push(e);else if(t<3&&e&&typeof e=="object")for(let q of Object.values(e))dc(q,t+1,n);return n}var ut=e=>typeof e=="string"&&e?e:void 0,pg=new Set(["Bash","PowerShell","Monitor"]);function uc(e,t,n=process.env,q=process.platform){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;if(e==="cursor"){let l=Array.isArray(r.workspace_roots)?r.workspace_roots:[],c=ut(r.cwd)??ut(l[0])??ut(n.CURSOR_PROJECT_DIR)??process.cwd(),h=ut(r.conversation_id)?{chat:ut(r.conversation_id)}:{};return r.hook_event_name==="beforeShellExecution"&&typeof r.command=="string"?{kind:"shell",command:r.command,cwd:c,shell:q==="win32"?"powershell":"posix",...h}:r.hook_event_name==="beforeMCPExecution"&&typeof r.tool_name=="string"?{kind:"tool",toolName:r.tool_name,cwd:c,...h}:null}if(r.hook_event_name!=="PreToolUse"||typeof r.tool_name!="string")return null;let s=ut(r.cwd)??process.cwd(),o=ut(r.session_id)?{chat:ut(r.session_id)}:{},i=r.tool_input&&typeof r.tool_input=="object"?r.tool_input:{};if(pg.has(r.tool_name)&&typeof i.command=="string")return{kind:"shell",command:i.command,cwd:s,shell:r.tool_name==="PowerShell"?"powershell":"posix",...o};let a=e==="codex"&&r.tool_name==="exec"?dc(typeof r.tool_input=="string"?r.tool_input:i):[];return a.length?{kind:"script",toolName:r.tool_name,texts:a,cwd:s,...o}:{kind:"tool",toolName:r.tool_name,cwd:s,...o}}function mc(e,t){if(e==="cursor"){if(t.decision!=="deny")return"";let n=t.message??"Canary held this call.";return JSON.stringify({permission:"deny",user_message:n,agent_message:n})}return t.decision==="deny"?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:t.message??"Canary held this call."}}):t.message?JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:t.message}}):""}Mq();g();p1();var Ut=(e,t)=>({decision:"allow",cause:e,...t?{message:t}:{}}),pc=e=>e.replace(/[\x00-\x1f\x7f]+/g,"?");function Nr(e){if(e.mode==="off")return Ut("mode_off");if(!e.trigger)return Ut("not_a_trigger");if(!e.login)return null;if(!e.login.ok)return Ut(e.login.cause);if(e.chat===void 0)return null;if(e.chat===null)return Ut("no_chat");if(!e.lookup)return null;if(!e.lookup.ok)return Ut(e.lookup.cause,`Canary couldn't be asked about this push (${pc(e.lookup.detail)}), so it went ahead.`);let{hold:t}=e.lookup;return t.state==="clear"?Ut("clear"):t.state==="remind"?{decision:"deny",cause:t.state,message:t.agent}:e.skip===void 0?null:e.skip?Ut("skipped",`Canary: the person chose to continue without verifying (${pc(e.skip.reason)}). Tell them it was pushed without a Canary check.`):{decision:"deny",cause:t.state,message:t.agent}}var fg=new Set(["clear","none","running","open","remind"]);async function fc(e,t,n,q={}){let r=AbortSignal.timeout(q.timeoutMs??Ot);try{let s=new URLSearchParams({workspaceId:e.workspaceId,chat:t,...n?{raised:n}:{}}),o=await W(`/api/v1/cli/hold?${s.toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:Fo(r,q.signal)});return!o||typeof o!="object"||!fg.has(String(o.state))?{ok:!1,cause:"unknown_state",detail:"Canary answered in a way this CLI version does not understand (update the CLI)"}:o.state!=="clear"&&typeof o.agent!="string"?{ok:!1,cause:"unknown_state",detail:"Canary's answer had no words to show"}:{ok:!0,hold:o}}catch(s){return r.aborted?{ok:!1,cause:"lookup_timeout",detail:`Canary did not answer within ${Math.round((q.timeoutMs??Ot)/1e3)} s`}:s instanceof L&&s.status>=400&&s.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${s.status}: ${s.message}${s.fix?` (${s.fix})`:""}`}:s instanceof L&&s.status>=500?{ok:!1,cause:"lookup_error",detail:`Canary answered ${s.status}`}:{ok:!1,cause:"lookup_unreachable",detail:s instanceof Error?s.message:String(s)}}}g();bo();g();import{homedir as vg}from"node:os";import{basename as gg,isAbsolute as yg,resolve as wg}from"node:path";var bg=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),kg=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,vc=e=>e.replace(/\\(.)/g,(t,n)=>n==="n"?`
|
|
3334
|
+
`:n==="t"?" ":n);function bc(e,t){for(let n of e)for(let q of n.matchAll(kg)){let r=q[4]!==void 0?[...q[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(o=>vc(o[1]??o[2]??"")).join(" "):vc(q[1]??q[2]??q[3]??""),s=ai(r,t);if(s)return s}return null}function kc(e,t){let n=!e.includes("__");if(!n&&!e.startsWith("mcp__"))return null;let q=bg.get(n?e:e.slice(e.lastIndexOf("__")+2));return q?{action:q,via:"mcp",dir:t}:null}function zg(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]==="\\"){n++;continue}let q=e[n]==="$"&&e[n+1]==="("?2:e[n]==="`"?1:0;if(!q)continue;let r=jr(e,n+q,q===2?")":"`");t.push(r.tokens),n=r.end-1}return t}var Pr=!1;function jr(e,t,n){let q=[],r=[],s="",o=!1,i=!1,a=!0,l=t,c=0,h=()=>{o&&q.push({word:s,quoted:i,bare:a}),s="",o=!1,i=!1,a=!0},d=u=>{h(),q.push({op:u})},m=(u,p)=>{let f=jr(e,u,p);return q.push({sub:f.tokens}),s+="$()",o=!0,f.end};for(;l<e.length;){let u=e[l],p=e[l+1];if(n==="`"&&u==="`")return h(),{tokens:q,end:l+1};if(n===")"&&u===")"&&c===0)return h(),{tokens:q,end:l+1};if(u==="\\"&&!Pr){p===`
|
|
3305
3335
|
`||(s+=p??"",o=!0),l+=2;continue}if(u==="'"){o||(a=!1);let f=e.indexOf("'",l+1);s+=e.slice(l+1,f<0?void 0:f),o=!0,i=!0,l=f<0?e.length:f+1;continue}if(u==='"'){for(o||(a=!1),o=!0,i=!0,l++;l<e.length&&e[l]!=='"';)e[l]==="\\"&&!Pr&&l+1<e.length&&/[$`"\\\n]/.test(e[l+1])?(s+=e[l+1],l+=2):e[l]==="$"&&e[l+1]==="("?l=m(l+2,")"):e[l]==="`"?l=m(l+1,"`"):(s+=e[l],l++);l++;continue}if(u==="#"&&!o){for(;l<e.length&&e[l]!==`
|
|
3306
3336
|
`;)l++;continue}if(u==="<"&&p==="<"&&e[l+2]!=="<"){let f=/^<<(-?)[ \t]*(?:'([^']*)'|"([^"]*)"|\\?([^\s;&|<>()]+))/.exec(e.slice(l));if(f){h(),r.push({end:f[2]??f[3]??f[4]??"",stripTabs:f[1]==="-",literal:f[4]===void 0||f[0].includes("\\")}),l+=f[0].length;continue}}if(u===`
|
|
3307
3337
|
`){d(`
|
|
3308
3338
|
`),l++;for(let f of r.splice(0))for(;;){let k=e.indexOf(`
|
|
3309
|
-
`,l),x=e.slice(l,k<0?void 0:k);if(l=k<0?e.length:k+1,(f.stripTabs?x.replace(/^\t+/,""):x)===f.end||k<0)break;if(!f.literal)for(let y of zg(x))q.push({sub:y})}continue}if(u===" "||u===" "||u==="\r"){h(),l++;continue}if(u===">"||u==="<"){let f=u===">";h(),l++;let k=!1;for(;l<e.length&&(e[l]===">"||e[l]==="&"||e[l]==="|");)e[l]==="&"&&(k=!0),l++;for(;l<e.length&&(e[l]===" "||e[l]===" ");)l++;let x=l;for(;l<e.length&&!/[\s;&|()<>`]/.test(e[l]);)l++;if(f&&!k){let y=e.slice(x,l);y&&q.push({write:y})}continue}if(u==="&"&&p===">"){h(),l++;continue}if((u==="&"||u==="|")&&p===u){d(u+u),l+=2;continue}if(u==="$"&&p==="("){l=m(l+2,")");continue}if(u==="`"){l=m(l+1,"`");continue}if(u==="("){c++,d(u),l++;continue}if(u===")"){c=Math.max(0,c-1),d(u),l++;continue}if(u===";"||u==="&"||u==="|"){d(u),l++;continue}if(/[0-9]/.test(u)&&!o&&/^[0-9]+[<>]/.test(e.slice(l))){l++;continue}s+=u,o=!0,l++}return h(),{tokens:q,end:e.length}}var xg=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),Sg=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),
|
|
3310
|
-
`)}catch{}let h=
|
|
3339
|
+
`,l),x=e.slice(l,k<0?void 0:k);if(l=k<0?e.length:k+1,(f.stripTabs?x.replace(/^\t+/,""):x)===f.end||k<0)break;if(!f.literal)for(let y of zg(x))q.push({sub:y})}continue}if(u===" "||u===" "||u==="\r"){h(),l++;continue}if(u===">"||u==="<"){let f=u===">";h(),l++;let k=!1;for(;l<e.length&&(e[l]===">"||e[l]==="&"||e[l]==="|");)e[l]==="&"&&(k=!0),l++;for(;l<e.length&&(e[l]===" "||e[l]===" ");)l++;let x=l;for(;l<e.length&&!/[\s;&|()<>`]/.test(e[l]);)l++;if(f&&!k){let y=e.slice(x,l);y&&q.push({write:y})}continue}if(u==="&"&&p===">"){h(),l++;continue}if((u==="&"||u==="|")&&p===u){d(u+u),l+=2;continue}if(u==="$"&&p==="("){l=m(l+2,")");continue}if(u==="`"){l=m(l+1,"`");continue}if(u==="("){c++,d(u),l++;continue}if(u===")"){c=Math.max(0,c-1),d(u),l++;continue}if(u===";"||u==="&"||u==="|"){d(u),l++;continue}if(/[0-9]/.test(u)&&!o&&/^[0-9]+[<>]/.test(e.slice(l))){l++;continue}s+=u,o=!0,l++}return h(),{tokens:q,end:e.length}}var xg=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),Sg=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),gc=e=>/^(\/dev\/|\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\$TMPDIR|\$\{TMPDIR)/.test(e),mt=!1,Cg=new Set(["if","then","else","elif","fi","do","done","while","until","for","!","{","}","time"]),yc=new Set(["command","exec","builtin","nohup","noglob","nice","sudo","env"]),Ag=new Set(["sh","bash","zsh","dash","ksh"]),wc=6,Ig=new Set(["-c","--exec-path","--namespace","--super-prefix","--config-env","--attr-source"]);function oi(e,t){if(t===null||/[$`*?[]/.test(e.word))return null;let n=e.bare&&(e.word==="~"||e.word.startsWith("~/"))?vg()+e.word.slice(1):e.word;return e.bare&&n.startsWith("~")?null:yg(n)?n:wg(t,n)}function Rg(e,t){let n=t,q=0;for(;q<e.length;q++){let s=e[q].word;if(s==="-C"){n=e[q+1]?oi(e[q+1],n):null,q++;continue}if(s.startsWith("-C")&&s.length>2){n=oi({...e[q],word:s.slice(2)},n);continue}if(/^--(git-dir|work-tree)(=|$)/.test(s)){n=null,s.includes("=")||q++;continue}if(Ig.has(s)){q++;continue}if(!s.startsWith("-"))break}if(e[q]?.word!=="push")return null;let r=[];for(let{word:s}of e.slice(q+1)){if(s==="--")break;if(s==="--dry-run"||s==="--help"||s==="-h"||/^-[a-zA-Z]*n[a-zA-Z]*$/.test(s)||s==="--delete"||/^-[a-zA-Z]*d[a-zA-Z]*$/.test(s))return null;s.startsWith("-")||r.push(s)}return r.length>1&&r.slice(1).every(s=>s.startsWith(":"))?null:{dir:n}}function Tg(e){let t=[];for(let n=0;n<e.length;n++){let q=e[n].word;if(q==="--help"||q==="-h"||q==="--dry-run")return!1;if(q==="-R"||q==="--repo"){n++;continue}q.startsWith("-")||t.push(q)}return t[0]==="pr"&&(t[1]==="create"||t[1]==="new")}function ii(e,t,n){let q=t,r=[],s=!1,o=()=>{let i=r;r=[];let a=s;s=!1;let l=f=>(!f&&a&&(mt=!0),f),c=0,h=(f,k)=>f.bare&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(f.word)||!f.quoted&&(Cg.has(f.word)||yc.has(f.word)||!!k&&yc.has(k.word)&&f.word.startsWith("-"));for(;c<i.length&&h(i[c],i[c-1]);)c++;let d=i[c];if(!d)return l(null);let m=gg(d.word.replace(/\\/g,"/")).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase(),u=i.slice(c+1);if(m==="cd"||m==="pushd")return q=u[0]&&!u[0].word.startsWith("-")?oi(u[0],q):null,l(null);let p=(f,k)=>({action:f,via:"shell",dir:k,...mt?{editsFirst:!0}:{}});if(m==="git"){let f=Rg(u,q);if(f)return p("push",f.dir);let k=u.find(y=>!y.word.startsWith("-"))?.word,x=(k==="checkout"||k==="switch")&&u.some(y=>/^-(b|B|c|C|-orphan)$/.test(y.word));return k&&Sg.has(k)&&!x&&(mt=!0),l(null)}if(m==="gh")return Tg(u)?p("pr_create",q):l(null);if(m==="tee"?u.some(f=>!f.word.startsWith("-")&&!gc(f.word))&&(mt=!0):(xg.has(m)||(m==="sed"||m==="perl")&&u.some(f=>/^-[a-zA-Z]*i/.test(f.word)))&&(mt=!0),(m==="npm"||m==="pnpm"||m==="yarn")&&u[0]?.word==="version"&&(mt=!0),n<wc&&(Ag.has(m)||m==="eval")){let f=m==="eval"?0:u.findIndex(x=>/^-[a-zA-Z]*c[a-zA-Z]*$/.test(x.word))+1,k=m==="eval"?u.map(x=>x.word).join(" "):f>0?u[f]?.word:void 0;if(k)return l(ii(jr(k,0,null).tokens,q,n+1))}return l(null)};for(let i of e){if("word"in i){r.push(i);continue}if("write"in i){s=s||!gc(i.write);continue}if("sub"in i){let l=n<wc?ii(i.sub,q,n+1):null;if(l)return l;continue}let a=o();if(a)return a}return o()}function ai(e,t,n={}){if(!/\bpush\b/.test(e)&&!/\bpr\b/.test(e))return null;Pr=n.shell==="powershell",mt=!1;try{return ii(jr(e,0,null).tokens,t,0)}finally{Pr=!1,mt=!1}}var Ng=8e3,Pg=64*1024*1024;async function jg(e,t={}){let n=e.kind==="shell"?ai(e.command,e.cwd,{shell:e.shell}):e.kind==="script"?bc(e.texts,e.cwd):kc(e.toolName,e.cwd);if(!n)return e.chat&&e.kind!=="tool"&&j3(e.kind==="shell"?[e.command]:e.texts)&&L3(e.cwd,e.chat),Nr({mode:"on",trigger:null});let q={mode:zt(),trigger:n},r,s=()=>Math.max(250,Math.min(Ot,t.deadline?t.deadline-Date.now()-500:Ot)),o=[async()=>{Q1({cwd:e.cwd,agent:!0});let a=Q(),l=K().team?.id;if(!a){q.login={ok:!1,cause:"not_logged_in"};return}if(!l){q.login={ok:!1,cause:"no_workspace"};return}r={token:a,apiUrl:a1(),workspaceId:l},t.seen&&(t.seen.target=r),q.login={ok:!0}},async()=>{q.chat=e.chat??null},async()=>{q.lookup=await fc(r,e.chat,N4(e.chat),{timeoutMs:s(),signal:t.signal})},async()=>{q.skip=W4(e.chat)}],i=null;for(let a of o){if(i=Nr(q),i)break;await a()}if(i??=Nr(q)??{decision:"allow",cause:"crash"},q.lookup&&e.chat){let a=q.lookup.ok?q.lookup.hold:null,l=i.decision==="deny"&&a!==null,c=l&&Array.isArray(a.raise)?a.raise:[],h=l&&a.state==="open"&&a.requestId&&Array.isArray(a.open)&&a.open.length>0?{requestId:a.requestId,open:a.open}:void 0;j4(e.chat,c,h)}return i}async function Mg(e){let t=[],n=0;for await(let q of e){let r=typeof q=="string"?Buffer.from(q):q;if(n+=r.length,n>Pg)throw new Error("event too large");t.push(r)}return JSON.parse(Buffer.concat(t).toString("utf8").replace(/^\uFEFF/,""))}var Lg={claude:"claude-code",codex:"codex",cursor:"cursor"};async function Fg(e,t){Q1({harness:Lg[e]});let n=t.ceilingMs??Ng;Bi(250);let q=new AbortController,r,s=new Promise(c=>{r=setTimeout(()=>{q.abort(),c({decision:"allow",cause:"ceiling"})},n)}),o={},i=(async()=>{let c=await Mg(t.stdin);try{Eg(zc(G(),"hook-debug"))&&Og(zc(G(),"hook-events.log"),`${new Date().toISOString()} ${e} ${JSON.stringify(c)}
|
|
3340
|
+
`)}catch{}let h=uc(e,c);return h?jg(h,{signal:q.signal,deadline:Date.now()+n,seen:o}):{decision:"allow",cause:"not_a_trigger"}})().catch(()=>({decision:"allow",cause:q.signal.aborted?"ceiling":"crash"})),a=await Promise.race([i,s]);clearTimeout(r);let l=mc(e,a);return l&&await t.write(l),a.cause!=="not_a_trigger"&&t.note(`canary hook: ${a.decision} (${a.cause})`),await Fa(a,o.target),a}function xc(e){e.command("hook <harness>",{hidden:!0}).description("check an agent's push or pull request before it happens (called by the agent harness, not by people)").action(async t=>{if(cc.includes(t)){let n=Number(process.env.CANARY_HOOK_CEILING_MS)>0?Number(process.env.CANARY_HOOK_CEILING_MS):void 0;await Fg(t,{stdin:process.stdin,ceilingMs:n,note:q=>process.stderr.write(q+`
|
|
3311
3341
|
`),write:q=>new Promise(r=>process.stdout.write(q+`
|
|
3312
|
-
`,()=>r()))})}process.exit(0)})}g();p1();e1();function
|
|
3313
|
-
`);let a=i.replace(/\.json$/,".md");return
|
|
3314
|
-
`):"";return{result:t.data.result??null,more:Fe(n),do:t.do}}var
|
|
3315
|
-
`),""}}function
|
|
3316
|
-
`:""}Canary \xB7 more to come: canary wait ${t}`)),process.exitCode=s}function
|
|
3317
|
-
`)}}var
|
|
3318
|
-
`))}async function
|
|
3319
|
-
`))}async function
|
|
3342
|
+
`,()=>r()))})}process.exit(0)})}g();p1();e1();function Sc(e){e.command("logout").description("Log out and revoke this device's token").option("--json","output machine-readable JSON").action(async t=>{let n=t.json===!0,q=Q();if(q)try{await W("/api/v1/cli/auth/logout",{method:"POST",token:q})}catch{}Vi();let r=!!process.env.CANARY_TOKEN;n?console.log(JSON.stringify({ok:!0,...r?{note:"CANARY_TOKEN env var still set"}:{}})):(console.log("Logged out."),r&&console.error("Note: CANARY_TOKEN is set in your environment \u2014 unset it to fully log out."))})}g();import{createHash as _g}from"node:crypto";import{mkdirSync as Ug,readdirSync as Gg,readFileSync as Vg}from"node:fs";import{dirname as Jg,join as ci}from"node:path";p1();e1();ie();g();import{copyFileSync as Cc,existsSync as Kn,mkdirSync as Rc,renameSync as $g,rmSync as li,writeFileSync as Ac}from"node:fs";import{dirname as Dg,join as _1}from"node:path";Le();var Mr=()=>({runs:{},told:{},said:[],endedAt:{}}),Wg=4*6e4;function Ic(e){let t=Y(_1(Nt(e.requestId),"request.json"));return e.session!==null&&t?.chat===e.session}function Lr(e){let t=Y(_1(Nt(e),"request.json"));return _t(typeof t?.checkout=="string"&&Kn(t.checkout)?t.checkout:process.cwd())}function Hg(e,t,n){let q=s1(t);Rc(q,{recursive:!0,mode:448});let r=Nt(e),s=_1(q,"source.bundle");if(!Kn(s)&&Kn(_1(r,"source.bundle")))try{$g(_1(r,"source.bundle"),s)}catch{Cc(_1(r,"source.bundle"),s),li(_1(r,"source.bundle"),{force:!0})}for(let i of["source.json",y2,"request.json"])!Kn(_1(q,i))&&Kn(_1(r,i))&&Cc(_1(r,i),_1(q,i));let o=Lr(e);Ae(n,i=>(i.owner=v2()??i.owner??null,i.runs[t]??={checkout:o},i))}var Yn=e=>typeof e=="string"&&e?e:null,Bg=e=>{try{return he(e,"job"),!0}catch{return!1}};function Tc(e,t,n){let q=Yn(e.data.checksRun),r=n.session;if(e.type==="ended"&&r&&Ic(n)&&li(_1(Nt(n.requestId),"source.bundle"),{force:!0}),!q||!r)return[];if(!Object.hasOwn(t.runs,q)){if(e.type==="ended"||!Ic(n))return[];Hg(n.requestId,q,r),t.runs[q]=[]}let s=e.data.cMessage;switch(typeof s=="number"&&Ae(r,o=>({...o,cursors:{...o.cursors,[q]:Math.max(o.cursors[q]??0,s)}})),e.type){case"checks_ready":{let o=(Array.isArray(e.data.batches)?e.data.batches:[]).map(a=>Yn(a.batchId)).filter(a=>a!==null);t.runs[q]=[...new Set([...t.runs[q]??[],...o])];let i=e.do.flatMap(a=>a.type==="start_verifier"?[a.batchId]:[]);return i.length>1&&Object.keys(ni(Lr(n.requestId))).length===0&&(t.held={...t.held,[q]:[...new Set([...t.held?.[q]??[],...i.slice(1)])]}),[]}case"verdict":{let o=e.data.record;if(!o?.jobId||!Bg(o.jobId))return[];let i=_1(s1(q),"results",`${o.jobId}.json`);Rc(Dg(i),{recursive:!0}),Ac(i,JSON.stringify(o,null,2)+`
|
|
3343
|
+
`);let a=i.replace(/\.json$/,".md");return Ac(a,qi(o,q)),o.verdict==="broken"?[{type:"read_record",command:`canary jobs record ${o.jobId}`}]:[]}case"batch_ended":{let o=Yn(e.data.batchId);if(!o)return[];t.said.includes(`ended:${o}`)||t.said.push(`ended:${o}`),ot(o);let i=X().find(a=>a.batchId===o&&a.sessionId===r);return e.data.reason==="set_aside"?(i&&Jn([o],(i.setupMinutes??30)*6e4+3e4),[]):((t.endedAt??={})[o]??=Date.now(),i&&Jn([o],Wt+3e4),[])}case"wait_over":{let o=Yn(e.data.batchId);return o&&$t([{runId:q}],o,Yn(e.data.jobId)),[]}case"ended":{let o=e.data.result?.running;return!(Array.isArray(o)&&o.length>0)&&!Vn(q)&&li(_1(s1(q),"source.bundle"),{force:!0}),[]}default:return[]}}var Oc=e=>e.asks.length>0||e.approvals.length>0||e.changed||(e.setups?.length??0)>0;function Ec(e,t,n=Date.now()){let q={asks:[],approvals:[],changed:!1},r=Object.keys(e.runs);if(!t.session||r.length===0)return{tell:q,do:[]};let s=t.session;for(let l of r)er(l);let o=[],i=l=>e.said.includes(`ended:${l}`);for(let l of de(r.map(c=>({runId:c})))){if(l.status!=="open"||i(l.batchId))continue;let c=e.told[l.path];c!==void 0&&n-c<Wg||(e.told[l.path]=n,l.text.trim()&&q.asks.push({text:l.text}),o.push({type:"answer",questionId:l.id,question:l.text,command:`canary jobs answer ${l.id} "<answer>"`}))}let a=Object.values(e.runs).flat().filter(l=>!i(l));for(let l of a)for(let c of $e(l)){let h=Nn(c);!h||e.said.includes(`approval:${c}`)||(e.said.push(`approval:${c}`),q.approvals.push({why:h}))}if(n-(e.setupsAt??0)>=mr){let l=pr(s,a);l.length>0&&(q.setups=l,e.setupsAt=n)}for(let[l,c]of Object.entries(e.endedAt??{}))n-c<Wt||e.said.includes(`unfinished:${l}`)||X().some(h=>h.batchId===l&&h.sessionId===s&&!h.left)&&(e.said.push(`unfinished:${l}`),o.push({type:"stop_verifier",batchId:l,restart:"never"}));for(let[l,c]of Object.entries(e.held??{})){let h=c.filter(u=>!i(u)&&!e.said.includes(`start:${u}`)),d=e.runs[l]??[];if(h.length===0||!(d.some(x2)||d.filter(u=>!c.includes(u)).every(i)))continue;let m=Lr(t.requestId);for(let u of h)e.said.push(`start:${u}`),In(rt(m))?o.push({type:"start_verifier",batchId:u}):Rn(u,s,m)}for(let l of Tn(s))!a.includes(l.batchId)||!In(rt(l.checkout))||An(l.checkout)||(ot(l.batchId),o.push({type:"start_verifier",batchId:l.batchId}));return{tell:q,do:o}}async function Nc(e,t){if(e.said.includes("changed")||Object.keys(e.runs).length===0)return!1;let n=Y(_1(Nt(t.requestId),"source.json"))?.treeHash;if(typeof n!="string")return!1;try{if((await hn(Lr(t.requestId))).treeHash===n)return!1}catch{return!1}return!0}Qe();var Yg=25,Fr=45e3,Kg=9*6e4,Xg=9e4,Qg=5,Zg=200,hi=(e,t)=>ci(G(),"requests",t===null?`${e}.json`:`${e}.${_g("sha256").update(t).digest("hex").slice(0,16)}.json`);function Pc(e,t){let n=Y(hi(e,t)),q=typeof n?.cursor=="number"&&Number.isInteger(n.cursor)&&n.cursor>=0?n.cursor:0,r=n?.checks&&typeof n.checks=="object"?{...Mr(),...n.checks}:void 0,s=Array.isArray(n?.held?.do)?{do:n.held.do,result:n.held.result,exitCode:n.held.exitCode===2?2:0}:void 0;return{cursor:q,ending:typeof n?.ending=="string"?n.ending:null,...r?{checks:r}:{},...s?{held:s}:{}}}function jc(e,t,n){Ug(Jg(hi(e,t)),{recursive:!0,mode:448}),F1(hi(e,t),n)}function Mc(e){let t=[...e].reverse().find(q=>q.type==="ended");if(!t)return null;let n=typeof t.data.more=="string"?t.data.more:Array.isArray(t.data.more)?t.data.more.filter(q=>typeof q=="string").join(`
|
|
3344
|
+
`):"";return{result:t.data.result??null,more:Fe(n),do:t.do}}var di=()=>kt();function Lc(e,t,n,q){let r=di();return W(`/api/v1/cli/requests/${e}/events?after=${n}&wait=${q}`,{token:t,signal:AbortSignal.timeout(Fr),...r?{headers:{"x-canary-session":r}}:{}}).then(s=>({...s,events:s.events.map(vn)}))}function ey(e,t,n){return W(`/api/v1/cli/requests/${e}/here`,{method:"POST",token:t,body:n,signal:AbortSignal.timeout(Fr)})}var ty=new Set(["start_verifier","stop_verifier","keep_late_answer"]),ny={read:Lc,pause:e=>new Promise(t=>setTimeout(t,e)),now:Date.now,onEvent:Tc,localNews:Ec,changedFiles:Nc,here:ey,session:di};async function qy(e,t,n,q,r=ny){let s=r.now()+q,o=null,i={...n},a={...Mr(),...n.checks},l={requestId:e,session:r.session()},c=()=>Object.keys(a.runs).length>0?{...i,checks:a}:i;for(;;){let h=s-r.now();if(h<=0)return{parts:[],place:c(),ended:!1};let d=Object.keys(a.runs).length>0,m;try{m=await r.read(e,t,i.cursor,Math.max(1,Math.min(d?Qg:Yg,Math.floor(h/1e3)))),o=null}catch(x){if(!z1(x)||(o??=r.now(),Number.isFinite(q)&&r.now()-o>Xg))throw x;await r.pause(2e3);continue}let u=[],p=i.cursor;for(let x of m.events){let y=r.onEvent(x,a,l),b=hy(x.data.checksRun),z=new Set(Object.values(a.held??{}).flat()),C=(b===null||Object.hasOwn(a.runs,b)?x.do:x.do.filter(v=>!ty.has(v.type))).filter(v=>v.type!=="start_verifier"||!z.has(v.batchId)),I=Fe(x.say),S=[...C,...y];(x.part||y.length>0)&&(I!==""||S.length>0)&&u.push({seq:x.seq,say:I,do:S}),i={cursor:x.seq,ending:x.type==="ended"&&typeof x.data.ending=="string"?x.data.ending:i.ending}}if(!m.ended){let x=r.localNews(a,l);m.events.some(b=>b.type==="verdict")&&await r.changedFiles(a,l)&&(x.tell.changed=!0);let y=Oc(x.tell)?await ry(r,e,t,x.tell):"";y&&x.tell.changed&&a.said.push("changed"),(y||x.do.length>0)&&u.push({seq:null,say:Fe(y),do:x.do})}let f=m.ended&&!m.events.some(x=>x.type==="ended")&&p>0,k=Mc(f?(await r.read(e,t,p-1,0)).events:m.events)?.result;if(m.ended||u.length>0)return{parts:u,place:c(),ended:m.ended,...k?{result:k}:{}}}}async function ry(e,t,n,q){try{return(await e.here(t,n,q)).say}catch(r){return process.stderr.write(`Canary couldn't word what happened on this machine (${r instanceof Error?r.message:String(r)}); what to do about it is still given.
|
|
3345
|
+
`),""}}function sy(e,t){let n={...Mr(),...e,runs:{...e?.runs},told:{...e?.told},said:[...e?.said??[]],endedAt:{...e?.endedAt},held:{...e?.held}};for(let[q,r]of Object.entries(t?.runs??{}))n.runs[q]=[...new Set([...n.runs[q]??[],...r])];for(let[q,r]of Object.entries(t?.held??{}))n.held[q]=[...new Set([...n.held[q]??[],...r])];for(let[q,r]of Object.entries(t?.told??{}))n.told[q]=Math.max(n.told[q]??0,r);for(let[q,r]of Object.entries(t?.endedAt??{}))n.endedAt[q]=Math.min(n.endedAt[q]??r,r);return n.said=[...new Set([...n.said,...t?.said??[]])],t?.setupsAt&&(n.setupsAt=Math.max(n.setupsAt??0,t.setupsAt)),n}async function oy(e,t){let n=[];for(;;){let q=await Lc(e,t,n.at(-1)?.seq??0,0);if(n.push(...q.events),q.ended||q.events.length<Zg)return{events:n,ended:q.ended}}}function ui(e,t,n){if(n instanceof L)return n.status===404?$(e,"request_not_found","Canary has no request with that id for you.","check the id Canary gave when you asked",3):n.status===401?$(e,"not_logged_in","Your Canary login is no longer valid.","run `canary login`",3):z1(n)?$(e,"unreachable","Canary couldn't be reached.",`run \`canary wait ${t}\` again in a minute`,2):$(e,n.code??"api_error",n.message,n.fix,n.status>=500?2:3);let q=yn(n);if(q)return $(e,"home_not_writable",q.message,q.fix,2);$(e,"internal_error",n instanceof Error?n.message:String(n),void 0,2)}function iy(e){try{let t=Vg(ci(G(),"requests",`${e}.asked`),"utf8").trim();return t?g2(t).canaryMd:null}catch{return null}}function F2(e,t,n,q,r,s,o){let i=e?iy(t):null;e?console.log(JSON.stringify({ok:!0,requestId:t,say:n,do:q,ended:r,...o?{result:o}:{},exitCode:s,...i?{canaryMd:i}:{}})):(n&&console.log(n),r||console.log(`${n?`
|
|
3346
|
+
`:""}Canary \xB7 more to come: canary wait ${t}`)),process.exitCode=s}function ay(e){if(le.test(e))return e;if(!/^[0-9a-f][0-9a-f-]{5,34}$/i.test(e))return null;let t;try{t=Gg(ci(G(),"requests"))}catch{return null}let n=new Set(t.map(q=>q.slice(0,36)).filter(q=>le.test(q)&&q.toLowerCase().startsWith(e.toLowerCase())));return n.size===1?[...n][0]:null}async function ly(e,t,n=!1){Q1({cwd:process.cwd(),agent:t,mode:"wait"});let q=Q();if(!q)return $(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!le.test(e))return $(t,"invalid_request_id","That isn't a request id.","use the id Canary gave when you asked",3);let r=di(),s=Pc(e,r);if(s.held){F2(t,e,"",s.held.do,!0,s.held.exitCode,s.held.result),jc(e,r,{cursor:s.cursor,ending:s.ending,...s.checks?{checks:s.checks}:{}});return}let o;try{o=await qy(e,q,s,n?Number.POSITIVE_INFINITY:Kg)}catch(u){return ui(t,e,u)}let i=Pc(e,r),a=o.parts.filter(u=>u.seq===null||u.seq>i.cursor),l={...o.place,cursor:Math.max(o.place.cursor,i.cursor),...o.place.checks||i.checks?{checks:sy(i.checks,o.place.checks)}:{}},c=a.flatMap(u=>u.do),h=[...c.filter(u=>u.type==="ask"),...c.filter(u=>u.type!=="ask")],d=fn(a.map(u=>u.say)),m=l.ending==="failed"?2:0;i.held?(F2(t,e,d,h,!1,0),l={...l,held:i.held}):t&&o.ended&&d&&h.some(u=>u.type==="ask")?(F2(t,e,d,[],!1,0),l={...l,held:{do:h,...o.result?{result:o.result}:{},exitCode:m}}):F2(t,e,d,h,o.ended,m,o.result);try{jc(e,r,l)}catch(u){process.stderr.write(`Canary couldn't save where this wait got to (${u instanceof Error?u.message:String(u)}); the next wait may show these lines again.
|
|
3347
|
+
`)}}var hy=e=>typeof e=="string"&&e.trim()?e.trim():null,cy=e=>e.filter(t=>t.type==="fix"||t.type==="pr_section"||t.type==="ask"&&t.options.some(n=>n.fix!==void 0));async function dy(e,t,n=!1){Q1({cwd:process.cwd(),agent:t,mode:"show"});let q=Q();if(!q)return $(t,"not_logged_in","Not logged in","run `canary login` first",3);let r=ay(e);if(!r)return $(t,"invalid_request_id","That isn't a request id this machine knows.","use the whole id Canary gave when you asked",3);try{let{events:s,ended:o}=await oy(r,q),i=Mc(s),a=n?Fe((await W(`/api/v1/cli/requests/${r}/repro`,{token:q,signal:AbortSignal.timeout(Fr)})).say):fn([...s.map(l=>l.say),i?.more??""]);F2(t,r,a,cy(i?.do??[]),o,0,i?.result??void 0)}catch(s){ui(t,r,s)}}var uy=(e,t,n)=>W(`/api/v1/cli/requests/${e}/answer`,{method:"POST",token:t,body:n,signal:AbortSignal.timeout(Fr)});async function my(e,t,n,q,r,s=uy){Q1({cwd:process.cwd(),agent:r,mode:"answer"}),n==="-"&&(n=await i0());let o=Q();if(!o)return $(r,"not_logged_in","Not logged in","run `canary login` first",3);if(!le.test(e))return $(r,"invalid_request_id","That isn't a request id.","use the id in the command Canary gave with its question",3);let i=n.trim();if(!i)return $(r,"no_answer","There's no answer in those words.",`put the answer in quotes: canary answer ${e} --id ${t} "<answer>"`,3);try{F2(r,e,Fe((await s(e,o,{id:t,text:i,from:q})).say),[],!1,0)}catch(a){ui(r,e,a)}}function Fc(e){e.command("wait").description("Follow a request: returns when something lands; run it again until the request ends").argument("<requestId>","the request's id, from Canary's answer").option("--json","one JSON document for agents").option("--no-timeout","for a wait run in the background: return only when something lands or the request ends").action((t,n)=>ly(t,n.json===!0,n.timeout===!1)),e.command("show").description("Show everything a request has said so far").argument("<requestId>","the request's id, from Canary's answer, or its first characters on the machine that asked").option("--repro","how to make each must-fix happen").option("--json","one JSON document for agents").action((t,n)=>dy(t,n.json===!0,n.repro===!0)),e.command("answer").description("Answer a request's question about which part of the code to read").argument("<requestId>","the request's id, from the command Canary gave with its question").argument("<answer...>","the answer, in quotes").requiredOption("--id <questionId>","the question's id, from the command Canary gave with it").addOption(new Ni("--from <who>","whose words these are: the person's, or the agent's own from its context").choices(["person","agent"]).default("agent")).option("--json","one JSON document for agents").action((t,n,q)=>my(t,q.id,n.join(" "),q.from,q.json===!0))}g();p1();e1();Qe();g();p1();Qe();var py={happy_path:"Core flow",boundary:"Edge case",failure:"Failure handling",security:"Security",parity:"Old-vs-new behavior",performance:"Performance",compatibility:"Compatibility",lifecycle:"Lifecycle",modality:"Interface"},fy=15e3;function vy(e){return e&&py[e]||"Other"}var gy=e=>{let t=e?.finding?.nextActionCodeRef??e?.codeRefs?.[0]??e?.checkReadback?.codeRefs?.[0]??null;return t?{file:t.file,line:t.startLine??null}:null},yy=e=>(Array.isArray(e?.evidence)?e.evidence:[]).filter(t=>t&&t.media&&typeof t.media.url=="string").map(t=>({kind:F(t.modality)||"evidence",caption:F(t.caption),url:t.media.url,expiresAt:t.media.expiresAt??null}));function wy(e,t,n){if(e.status!=="completed"||Se(e.materiality)===null)return null;let q=t??null,r=q?.isStatic===!0?"source":"runtime",s=e.result==="pass"?"passed":e.result==="fail"?"failed":"could_not_run",o=F(q?.assertion)||null;return{checkRunId:e.checkRunId,checkUrl:`${n}/checks/${e.checkRunId}`,scenarioId:e.stageBCheckId??e.checkRunId,category:vy(q?.lane),title:F(e.title),proof:r,status:s,whatWasTried:r==="source"?F(q?.finding?.whatWasTested)||null:F(q?.finding?.reproduce??q?.finding?.whatWasTested)||null,expected:o||F(q?.finding?.whatWasTested)||null,observed:F(q?.finding?.headline??q?.verdict?.reasonOneLiner)||null,assertion:o,location:gy(q),evidence:yy(q),fix:r==="source"&&F(q?.finding?.reproduce)||null,reason:s==="could_not_run"&&(F(q?.verdict?.reasonOneLiner)||gn[e.blockedReason??""])||null}}async function $c(e,t,n){let q=new Map,r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;for(let s of t)if(!(s.status!=="completed"||q.has(s.checkRunId)||!r.test(s.checkRunId)))try{q.set(s.checkRunId,await W(`/api/v1/red-team/runs/${e}/checks/${s.checkRunId}/finding`,{token:n.token,signal:AbortSignal.timeout(fy),...n.baseUrl?{baseUrl:n.baseUrl}:{}}))}catch{q.set(s.checkRunId,null)}return q}function Dc(e,t,n){let q=e.stageC.checks.map(r=>wy(r,t.get(r.checkRunId)??null,n.runUrl)).filter(r=>r!==null);return{runId:e.runId,runUrl:n.runUrl,repo:n.repo,treeHash:e.target.treeHash??"",files:n.files,reverifySourceRunId:e.reverifySourceRunId??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null,checks:q,passed:q.filter(r=>r.status==="passed").length,failed:q.filter(r=>r.status==="failed").length,couldNotRun:q.filter(r=>r.status==="could_not_run").length,errored:e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns}}var _c=new Set(["completed","failed","cancelled"]);function Wc(e){return _c.has(e.status)?null:e.status==="queued"?"queued":e.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function Hc(e){return e.status==="failed"||e.status==="cancelled"?"errored":e.status!=="completed"?e.status==="running"?"running":"pending":e.result==="pass"?"passed":e.result==="fail"?"failed":"could_not_run"}async function mi(e,t,n,q,r={}){let s=Q();if(!s)return $(e,"not_logged_in","Not logged in","run `canary login` first",3),null;if(t.some(o=>!le.test(o)))return $(e,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await W(n,{token:s,...q?{baseUrl:q}:{},...r})}catch(o){if(o instanceof L){if(o.status===404)return $(e,"not_found","no such run or check in your workspace",void 0,3,{httpStatus:404}),null;let i=!z1(o)&&o.status>=400&&o.status<500,a=o.fix??(o.status===401?"run `canary login`":i?void 0:"run the command again in a minute");return $(e,"api_error",o.message,a,i?3:2,{httpStatus:o.status}),null}throw o}}var Bc=e=>{if(!e?.file)return"";let t=e.startLine?`:${e.startLine}`:"",n=e.startLine&&e.endLine&&e.endLine>e.startLine?`-${e.endLine}`:"";return`${F(e.file)}${t}${n}`};async function by(e,t,n){let q=await mi(t,[e],`/api/v1/red-team/runs/${e}`,n);if(!q)return;let r=q.run,s=q.repository?.fullName??"";if(t){let l=r.stageC.checks.filter(m=>Se(m.materiality)!==null).map(m=>({checkRunId:m.checkRunId,scenarioId:m.stageBCheckId??m.checkRunId,title:F(m.title),status:Hc(m)})),c={runId:r.runId,status:r.status,progress:Wc(r),treeHash:r.target.treeHash??"",repo:s,reverifySourceRunId:r.reverifySourceRunId??null,startedAt:r.startedAt??null,completedAt:r.completedAt??null,failureMessage:r.failure?.publicMessage??null,checks:l,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,couldNotRun:l.filter(m=>m.status==="could_not_run").length,errored:r.stageC.failedCheckRuns+r.stageC.cancelledCheckRuns},h={},d=Q();if(_c.has(r.status)&&d){let m=await $c(e,r.stageC.checks,{token:d,...n?{baseUrl:n}:{}});h=Dc(r,m,{runUrl:`${Ee().replace(/\/+$/,"")}/runs/${e}`,repo:s,files:null})}return void console.log(JSON.stringify({ok:!0,...c,...h}))}let o=Wc(r),i=[`run ${F(r.runId)} \xB7 ${F(r.status)}${o?` \xB7 ${o}`:""}${r.target.treeHash?` \xB7 tree ${F(r.target.treeHash).slice(0,12)}`:""}`];r.failure?.publicMessage&&i.push(` ${F(r.failure.publicMessage)}`);let a=r.stageC;i.push(`checks ${a.checks.length} \xB7 ${a.results.pass} passed \xB7 ${a.results.fail} failed \xB7 ${a.results.blocked} could not verify \xB7 ${a.failedCheckRuns+a.cancelledCheckRuns} errored`);for(let l of a.checks){let c=Hc(l),h=c==="could_not_run"?"could not verify":c,d=l.result==="blocked"?gn[l.blockedReason??""]:void 0;i.push(` ${Se(l.materiality)??"P3"} ${h.padEnd(16)} ${F(l.title)} ${F(l.checkRunId)}${d?` (${d})`:""}`)}console.log(i.join(`
|
|
3348
|
+
`))}async function ky(e,t,n,q){let r=await mi(n,[e,t],`/api/v1/red-team/runs/${e}/checks/${t}/finding`,q);if(!r)return;if(n)return void console.log(JSON.stringify({ok:!0,runId:e,checkRunId:t,...r}));let s=[];s.push(F(r.finding?.headline)||"(no finding written for this check yet)"),r.verdict&&s.push(`verdict: ${F(r.verdict.result)}${r.verdict.reasonOneLiner?` \u2014 ${F(r.verdict.reasonOneLiner)}`:""}${r.isStatic?" (reasoned from the code, not run)":""}`),r.assertion&&s.push(`assertion: ${F(r.assertion)}`),r.observable&&s.push(`observable: ${F(r.observable)}`),r.checkReadback?.whyThisCheck&&s.push(`why this check: ${F(r.checkReadback.whyThisCheck)}`),r.finding?.whatWasTested&&s.push(`tested: ${F(r.finding.whatWasTested)}`),r.finding?.reproduce&&s.push(`reproduce: ${F(r.finding.reproduce)}`),r.finding?.nextActionCodeRef&&s.push(`\u2192 ${Bc(r.finding.nextActionCodeRef)}`);for(let o of r.codeRefs??[])s.push(` ref ${Bc(o)}${o.reason?` \u2014 ${F(o.reason)}`:""}`);for(let o of r.evidence??[])s.push(` evidence ${F(o.modality)}: ${F(o.caption)}${o.media?` ${F(o.media.url)}`:o.failureReason?` (${F(o.failureReason)})`:""}`);for(let o of r.verdict?.limitations??[])s.push(` limitation: ${F(o)}`);r.network?.failures?.length&&s.push(` network failures: ${r.network.failures.length}`),console.log(s.join(`
|
|
3349
|
+
`))}async function zy(e,t,n,q,r,s){if(await mi(r,[e,t],`/api/v1/red-team/runs/${e}/checks/${t}/report`,s,{method:"POST",body:{reported:n,...q?{note:q}:{}}})){if(r)return void console.log(JSON.stringify({ok:!0,runId:e,checkRunId:t,reported:n}));console.log(`reported ${n}${q?`: ${F(q)}`:""}`)}}async function xy(e,t,n){let q=Q();if(!q)return $(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!le.test(e))return $(t,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let r;try{r=await Ao(e,q,{...n?{baseUrl:n}:{},onProgress:o=>console.error(` ${o}`)})}catch(o){if(o instanceof xe)return $(t,o.code,o.message,`run \`canary run wait ${e}\` again to keep waiting`,2,{runId:e});if(o instanceof L){if(o.status===404)return $(t,"not_found","no such run in your workspace",void 0,3,{httpStatus:404});let i=!z1(o)&&o.status>=400&&o.status<500;return $(t,"api_error",o.message,o.fix??(o.status===401?"run `canary login`":i?void 0:`run \`canary run wait ${e}\` again`),i?3:2,{runId:e,httpStatus:o.status})}throw o}let s=Io(r.run,r.run.target?.treeHash??"",r.findings,r.run.reverify);console.log(t?JSON.stringify(s):Ro(s)),process.exitCode=s.exitCode}function Uc(e){e.command("run").argument("[runId]").description("Show a verify run: status and every check with its verdict").option("--json","print one JSON document: status, progress, every check with its verdict, and the report fields once the run has finished").action(async(n,q)=>{try{if(!n)return $(q.json===!0,"bad_id","pass the run id `canary verify` printed","canary run <runId>",3);await by(n,q.json===!0)}catch(r){$(q.json===!0,"internal_error",r instanceof Error?r.message:String(r),void 0,2)}}).command("wait <runId>").description("Wait for a run to finish, then print its findings (progress on stderr)").option("--json","print one JSON document").action(async(n,q,r)=>{let s=r.optsWithGlobals().json===!0;try{await xy(n,s)}catch(o){$(s,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}}),e.command("check <runId> <checkRunId>").description("Show one check in full: verdict, what was tested, reproduce steps, code refs, evidence \u2014 or report what you did with it").option("--json","print the server's finding body, unchanged, under an ok:true envelope with runId and checkRunId").option("--fixed","report: you fixed the behaviour this finding describes").option("--disputed <why>","report: the finding is not a real problem, and why").option("--skipped <why>","report: you did not act on it, and why").action(async(n,q,r)=>{try{let s=[r.fixed?"fixed":null,r.disputed!==void 0?"disputed":null,r.skipped!==void 0?"skipped":null].filter(Boolean);if(s.length>1)return $(r.json===!0,"bad_report","report exactly one of --fixed, --disputed, --skipped",void 0,3);if(s.length===1){let o=(s[0]==="disputed"?r.disputed:s[0]==="skipped"?r.skipped:void 0)?.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").trim();return o!==void 0&&!o?$(r.json===!0,"bad_report",`--${s[0]} needs a reason`,void 0,3):await zy(n,q,s[0],o,r.json===!0)}await ky(n,q,r.json===!0)}catch(s){$(r.json===!0,"internal_error",s instanceof Error?s.message:String(s),void 0,2)}})}g();mq();Rt();p1();bt();e1();ie();import{readFileSync as Ey,unlinkSync as Ny,writeFileSync as Py}from"node:fs";import{basename as jy,join as My}from"node:path";import{setTimeout as Ly}from"node:timers/promises";g();import{emitKeypressEvents as Sy}from"node:readline";var Cy=36,Ay=12,Gc=64*1024,pi=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Iy={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},Ry={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function $r(e){let t=Math.max(0,Math.floor(e));return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}function Ty(e,t){let n="";for(let{segment:q}of[...pi.segment(l1(e))].reverse()){if(kn(q+n)>t)break;n=q+n}return n}function Vc(e,t,n){let q=e.question,r=Math.max(1,t-5),s=(a,l="text")=>` ${zn(l1(a),l,n)}`,o=0;if(q.secret){for(let a of pi.segment(e.input??""))if(++o===24)break}let i=q.secret?"\u2022".repeat(o):Ty(e.input??"",Math.max(1,r-2));return[s("CANARY \xB7 SETUP","gold"),s(`${e.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${$r(e.seconds)}`),s(`CLI workspace ${e.workspace}`,"muted"),"",s(q.key,"gold"),...Ze(q.prompt,r).map(a=>s(a)),s(e.inputActive?`\u203A ${i||(q.secret?"(hidden)":"")}`:e.inputSubmitted?"Value captured locally.":"Input deferred","muted"),s(e.inputNotice??(q.secret?"Your value stays hidden.":""),"muted"),s(e.inputActive?"Enter submit \xB7 Esc/Ctrl+C later":e.inputSubmitted?"Waiting for verification to continue.":"Run canary setup to resume.","muted")]}function Oy(e,t,n,q){let r=Math.max(1,t-5),s=Math.max(1,n-2),o=e.outcome?Ry[e.outcome.status]:e.question?"Your input is needed":Iy[e.status],i=e.outcome?.status==="green"?"green":"gold",a=(h,d="text")=>zn(l1(h),d,q),l;if(s<=3)l=[a(o,i),a(`Elapsed ${$r(e.seconds)}`,"muted")].slice(0,s);else if(e.question&&!e.outcome)l=Vc(e,t,q);else{let h=e.seconds%1.6,d=!e.outcome&&["pending","running"].includes(e.status)&&h<1.4?Math.sin(h/1.4*Math.PI*2)*Math.sin(h/1.4*Math.PI):0,m=d2[Math.max(0,Math.min(16,Math.round(d*10)+8))];if(t>=76&&n>=23){let u={1:a("CANARY \xB7 SETUP","gold"),3:a(o,i),5:a(`Elapsed ${$r(e.seconds)}`,"muted")};l=["",...m.map((p,f)=>` ${a(p,i)} ${u[f]??""}`)]}else l=[` ${a("CANARY \xB7 SETUP","gold")}`,` ${a(o,i)}`,` ${a(`Elapsed ${$r(e.seconds)}`,"muted")}`];l.push("",` ${a(`Repository ${e.repository}`)}`,` ${a(`CLI workspace ${e.workspace}`)}`),e.detail&&!e.outcome&&l.push(...Ze(e.detail,r).map(u=>` ${a(u,"muted")}`)),e.outcome||l.push("",` ${a("Ctrl+C stops watching \xB7 canary setup resumes","muted")}`)}return(l.length>s?[...l.slice(0,Math.max(0,s-2)),...l.slice(-2)]:l).map(h=>Gq(h,Math.max(1,t-1)))}function Jc(e){if(e.json||!e.animation||!process.stdin.isTTY||!process.stdout.isTTY||!process.stderr.isTTY||process.env.CI||process.env.TERM==="dumb"||process.env.CANARY_NO_ANIMATION)return;let t=process.stderr,n=process.stdin,q=!process.env.NO_COLOR,r=c2(t),s=performance.now(),o={...e,status:"submitting",seconds:0},i=!1,a=!1,l,c=!1,h,d,m=()=>({columns:t.columns||80,rows:t.rows||24}),u=w=>{try{t.write(w)}catch{}},p=()=>u(`${S1}0m${S1}?25h`);function f(){if(i||c)return;o.seconds=(performance.now()-s)/1e3;let{columns:w,rows:P}=m();try{r.render(Oy(o,w,P,q))}catch{z()}}function k(){let{columns:w,rows:P}=m();return n.isTTY&&w>=Cy&&P>=Ay&&Vc(o,w,!1).length<=P-2}function x(){let w=o.question;if(!w)return;c=!0;try{r.render([])}catch{}let P=Math.max(1,m().columns-3);u(`
|
|
3320
3350
|
Input needed: ${l1(w.key)}
|
|
3321
3351
|
${Ze(w.prompt,P).join(`
|
|
3322
3352
|
`)}
|
|
@@ -3324,37 +3354,37 @@ ${Ze(w.prompt,P).join(`
|
|
|
3324
3354
|
Answer with: canary setup --answer '<value>'
|
|
3325
3355
|
`)}function y(){d&&!k()?d.settle(null,!0):f()}function b(){!i||d||a||(a=!0,process.off("SIGINT",I),process.off("SIGTERM",S),process.off("exit",z),p(),l!==void 0&&(u(`
|
|
3326
3356
|
Stopped watching. Run canary setup to resume verification.
|
|
3327
|
-
`),process.exit(l)))}function z(){i||(i=!0,clearInterval(h),t.off("resize",y),d?.settle(null),b())}function C(w){l=w,z(),b()}function I(){d?d.settle(null):C(130)}function S(){C(143)}async function v(w,P){return i||d||P?.aborted?null:(o.question={...w},o.input="",o.inputActive=!0,o.inputSubmitted=!1,o.inputNotice=void 0,c=!1,k()?new Promise(V=>{let J1=n.isRaw,T1=n.readableFlowing===!0,o1="",R="",M=!1,T=!1,D="",J=!1,q1=!1,Y1=!1,ye=!1,K1;function _e(O1,r1=!1){ye||(K1={answer:K1&&O1!==null?K1.answer:O1,showStatic:r1||K1?.showStatic||!1},q1||=!!D&&!T,o1=R="",o.input="",(M||T||D||q1)&&(o.inputNotice="Finishing clipboard input.",f()),pt())}function pt(){if(ye||!K1||J||M||T||D||q1)return;let{answer:O1,showStatic:r1}=K1;ye=!0,n.off("keypress",Vt),n.off("data",se),n.off("data",Gt),n.off("end",U),n.off("error",U),n.off("close",U),P?.removeEventListener("abort",ue);try{n.setRawMode(J1)}catch{}T1||n.pause(),u(`${S1}?2004l`),o1="",R="",o.input="",o.inputActive=!1,o.inputSubmitted=O1!==null,o.inputNotice=O1===null?"You can provide this value later.":"Input received locally.",d=void 0,r1&&!i?x():f(),p(),b(),V(O1)}function ue(){_e(null)}function U(){M=T=J=q1=!1,D="",_e(null)}function se(O1){J=!0;for(let r1 of typeof O1=="string"?O1:O1.toString("utf8")){let Jt=T?`${S1}201~`:`${S1}200~`;D=r1===Jt[D.length]?D+r1:r1==="\x1B"?r1:"",D===Jt&&(T=!T,D="")}}function Gt(){J=!1,pt()}function d1(O1){o1.length+O1.length>
|
|
3328
|
-
`)),R="";else if(M){let Jt=(O1||r1.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(r1.sequence??"").includes("\x1B")||(R.length+Jt.length<=
|
|
3357
|
+
`),process.exit(l)))}function z(){i||(i=!0,clearInterval(h),t.off("resize",y),d?.settle(null),b())}function C(w){l=w,z(),b()}function I(){d?d.settle(null):C(130)}function S(){C(143)}async function v(w,P){return i||d||P?.aborted?null:(o.question={...w},o.input="",o.inputActive=!0,o.inputSubmitted=!1,o.inputNotice=void 0,c=!1,k()?new Promise(V=>{let J1=n.isRaw,T1=n.readableFlowing===!0,o1="",R="",M=!1,T=!1,D="",J=!1,q1=!1,Y1=!1,ye=!1,K1;function _e(O1,r1=!1){ye||(K1={answer:K1&&O1!==null?K1.answer:O1,showStatic:r1||K1?.showStatic||!1},q1||=!!D&&!T,o1=R="",o.input="",(M||T||D||q1)&&(o.inputNotice="Finishing clipboard input.",f()),pt())}function pt(){if(ye||!K1||J||M||T||D||q1)return;let{answer:O1,showStatic:r1}=K1;ye=!0,n.off("keypress",Vt),n.off("data",se),n.off("data",Gt),n.off("end",U),n.off("error",U),n.off("close",U),P?.removeEventListener("abort",ue);try{n.setRawMode(J1)}catch{}T1||n.pause(),u(`${S1}?2004l`),o1="",R="",o.input="",o.inputActive=!1,o.inputSubmitted=O1!==null,o.inputNotice=O1===null?"You can provide this value later.":"Input received locally.",d=void 0,r1&&!i?x():f(),p(),b(),V(O1)}function ue(){_e(null)}function U(){M=T=J=q1=!1,D="",_e(null)}function se(O1){J=!0;for(let r1 of typeof O1=="string"?O1:O1.toString("utf8")){let Jt=T?`${S1}201~`:`${S1}200~`;D=r1===Jt[D.length]?D+r1:r1==="\x1B"?r1:"",D===Jt&&(T=!T,D="")}}function Gt(){J=!1,pt()}function d1(O1){o1.length+O1.length>Gc?(Y1=!0,o.inputNotice="Too long. Ctrl+U clears input."):(o1+=O1,Y1||(o.inputNotice=void 0))}function Vt(O1,r1){if(!(ye||!r1))try{if(!J&&r1.name==="escape"&&(D=""),!D&&r1.sequence?.startsWith("\x1B")&&(q1=!1),K1){r1.name==="paste-start"?M=!0:r1.name==="paste-end"&&(M=!1),pt();return}if(r1.name==="paste-start"){M=!0,R="";return}if(r1.name==="escape"||r1.ctrl&&["c","d"].includes(r1.name??"")){ue();return}if(r1.name==="paste-end")M=!1,d1(R.replace(/\r\n?/g,`
|
|
3358
|
+
`)),R="";else if(M){let Jt=(O1||r1.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(r1.sequence??"").includes("\x1B")||(R.length+Jt.length<=Gc?R+=Jt:(Y1=!0,o.inputNotice="Too long. Ctrl+U clears input."));return}else if(r1.ctrl&&r1.name==="u")o1="",Y1=!1,o.inputNotice=void 0;else if(r1.name==="backspace")o1=[...pi.segment(o1)].slice(0,-1).map(f6=>f6.segment).join("");else if(r1.name==="return"||r1.name==="enter"){if(!o1.trim())o.inputNotice="Enter a value, or Esc to answer later.";else if(!Y1){_e(o1);return}}else!r1.ctrl&&!r1.meta&&O1&&d1(O1.replace(/[\x00-\x1f\x7f-\x9f]/g,""));o.input=o1,f()}catch{ue()}}d={settle:_e};try{if(n.prependListener("data",se),Sy(n),n.on("keypress",Vt),n.on("data",Gt),n.once("end",U),n.once("error",U),n.once("close",U),P?.addEventListener("abort",ue,{once:!0}),P?.aborted){ue();return}n.setRawMode(!0),n.resume(),u(`${S1}?2004h${S1}?25l`),f()}catch{ue()}}):(o.inputActive=!1,x(),null))}return t.on("resize",y),process.on("SIGINT",I),process.on("SIGTERM",S),process.once("exit",z),h=setInterval(f,80),h.unref(),u(`${S1}?25l`),f(),{update(w,P){i||(o.status=w,o.detail=P,d||(o.question=void 0,o.input=void 0,c=!1),u(`${S1}?25l`),f())},warn(w){if(!i)try{r.render([])}catch{z()}u(`
|
|
3329
3359
|
Warning: ${w.split(/\r?\n/).map(l1).join(`
|
|
3330
3360
|
`)}
|
|
3331
3361
|
|
|
3332
3362
|
`),f()},ask:v,finish(w){if(i)return;d?.settle(null),o.question=void 0,o.outcome=w,c=!1,f(),z();let P=[w.message,...w.updatedFiles?.length?[`Updated locally: ${w.updatedFiles.join(", ")}`]:[],...w.warning?[`Warning: ${w.warning}`]:[],...w.next?[`Next: ${w.next}`]:[]].filter(V=>!!V);P.length&&u(`
|
|
3333
3363
|
${P.flatMap(V=>V.split(/\r?\n/).map(l1)).join(`
|
|
3334
3364
|
`)}
|
|
3335
|
-
`)},stop:z}}Zs();o2();M1();Le();
|
|
3336
|
-
`);function Wr(e){try{
|
|
3365
|
+
`)},stop:z}}Zs();o2();M1();Le();Hq();Wq();var $2=3e3,Dr=2,Fy=9e4,Yc=new Set(["pending","running","needs_input","green","red","error","interrupted"]);function D1(e,t){for(let n of[...e.secrets].sort((q,r)=>r.length-q.length))n&&(t=t.split(n).join("[redacted]"));return t}var fi=e=>My(e,".canary","verify-job.json");function Xn(e){try{let t=JSON.parse(Ey(fi(e),"utf8"));if(!t||typeof t.jobId!="string"||!t.jobId)throw new Error("invalid job ID");if(t.sourceUploadId!==void 0&&(typeof t.sourceUploadId!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t.sourceUploadId)))throw new Error("invalid source upload ID");if(t.scope&&(!t.source||!$q(t.source)||typeof t.recipeHash!="string"||typeof t.scope.apiUrl!="string"||![t.scope.userId,t.scope.workspaceId,t.scope.repositoryId].every(q=>typeof q=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(q))))throw new Error("invalid scope");let n=t.workspace&&typeof t.workspace.id=="string"&&typeof t.workspace.name=="string"?{id:t.workspace.id,name:t.workspace.name}:void 0;return{jobId:t.jobId,...typeof t.recipeHash=="string"?{recipeHash:t.recipeHash}:{},...n?{workspace:n}:{},...t.scope?{scope:t.scope}:{},...t.source?{source:t.source}:{},...t.sourceUploadId?{sourceUploadId:t.sourceUploadId}:{}}}catch(t){if(t.code==="ENOENT")return null;throw new Z1("invalid_setup_receipt","The saved setup job in .canary/verify-job.json is unreadable, so no new job was started.","Fix or remove .canary/verify-job.json, then run canary setup again.")}}function $y(e){return Xn(e)?.jobId??null}var Kc=(e,t)=>Py(fi(e),JSON.stringify(t)+`
|
|
3366
|
+
`);function Wr(e){try{Ny(fi(e))}catch{}}var D2=(e,t)=>Ly(e,void 0,{signal:t});function Dy(e){let t=e?.setup?.services;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"?n.name:void 0).filter(n=>typeof n=="string"):[]}function Wy(e,t){let n,q;try{n=Ye(e),rn(e),q=q2(e).name}catch(h){if(h instanceof Z1||h instanceof n1){t?console.log(JSON.stringify({ok:!1,error:h.code,message:h.message,..."fix"in h&&h.fix?{fix:h.fix}:{}})):console.error(`\u2717 ${h.message}${"fix"in h&&h.fix?`
|
|
3337
3367
|
Fix: ${h.fix}`:""}`),process.exitCode=1;return}throw h}let r=q??null,s=n.setupSh.trim().split(`
|
|
3338
|
-
`).length,o=
|
|
3368
|
+
`).length,o=Dy(n.runJson),i=[...new Set([...n.envManifest.map(h=>h.name),...Object.keys(n.envValues)])],a=n.envManifest.filter(h=>h.neededAt==="boot").map(h=>h.name),{missing:l}=Xs(n.envManifest,n.envValues),c=l.length===0;t?console.log(JSON.stringify({ok:c,repo:r,recipe:{setupShLines:s,services:o,envKeys:i,bootRequired:a,missing:l}})):(console.log(`Repo ${r??"(local repository)"}`),console.log(`Recipe .canary/ \xB7 setup.sh (${s} lines) \xB7 run.json (${o.length} service${o.length===1?"":"s"}${o.length?": "+o.join(", "):""})`),console.log(`Env ${i.length} key${i.length===1?"":"s"} \xB7 ${a.length} boot-required \xB7 ${l.length?`MISSING: ${l.join(", ")}`:"all present"}`),c?console.log("\u2713 Recipe looks valid \u2014 ready to verify."):console.error(`\u2717 Recipe incomplete \u2014 ${l.join(", ")} (boot-required) ${l.length===1?"has":"have"} no value.`)),c||(process.exitCode=1)}async function Xc(e,t,n,q,r={}){if(t.status==="green"){let s=Xn(e),o=s?.workspace,i=r.recipeChanged??!1;if(s?.recipeHash)try{i||=xt(Ye(e))!==s.recipeHash}catch{i=!0}let a=!1;if(s?.source){let h=(m,u)=>m.sha256===u.sha256&&m.treeHash===u.treeHash&&m.baseTreeHash===u.baseTreeHash&&m.baseSha===u.baseSha&&m.provenance.baselineMode===u.provenance.baselineMode&&(m.provenance.baseRef??null)===(u.provenance.baseRef??null);if(t.approved?.source&&!h(t.approved.source,s.source))throw new Error("The approved source does not match the source this job was submitted with. Run canary setup again to verify the current files.");let d;try{d=await It(e,{baseRef:s.source.provenance.baseRef??void 0}),a=d.manifest.treeHash!==s.source.treeHash||d.manifest.baseTreeHash!==s.source.baseTreeHash||d.manifest.provenance.baselineMode!==s.source.provenance.baselineMode||(d.manifest.provenance.baseRef??null)!==(s.source.provenance.baseRef??null)}catch{a=!0}finally{await d?.dispose()}}if(s?.recipeHash)try{i||=xt(Ye(e))!==s.recipeHash}catch{i=!0}let l=r.writeBack!==!1&&!i&&!a;if(i||a){let h="This result is for the files as they were when submitted. They changed since, so the approved recipe was not written over your files. Run canary setup again to verify the current files.";q.warnings.push(h),!n&&!q.display&&console.error(`! ${h}`)}Wr(e);let c=[];if(t.approved?.healed&&l)try{c=Z3(e,t.approved)}catch(h){let d=D1(q,`Could not update .canary/ with the approved changes: ${h instanceof Error?h.message:String(h)}`);q.warnings.push(d),q.display||console.error(`! ${d}`)}return n?console.log(JSON.stringify({ok:!0,status:"green",jobId:t.jobId,...o?{workspace:o}:{},...i?{recipeChanged:!0}:{},...a?{sourceChanged:!0}:{},...s?.source?{source:s.source,repositoryId:s.scope?.repositoryId}:{},...t.approved?{approved:{healed:t.approved.healed,...t.approved.recipeId?{recipeId:t.approved.recipeId}:{},...t.approved.recipeVersionId?{recipeVersionId:t.approved.recipeVersionId}:{},...t.approved.version!==void 0?{version:t.approved.version}:{},...c.length?{updatedFiles:c}:{}}}:{}})):q.display?q.display.finish({status:"green",message:`Your recipe boots from zero in a clean sandbox.${o?` Workspace: ${o.name}.`:""}`,updatedFiles:c,warning:q.warnings.join(`
|
|
3339
3369
|
`)||void 0,next:`Open Canary: ${Ee().replace(/\/+$/,"")}/repositories`}):(console.log("\u2713 Verified \u2014 the recipe boots from zero in a clean sandbox. This repo is set up on Canary."),o&&console.log(` Workspace: ${o.name}`),t.approved?.healed&&(console.log(" The cloud verifier adjusted the setup while fixing the boot."),c.length?console.log(` Updated locally to match: ${c.join(", ")}`):l||console.log(" Its approved version was not written over your newer files."))),!0}if(t.status==="interrupted")return!1;if(t.status==="red"||t.status==="error"){Wr(e);let s={phase:t.failure?.phase?D1(q,t.failure.phase):null,failingCommand:t.failure?.failingCommand?D1(q,t.failure.failingCommand):null,log:t.failure?.log?D1(q,t.failure.log):null};return n?console.log(JSON.stringify({ok:!1,status:t.status,jobId:t.jobId,failure:s})):q.display?q.display.finish({status:t.status,message:`Verification ${t.status==="error"?"errored":"failed"}${s.phase?` (${s.phase})`:""}${s.failingCommand?` at: ${s.failingCommand}`:""}${s.log?`
|
|
3340
3370
|
|
|
3341
3371
|
${s.log.slice(-2e3)}`:""}`,warning:q.warnings.join(`
|
|
3342
3372
|
`)||void 0,next:"Fix the recipe in .canary/ and run canary setup again."}):(console.error(`\u2717 Verify ${t.status==="error"?"errored":"failed"}${s.phase?` (${s.phase})`:""}${s.failingCommand?` at: ${s.failingCommand}`:""}`),s.log&&console.error(`
|
|
3343
3373
|
${s.log.slice(-2e3)}`),console.error("\nFix the recipe in .canary/ and run `canary setup` again.")),process.exitCode=1,!0}if(t.status==="needs_input"&&t.needsInput){let s={...t.needsInput,key:D1(q,t.needsInput.key),prompt:D1(q,t.needsInput.prompt)};return n?console.log(JSON.stringify({ok:!1,status:"needs_input",jobId:t.jobId,needsInput:s})):(console.log(`? The cloud verifier needs input${s.secret?" (a secret \u2014 pass the real value, don't echo it anywhere else)":""}:`),console.log(` ${s.key}: ${s.prompt}`),console.log(`
|
|
3344
|
-
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function
|
|
3345
|
-
`+(c?" .canary/ changed since it was submitted, so its approved version was NOT written over your files. Run `canary setup` again to verify the current files.":" If you changed .canary/ since then, run `canary setup` again to verify the current files.")),await
|
|
3374
|
+
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function Qc(e,t){return e.status==="needs_input"&&e.needsInput?.questionId===t.questionId}async function Hy(e,t,n){let q=new AbortController,r=new AbortController,s=e.display.ask({...t,key:D1(e,t.key),prompt:D1(e,t.prompt)},q.signal).then(i=>({kind:"answer",value:i})),o=(async()=>{for(;;){await D2($2,r.signal);let i=await n(r.signal);if(!Qc(i,t))return{kind:"state",view:i}}})();try{return await Promise.race([s,o])}finally{r.abort(),q.abort(),await Promise.allSettled([s,o])}}async function By(e,t,n,q,r,s){let o="",i=null;async function a(c){for(;;)try{let h=await W(`/api/v1/cli/verify/${t}`,{token:n,baseUrl:r.context?.apiUrl,signal:c});if(!h||!Yc.has(h.status))throw new Error("Verification returned an unrecognized state. Run canary setup again to retry.");return i=null,h}catch(h){if(c?.aborted)throw h;if(h instanceof L&&h.status===0&&(i===null&&(i=Date.now(),r.display?r.display.update("retrying","Cloud service unreachable. Retrying the same job."):q||console.log(" \u2026 cloud service unreachable \u2014 retrying")),Date.now()-i<Fy)){await D2($2,c);continue}throw h}}let l;for(;;){let c=l??await a();if(l=void 0,c.status==="interrupted")return"interrupted";if(c.status==="needs_input"&&s&&c.needsInput?.questionId===s.questionId&&Date.now()<s.until){await D2($2);continue}if(c.status==="needs_input"&&c.needsInput&&r.display){let h=c.needsInput,d=await Hy({...r,display:r.display},h,a);if(d.kind==="state"){l=d.view;continue}let m=d.value;if(m===null)return r.display.finish({status:"paused",message:"The verifier is waiting for your answer.",next:"Run canary setup to resume, or canary setup --answer '<value>' to answer directly."}),process.exitCode=3,"terminal";let u=await a();if(!Qc(u,h)){l=u;continue}r.display.update("answering","Sending your answer to the verifier.");try{await t6(e,t,n,h,m,q,r)}catch(p){if(p instanceof L&&p.status===409)continue;throw p}s={questionId:h.questionId,until:Date.now()+3e4},r.display.update("answering","Answer received. Waiting for verification to continue."),await D2($2);continue}if((c.status==="pending"||c.status==="running")&&(r.display?r.display.update(c.status):c.status!==o&&!q&&console.log(` \u2026 ${c.status==="pending"?"queued":"verifying in a clean cloud sandbox (boot + heal \u2014 this can take a while)"}`)),o=c.status,await Xc(e,c,q,r))return"terminal";await D2($2)}}async function Hr(e,t,n,q,r,s){Zt();let o=t;for(let i=0;;){if(await By(e,o,n,q,r,s)==="terminal")return;if(Wr(e),r.freshUpload=!0,i>=Dr){q?console.log(JSON.stringify({ok:!1,status:"interrupted",jobId:o})):r.display?r.display.finish({status:"error",message:"Verification kept getting interrupted by the cloud service.",next:"Run canary setup again in a minute to restart from your local .canary/ files."}):console.error("\u2717 Verification kept getting interrupted (the cloud service may be redeploying). Run `canary setup` again in a minute \u2014 it restarts from your local .canary/ files."),process.exitCode=1;return}i+=1,q?console.error(JSON.stringify({event:"resubmitted",attempt:i,of:Dr})):r.display?r.display.update("retrying",`The cloud worker stopped. Resubmitting (${i} of ${Dr}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${i} of ${Dr})`);let l=await e6(e,n,q,r);if(l===null)return;o=l,s=void 0}}async function Zc(e,t,n,q){let r=q.context??=await je(e,t),s=n.scope;if(s.apiUrl.replace(/\/+$/,"")!==r.apiUrl.replace(/\/+$/,"")||s.userId!==r.userId||s.workspaceId!==r.workspaceId)throw new n1("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json was started by a different account, workspace, or Canary server. Switch back to it to resume that job, or remove the file to start over.");if((await Pe({...r,token:t})).repositoryId!==s.repositoryId)throw new n1("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json belongs to a different repository. Remove the file to start over.");q.baseRef??=n.source?.provenance.baseRef??void 0,mn(n.source,r,s.repositoryId,{requestKey:`setup:${n.recipeHash}`,uploadId:n.sourceUploadId})}async function e6(e,t,n,q){let r=Ye(e);rn(e);let{missing:s}=Xs(r.envManifest,r.envValues);if(s.length)return n?console.log(JSON.stringify({ok:!1,error:"missing_boot_env",missing:s})):q.display?q.display.finish({status:"error",message:`Boot-required environment values are missing: ${s.join(", ")}`,next:"Fill .canary/env.json and run canary setup again."}):console.error(`\u2717 Boot-required env without values: ${s.join(", ")} \u2014 fill .canary/env.json first.`),process.exitCode=1,null;let o=q.context??=await je(e,t),i=await Pe({...o,token:t}),a=await It(e,{baseRef:q.baseRef});try{q.display?.update("submitting","Uploading your local source and the .canary/ recipe.");let l=xt(r),c=await h2(a,o,i.repositoryId,t,{requestKey:`setup:${l}`,fresh:q.freshUpload});q.freshUpload=!1;let h=await W("/api/v1/cli/verify",{method:"POST",token:t,baseUrl:o.apiUrl,body:{workspaceId:o.workspaceId,repositoryId:i.repositoryId,source:c,setupSh:r.setupSh,runJson:JSON.stringify(r.runJson??null),env:{manifest:r.envManifest,values:r.envValues}}});if(!h?.jobId||h.repositoryId!==i.repositoryId||h.workspace&&h.workspace.id!==o.workspaceId||h.source&&h.source.sha256!==a.manifest.sha256)throw new Error("Canary's answer does not match the repository and source that were uploaded. Run canary setup again.");return Kc(e,{jobId:h.jobId,recipeHash:l,workspace:h.workspace??i.workspace,source:a.manifest,sourceUploadId:c.uploadId,scope:{apiUrl:o.apiUrl,userId:o.userId,workspaceId:o.workspaceId,repositoryId:i.repositoryId}}),mn(a.manifest,o,i.repositoryId,{requestKey:`setup:${l}`,uploadId:c.uploadId}),h.jobId}finally{await a.dispose()}}async function _y(e,t,n){let q=Q();if(!q){t?console.log(JSON.stringify({ok:!1,error:"not_logged_in",fix:"canary login"})):n.display?n.display.finish({status:"error",message:"You're not signed in.",next:"Run canary login first."}):console.error("\u2717 Not logged in \u2014 run `canary login` first."),process.exitCode=1;return}nn();let r=Xn(e);r?.scope&&await Zc(e,q,r,n);let s=r?.jobId??null;if(s){n.display?.update("submitting","Checking your saved verification job.");let i=null,a=!1,l=Date.now()+3e4;for(;;)try{if(i=await W(`/api/v1/cli/verify/${s}`,{token:q,baseUrl:n.context?.apiUrl}),!i||!Yc.has(i.status))throw new Error("Saved verification returned an unrecognized state. Run canary setup again to retry.");break}catch(c){if(c instanceof L&&c.status===0){if(Date.now()<l){n.display?.update("retrying","Cloud service unreachable. Checking your saved job before continuing."),await D2($2);continue}a=!0}else if(!(c instanceof L&&c.status===404))throw c;break}if(a){t?console.log(JSON.stringify({ok:!1,error:"unreachable",jobId:s})):n.display?n.display.finish({status:"error",message:"Could not reach the cloud service to check your saved job.",next:"Run canary setup again shortly. Your job is saved."}):console.error("\u2717 Could not reach the cloud service to check your saved verify job \u2014 try again shortly."),process.exitCode=1;return}if(i){if(i.status==="pending"||i.status==="running"||i.status==="needs_input"){n.display?n.display.update(i.status==="needs_input"?"answering":i.status,"Resuming your saved verification job."):t||console.log(`Resuming verify job ${s} \u2026`),await Hr(e,s,q,t,n);return}if(i.status==="green"||i.status==="red"||i.status==="error"){let c=!1;if(r?.recipeHash)try{c=xt(Ye(e))!==r.recipeHash}catch{c=!0}t?console.error(JSON.stringify({event:"previous_job_result",jobId:s,...c?{recipeChanged:!0}:{}})):n.display?n.warnings.push(c?"This is your earlier verification result, and .canary/ changed since it was submitted: its approved version was not written over your files. Run canary setup again to verify the current files.":"This is your earlier verification result. If you changed .canary/ since then, run canary setup again to verify the current files."):console.log(`Your earlier verify job ${s} finished after the previous run stopped \u2014 applying its result now.
|
|
3375
|
+
`+(c?" .canary/ changed since it was submitted, so its approved version was NOT written over your files. Run `canary setup` again to verify the current files.":" If you changed .canary/ since then, run `canary setup` again to verify the current files.")),await Xc(e,i,t,n,{writeBack:!c,recipeChanged:c});return}}Wr(e),n.freshUpload=!0}let o=await e6(e,q,t,n);o!==null&&(n.display?n.display.update("pending","Recipe sent. Waiting for the cloud verifier."):t||console.log(`Shipped the recipe \u2014 verify job ${o}`),await Hr(e,o,q,t,n))}async function t6(e,t,n,q,r,s,o){if(q.secret&&r&&o.secrets.add(r),await W(`/api/v1/cli/verify/${t}/answer`,{method:"POST",token:n,baseUrl:o.context?.apiUrl,body:{questionId:q.questionId,value:r}}),q.secret){let i=Xn(e),a=!1;try{a=!!i?.recipeHash&&xt(Ye(e))===i.recipeHash}catch{}try{if(i?.recipeHash&&!a)throw new Error("Local recipe changed since submission; the answered value was not written over it.");Qs(e,[{name:q.key,value:r,class:"external_boot",why:q.prompt.slice(0,200)||"asked during cloud verification"}]),a&&i&&Kc(e,{...i,recipeHash:xt(Ye(e))}),!s&&!o.display&&console.log(`Saved ${D1(o,q.key)} to .canary/env.json for future runs.`)}catch(l){let c=D1(o,`Could not save ${q.key} to .canary/env.json: ${l instanceof Error?l.message:String(l)}`);o.display?o.display.warn(c):console.error(`! ${c}`)}}}async function Uy(e,t,n,q){let r=Q(),s=$y(e);if(!r||!s){n?console.log(JSON.stringify({ok:!1,error:s?"not_logged_in":"no_active_job",fix:s?"canary login":"canary setup"})):q.display?q.display.finish({status:"error",message:s?"You're not signed in.":"No active verification job.",next:s?"Run canary login first.":"Run canary setup first."}):console.error(s?"\u2717 Not logged in \u2014 run `canary login`.":"\u2717 No active verify job \u2014 run `canary setup` first."),process.exitCode=1;return}let o=Xn(e);o?.scope&&await Zc(e,r,o,q);let i=await W(`/api/v1/cli/verify/${s}`,{token:r,baseUrl:q.context?.apiUrl});if(i.status!=="needs_input"||!i.needsInput){q.display?q.display.update("submitting","Nothing is waiting for input. Checking the saved job."):n||console.log("Nothing is waiting for input \u2014 following the job instead."),await Hr(e,s,r,n,q);return}let a=i.needsInput;q.display?.update("answering","Sending your answer to the verifier."),await t6(e,s,r,a,t,n,q),q.display?q.display.update("answering","Answer received. Waiting for verification to continue."):n||console.log(`Answered ${D1(q,a.key)} \u2014 resuming \u2026`),await Hr(e,s,r,n,q,{questionId:a.questionId,until:Date.now()+3e4})}function n6(e){e.command("setup").description("Set up this repo on Canary: ship the .canary/ recipe for a cloud verify (boot + heal)").option("--check","validate the .canary/ recipe locally (no cloud)").option("--answer <value>","answer the question the cloud verifier is waiting on").option("--json","output machine-readable JSON").option("--no-animation","use plain progress output and answer questions with --answer").option("--dir <path>","repo directory (default: current directory)").option("--base <ref>","locally resolvable baseline for the submitted source snapshot").action(async t=>{let n=t.dir??process.cwd();Q1({cwd:n});let q=t.json===!0;if(t.check){Wy(n,q);return}let r={secrets:new Set(t.answer?[t.answer]:[]),warnings:[],baseRef:t.base};try{let s=K().team;r.display=Jc({json:q,animation:t.animation!==!1,repository:jy(n),workspace:s?.name||(s?.id?"Saved workspace":"Select a workspace")}),t.answer!==void 0?await Uy(n,t.answer,q,r):await _y(n,q,r)}catch(s){if(s instanceof Z1||s instanceof W1||s instanceof n1){let o=D1(r,s.message),i="fix"in s&&s.fix?D1(r,s.fix):void 0;q?console.log(JSON.stringify({ok:!1,error:s.code,message:o,...i?{fix:i}:{}})):r.display?r.display.finish({status:"error",message:o,next:i}):console.error(`\u2717 ${o}${i?`
|
|
3346
3376
|
Fix: ${i}`:""}`)}else if(s instanceof L){let o=D1(r,s.message),i="fix"in s&&s.fix?D1(r,s.fix):void 0;q?console.log(JSON.stringify({ok:!1,error:"api_error",status:s.status,message:o,...i?{fix:i}:{}})):r.display?r.display.finish({status:"error",message:o,next:i||"Run canary setup in this repository to resume."}):console.error(`\u2717 ${o}${i?`
|
|
3347
|
-
Fix: ${i}`:""}`)}else{let o=D1(r,s instanceof Error?s.message:String(s));q?console.log(JSON.stringify({ok:!1,error:"setup_error",message:o})):r.display?r.display.finish({status:"error",message:o,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${o}`)}process.exitCode=1}finally{r.display?.stop()}process.exitCode||await
|
|
3348
|
-
`,{flag:"w",mode:384})}catch{}}function
|
|
3377
|
+
Fix: ${i}`:""}`)}else{let o=D1(r,s instanceof Error?s.message:String(s));q?console.log(JSON.stringify({ok:!1,error:"setup_error",message:o})):r.display?r.display.finish({status:"error",message:o,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${o}`)}process.exitCode=1}finally{r.display?.stop()}process.exitCode||await bn({json:q})})}Qe();g();e1();ie();import{lstatSync as Gy,mkdirSync as Vy,readFileSync as q6,writeFileSync as r6}from"node:fs";import{join as vi}from"node:path";var Jy=5e3,Yy=/^[a-z0-9][a-z0-9-]{0,39}$/,Ky=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,Xy="npm i -g @runcanary/cli@latest --prefer-online";function o6(e){let t=vi(G(),"skills");return{dir:t,body:vi(t,`${e}.md`),meta:vi(t,`${e}.json`)}}function Qy(e){let t=o6(e);try{let n=JSON.parse(q6(t.meta,"utf8"));return{body:q6(t.body,"utf8"),meta:n}}catch{return null}}function Qn(e){try{return Gy(e).isSymbolicLink()}catch{return!1}}function Zy(e,t){let n=o6(e);try{if(Qn(G())||Qn(n.dir)||Qn(n.body)||Qn(n.meta)||(Vy(n.dir,{recursive:!0,mode:448}),Qn(n.dir)))return;r6(n.body,t.body,{flag:"w",mode:384}),r6(n.meta,JSON.stringify(t.meta,null,2)+`
|
|
3378
|
+
`,{flag:"w",mode:384})}catch{}}function s6(e){return e instanceof Error?e.message:String(e)}async function ew(e,t){let n;try{n=await fetch(e,{headers:{...Je(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${t}`},signal:AbortSignal.timeout(Jy)})}catch(q){return{kind:"failed",reason:s6(q)}}if(n.status===404)return{kind:"missing"};if(!n.ok){let q=(await n.text().catch(()=>"")).trim().slice(0,200);return{kind:"failed",reason:`HTTP ${n.status}${q?`: ${q}`:""}`}}try{return{kind:"ok",body:await n.text(),contentVersion:n.headers.get("x-canary-skills-version")??void 0}}catch(q){return{kind:"failed",reason:`response body interrupted: ${s6(q)}`}}}async function gi(e){let t=await ew(e.url,e.cliVersion);switch(t.kind){case"ok":{let n={url:e.url,fetchedAt:new Date().toISOString(),cliVersion:e.cliVersion,contentVersion:t.contentVersion};return Zy(e.key,{body:t.body,meta:n}),{ok:!0,body:t.body,url:e.url,contentVersion:t.contentVersion,offline:!1}}case"missing":return{ok:!1,error:e.notFound};case"failed":{let n=Qy(e.key);if(n&&n.meta.url===e.url)return{ok:!0,body:n.body,url:e.url,contentVersion:n.meta.contentVersion,offline:!0,reason:t.reason,fetchedAt:n.meta.fetchedAt,savedByCli:n.meta.cliVersion};let q=n?`the saved copy is from ${n.meta.url}, not this server`:"there is no saved copy";return{ok:!1,error:`live fetch of ${e.url} failed (${t.reason}) and ${q} \u2014 retry when the server is reachable`}}}}function tw(e,t){let n=s=>s.replace(/^v/,"").split("-")[0].split(".").map(o=>Number.parseInt(o,10)||0),q=n(e),r=n(t);for(let s=0;s<3;s++){let o=(q[s]??0)-(r[s]??0);if(o!==0)return o<0?-1:1}return 0}function nw(e){let t=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e);if(t)return/^minCli:\s*["']?(\d+\.\d+\.\d+)["']?\s*$/m.exec(t[1])?.[1]}function i6(e){return e.offline?`OFFLINE COPY \u2014 live fetch of ${e.url} failed (${e.reason}). Showing the copy fetched ${e.fetchedAt} by CLI ${e.savedByCli}; it may be outdated.`:`Source: ${e.url}${e.contentVersion?` (content version ${e.contentVersion})`:""}`}function W2(e,t,n={}){if(!e.ok)return t?{stream:"stdout",text:JSON.stringify({ok:!1,error:e.error,...n})+`
|
|
3349
3379
|
`,exit:1}:{stream:"stderr",text:`\u2717 ${e.error}
|
|
3350
3380
|
`,exit:1};if(t){let q={ok:!0,source:e.url,contentVersion:e.contentVersion??null,offline:e.offline,...e.offline?{reason:e.reason,fetchedAt:e.fetchedAt}:{},...n,body:e.body};return{stream:"stdout",text:JSON.stringify(q)+`
|
|
3351
|
-
`,exit:0}}return{stream:"stdout",text:`${
|
|
3381
|
+
`,exit:0}}return{stream:"stdout",text:`${i6(e)}
|
|
3352
3382
|
|
|
3353
3383
|
${e.body}${e.body.endsWith(`
|
|
3354
3384
|
`)?"":`
|
|
3355
|
-
`}`,exit:0}}function
|
|
3356
|
-
`,exit:0}}function Br(){return a1().replace(/\/+$/,"")}function
|
|
3357
|
-
Ask Canary anything, in your own words: canary "find issues in billing" (or on stdin: canary -)`);var
|
|
3385
|
+
`}`,exit:0}}function Zn(e){(e.stream==="stdout"?process.stdout:process.stderr).write(e.text),process.exit(e.exit)}function qw(e,t,n={}){if(!e.ok||t){let q=W2(e,t,n);return q.stream==="stdout"?{stdout:q.text,stderr:"",exit:q.exit}:{stdout:"",stderr:q.text,exit:q.exit}}return{stdout:e.body,stderr:`${i6(e)}
|
|
3386
|
+
`,exit:0}}function Br(){return a1().replace(/\/+$/,"")}function a6(e){e.command("skills").description("List the operations a coding agent can perform with Canary (hosted index)").option("--json","output machine-readable JSON").action(async t=>{let n=await gi({key:"index",url:`${Br()}/llms.txt`,cliVersion:e.version()??"0.0.0",notFound:`this Canary server (${Br()}) does not publish skills yet`});Zn(W2(n,!!t.json))}),e.command("skill <name>").description("Print the hosted instructions for one Canary operation").option("--json","output machine-readable JSON").option("--asset <file>","print a file published beside the operation (a template, a schema) instead of its instructions").action(async(t,n)=>{let q=!!n.json;Yy.test(t)||Zn(W2({ok:!1,error:`invalid operation name "${t.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},q));let r=e.version()??"0.0.0";if(n.asset!==void 0){Ky.test(n.asset)||Zn(W2({ok:!1,error:`invalid asset name "${n.asset.slice(0,80)}" \u2014 assets are lowercase file names ending in .html, .json, .md or .txt`},q));let o=await gi({key:`${t}--${n.asset}`,url:`${Br()}/skills/${t}/${n.asset}`,cliVersion:r,notFound:`no such asset "${n.asset}" for "${t}" \u2014 run \`canary skill ${t}\` to see which files it publishes`}),i=qw(o,q,{name:t,asset:n.asset});i.stderr&&process.stderr.write(i.stderr);let a=()=>process.exit(i.exit);i.stdout?process.stdout.write(i.stdout,a):a()}let s=await gi({key:t,url:`${Br()}/skills/${t}.md`,cliVersion:r,notFound:`no such operation "${t}" \u2014 run \`canary skills\` to list the operations`});if(s.ok){let o=nw(s.body);if(o&&r!=="0.0.0-dev"&&tw(r,o)<0){let i=`"${t}" needs Canary CLI ${o} or newer (you have ${r}). Update: ${Xy}`,a=W2({ok:!1,error:i},q,{needsCli:o,cliVersion:r});Zn({...a,exit:2})}}Zn(W2(s,q,{name:t}))})}g();p1();e1();Rt();var rw=3e3;function sw(e){let t=e.periodEnd?` \xB7 resets ${new Date(e.periodEnd).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}`:"";return e.limit===null?`Runs this month: ${e.used} \xB7 no limit`:`Runs this month: ${e.used} of ${e.limit}${t}`}function l6(e){e.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async t=>{let n=t.json===!0,q=Q();if(!q){n?console.log(JSON.stringify({ok:!1,error:"not_logged_in"})):console.error("Not logged in. Run `canary login`."),process.exitCode=1;return}try{let r=K().team,s=r?.id&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r.id)?r:void 0,o=await W(`/api/v1/cli/auth/whoami${s?`?workspaceId=${encodeURIComponent(s.id)}`:""}`,{token:q}),i=s?{id:s.id,name:s.name??o.team.name}:void 0,a=Po(),l=a&&i?await _q({token:q,apiUrl:a1().replace(/\/+$/,""),userId:o.user.id},a,i.id,AbortSignal.timeout(rw)):void 0,c=Eo();if(n)console.log(JSON.stringify({ok:!0,user:o.user,team:o.team,workspace:i,...o.usage?{usage:o.usage}:{},...a?{repository:{name:a,...l?.state?{state:l.state}:{}}}:{},...c.length?{pushCheck:{pending:c}}:{}}));else{console.log(`${o.user.email} (${i?.name??"No workspace selected"})`),o.usage&&console.log(sw(o.usage)),a&&(console.log(Vq(a)),console.log(Tt));for(let h of c)console.log(`Push check on ${h.label}: ${h.why} Run \`${h.command}\` in a terminal. ${h.after}`)}}catch(r){let s=r instanceof L&&r.status===401,o=s?"invalid_token":r instanceof Error?r.message:String(r);n?console.log(JSON.stringify({ok:!1,error:o})):console.error(s?"Your CLI session is no longer valid. Run `canary login`.":`Error: ${o}`),process.exitCode=1}})}g();p1();e1();M1();async function d6(){let e=Q();if(!e)throw new L(401,"not logged in");let{workspaces:t}=await W("/api/v1/cli/workspaces",{token:e});return t}function H2(e,t,n,q={}){e?console.log(JSON.stringify({ok:!1,error:t,message:n,...q})):console.error(n),process.exitCode=1}function h6(e,t){if(t instanceof L&&t.status===401){H2(e,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}H2(e,"workspace_error",t instanceof Error?t.message:String(t))}async function ow(e){let t=await d6(),n=K().team?.id;if(e){console.log(JSON.stringify({workspaces:t,active:n??null}));return}if(t.length===0){console.error("You're not a member of any workspace yet. Set one up at www.runcanary.ai first.");return}let q=String(t.length).length;t.forEach((r,s)=>{let o=r.id===n?"*":" ",i=String(s+1).padStart(q," ");console.log(`${o} ${i} ${r.name}`)})}function c6(e,t){if(!P1(n=>({...n,team:{id:e.id,name:e.name}}))){H2(t,"config_unreadable","The CLI's config file exists but cannot be read, so the workspace was not saved. Repair or remove it, or run: canary login",{fix:"canary login"});return}xq(),console.log(t?JSON.stringify({ok:!0,workspace:{id:e.id,name:e.name}}):`Switched to ${e.name}.`)}async function iw(e,t){let n=await d6(),q=e.trim();if(/^\d+$/.test(q)){let s=Number(q);if(s<1||s>n.length){H2(t,"workspace_not_found",`No workspace #${s} \u2014 you have ${n.length}. Run: canary workspace list`,{available:n.map(o=>({id:o.id,name:o.name})),fix:"canary workspace list"});return}c6(n[s-1],t);return}let r=n.filter(s=>s.id===q||s.name.toLowerCase()===q.toLowerCase());if(r.length===0){H2(t,"workspace_not_found",`No workspace matching "${e}".`,{available:n.map(s=>({id:s.id,name:s.name})),fix:"canary workspace list"});return}if(r.length>1){H2(t,"workspace_ambiguous",`"${e}" matches multiple workspaces \u2014 use the id.`,{matches:r.map(s=>({id:s.id,name:s.name})),fix:`canary workspace use ${r[0].id}`});return}c6(r[0],t)}function aw(e){let t=K().team;if(!t){e?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(e?JSON.stringify({workspace:t}):t.name)}function u6(e){let t=e.command("workspace").description("List and switch Canary workspaces");t.command("list").description("List the workspaces you belong to (the active one is marked with *)").option("--json","output machine-readable JSON").action(async n=>{let q=n.json===!0;try{await ow(q)}catch(r){h6(q,r)}}),t.command("use <workspace>").description("Set the active workspace (by number from `list`, name, or id)").option("--json","output machine-readable JSON").action(async(n,q)=>{let r=q.json===!0;try{await iw(n,r)}catch(s){h6(r,s)}}),t.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(n=>aw(n.json===!0))}M1();bt();var I1=new Ei;I1.name("canary").description("Canary \u2014 break the code your AI writes.").version(ke);var p6=process.argv[2]==="hook"||process.argv[2]==="jobs"||process.argv[2]==="wait";p6||H3();p6||Sq();O4(I1);l6(I1);Sc(I1);a6(I1);u6(I1);n6(I1);i4(I1);Uc(I1);Fc(I1);U4(I1);hc(I1);_4(I1);No(I1);xc(I1);I1.addHelpText("after",`
|
|
3387
|
+
Ask Canary anything, in your own words: canary "find issues in billing" (or on stdin: canary -)`);var lw=new Set(["help",...I1.commands.flatMap(e=>[e.name(),...e.aliases()])]),hw=new Set(["-h","--help",...I1.options.flatMap(e=>[e.short,e.long]).filter(e=>!!e)]),m6=Dl(process.argv.slice(2),lw,hw);Y4()||(m6?Vl(process.cwd(),m6):I1.parseAsync(process.argv)).catch(e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)});
|
|
3358
3388
|
/*! Bundled license information:
|
|
3359
3389
|
|
|
3360
3390
|
smol-toml/dist/error.js:
|