@runcanary/cli 0.1.17 → 0.1.18
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 +184 -165
- 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 Iy=Object.create;var Ni=Object.defineProperty;var Ry=Object.getOwnPropertyDescriptor;var Ty=Object.getOwnPropertyNames;var Ey=Object.getPrototypeOf,Oy=Object.prototype.hasOwnProperty;var jr=(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 dn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_i=(e,t)=>{for(var n in t)Ni(e,n,{get:t[n],enumerable:!0})},$y=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ty(t))!Oy.call(e,s)&&s!==n&&Ni(e,s,{get:()=>t[s],enumerable:!(r=Ry(t,s))||r.enumerable});return e};var Ny=(e,t,n)=>(n=e!=null?Iy(Ey(e)):{},$y(t||!e||!e.__esModule?Ni(n,"default",{value:e,enumerable:!0}):n,e));var O,w=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 Ay=Object.create;var $i=Object.defineProperty;var Iy=Object.getOwnPropertyDe
|
|
|
15
15
|
}
|
|
16
16
|
`,"canary/.claude-plugin/plugin.json":`{
|
|
17
17
|
"name": "canary",
|
|
18
|
-
"version": "0.1.
|
|
18
|
+
"version": "0.1.18",
|
|
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",
|
|
@@ -1071,16 +1071,23 @@ export const register: Register = on => {
|
|
|
1071
1071
|
if (e.props.isSummary || e.surface !== 'desktop') return next(e)
|
|
1072
1072
|
const split = splitReport(e.props.text)
|
|
1073
1073
|
if (split === null) return next(e)
|
|
1074
|
+
// A change's report can be followed at once by an area's section (rfcs/stage-a/AREAS.md, D28): each is its own card.
|
|
1075
|
+
const reports = [split.report]
|
|
1076
|
+
let after = split.after
|
|
1077
|
+
for (let more = splitReport(after); more !== null && more.before === ''; more = splitReport(after)) {
|
|
1078
|
+
reports.push(more.report)
|
|
1079
|
+
after = more.after
|
|
1080
|
+
}
|
|
1074
1081
|
const ui = $.ui.resolve(e)
|
|
1075
1082
|
if (!('Svg' in ui)) return next(e)
|
|
1076
|
-
const drawn = inkedReport(
|
|
1077
|
-
if (drawn.source.length > SVG_LIMIT) return next(e)
|
|
1083
|
+
const drawn = reports.map(report => inkedReport(report, widthOf(e.viewport?.columns)))
|
|
1084
|
+
if (drawn.some(card => card.source.length > SVG_LIMIT)) return next(e)
|
|
1078
1085
|
const { Box, Markdown, Svg } = ui
|
|
1079
1086
|
return (
|
|
1080
1087
|
<Box flexDirection="column" gap="sm">
|
|
1081
1088
|
{split.before !== '' && <Markdown text={split.before} />}
|
|
1082
|
-
<Svg source={
|
|
1083
|
-
{
|
|
1089
|
+
{drawn.map((card, index) => <Svg key={index} source={card.source} alt={card.alt} width={card.width} height={card.height} />)}
|
|
1090
|
+
{after !== '' && <Markdown text={after} />}
|
|
1084
1091
|
</Box>
|
|
1085
1092
|
)
|
|
1086
1093
|
})
|
|
@@ -1139,20 +1146,21 @@ export interface Split {
|
|
|
1139
1146
|
after: string
|
|
1140
1147
|
}
|
|
1141
1148
|
|
|
1142
|
-
|
|
1149
|
+
// A change's report; an area's, which names the area; and an area's section after a change's report (AREAS.md, D28).
|
|
1150
|
+
const HEADING = /^## (?:Canary report(?: on (.+?))?|In (.+?)):\\s*(.+?)\\s*$/
|
|
1143
1151
|
// The caption after " \xB7 " may still be arriving: it is read as far as it has come.
|
|
1144
|
-
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+\\*(.*?)\\*?)?)?\\s*$/u
|
|
1152
|
+
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
|
|
1145
1153
|
const ITALIC_LINE = /^\\*(?!\\*)(.+)(?<!\\*)\\*$/
|
|
1146
|
-
const LABELED = /^(?:([\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA])\\s+)?\\*\\*([^*]+?):\\*\\*\\s+(.+)$/u
|
|
1154
|
+
const LABELED = /^(?:([\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA\u{1F535}])\\s+)?\\*\\*([^*]+?):\\*\\*\\s+(.+)$/u
|
|
1147
1155
|
const SHARE = /^\`(Canary \xB7 [^\`]+)\`$/
|
|
1148
1156
|
const ALIGN = /^\\|(\\s*:?-+:?\\s*\\|)+\\s*$/
|
|
1149
1157
|
const FENCE = /^\\s*(\`\`\`|~~~)/
|
|
1150
1158
|
|
|
1151
1159
|
/** Where each block sits in the report, in the order the server writes them. */
|
|
1152
|
-
const PLACE = { score: 1, reading: 2, stats: 3,
|
|
1160
|
+
const PLACE = { score: 1, reading: 2, stats: 3, read: 4, recheck: 5, findings: 6, open: 7, outside: 8, steps: 9, footer: 10, share: 11 }
|
|
1153
1161
|
|
|
1154
1162
|
/** The server's own lists, by their labels, and where each sits: what a 5 proved sits where the findings would. */
|
|
1155
|
-
const LISTS: Record<string, number> = { 'Proven by running': PLACE.findings, 'Outside the checks': PLACE.outside, 'To reach 5/5': PLACE.steps }
|
|
1163
|
+
const LISTS: Record<string, number> = { Read: PLACE.read, 'Proven by running': PLACE.findings, 'Outside the checks': PLACE.outside, 'To reach 5/5': PLACE.steps }
|
|
1156
1164
|
|
|
1157
1165
|
/** The line under a score one proof from 5. */
|
|
1158
1166
|
const READING = /^one proof from \\d\\/5$/
|
|
@@ -1203,7 +1211,10 @@ export function splitReport(text: string): Split | null {
|
|
|
1203
1211
|
}
|
|
1204
1212
|
if (start < 0) return null
|
|
1205
1213
|
|
|
1206
|
-
const
|
|
1214
|
+
const heading = HEADING.exec(lines[start]!)!
|
|
1215
|
+
const area = heading[1] ?? heading[2]
|
|
1216
|
+
// An area's report reads as the area and what was found in it, in the heading's own words.
|
|
1217
|
+
const report: Report = { verdict: area === undefined ? heading[3]! : \`\${heading[1] === undefined ? 'In' : 'on'} \${area}: \${heading[3]!}\`, score: null, blocks: [] }
|
|
1207
1218
|
let place = 0
|
|
1208
1219
|
let i = start + 1
|
|
1209
1220
|
let end = i
|
|
@@ -1231,7 +1242,8 @@ function read(block: string[], report: Report, place: number): number | null {
|
|
|
1231
1242
|
before: score[2] === undefined ? null : pipsOf(score[1]!),
|
|
1232
1243
|
pips: pipsOf(score[2] ?? score[1]!),
|
|
1233
1244
|
value: score[3]!,
|
|
1234
|
-
|
|
1245
|
+
// What the score is, when the line names it (an area's health), said with what capped it, in the report's own words.
|
|
1246
|
+
caption: score[4] === undefined ? score[5] || null : score[5] ? \`\${score[4]} \xB7 \${score[5]}\` : score[4],
|
|
1235
1247
|
reading: null,
|
|
1236
1248
|
}
|
|
1237
1249
|
return PLACE.score
|
|
@@ -1259,7 +1271,8 @@ function read(block: string[], report: Report, place: number): number | null {
|
|
|
1259
1271
|
if (labeled !== null) {
|
|
1260
1272
|
const at = LISTS[labeled[2]!]
|
|
1261
1273
|
if (at === undefined || at <= place) return null
|
|
1262
|
-
|
|
1274
|
+
// The area's Read line has its own mark, which the card draws as no pip.
|
|
1275
|
+
report.blocks.push({ kind: 'list', mark: labeled[1] === undefined || labeled[1] === '\u{1F535}' ? null : (labeled[1] as Pip), label: labeled[2]!, items: labeled[3]!.split(' \xB7 ') })
|
|
1263
1276
|
return at
|
|
1264
1277
|
}
|
|
1265
1278
|
const share = SHARE.exec(first)
|
|
@@ -1345,7 +1358,7 @@ When Claude Code itself refuses something (its permission mode turns a command d
|
|
|
1345
1358
|
|
|
1346
1359
|
## Keep a listener running
|
|
1347
1360
|
|
|
1348
|
-
- While a \`/canary\` request is still going, \`canary wait <request id>\` is the listener for its checks: start no \`canary jobs watch\` for them, take its \`start_verifier\` action as a "new checks" line and its \`answer\` action as a verifier's question, and keep running it as the \`canary\` skill says. Its \`say\` is what you tell the user about those checks, each result and the end included: add nothing of your own to it. Checks can be tried again while the request is still going too, as below: \`canary wait\` gives a \`start_verifier\` action for their batch, and the request's result waits for them. Once the request has ended, its checks are like any others here: to try some again, run \`canary jobs retry\` and start the listener below.
|
|
1361
|
+
- While a \`/canary\` request is still going, \`canary wait <request id>\` is the listener for its checks: start no \`canary jobs watch\` for them, take its \`start_verifier\` action as a "new checks" line and its \`answer\` action as a verifier's question (answered with \`canary jobs answer\`) unless its \`command\` starts with \`canary answer\`, which is the request's own question about which code to read and is answered as the \`canary\` skill says, and keep running it as the \`canary\` skill says. Its \`say\` is what you tell the user about those checks, each result and the end included: add nothing of your own to it. Checks can be tried again while the request is still going too, as below: \`canary wait\` gives a \`start_verifier\` action for their batch, and the request's result waits for them. Once the request has ended, its checks are like any others here: to try some again, run \`canary jobs retry\` and start the listener below.
|
|
1349
1362
|
- Start it with the Monitor tool, running \`canary jobs watch\`, with the Monitor tool's longest time limit. Every line it prints is something to act on. A long line arrives in parts, each cut marked with \`\u2026\`: read the parts as one. One runs per session; starting another replaces the old one.
|
|
1350
1363
|
- The Monitor tool ends a watch after its time limit and tells you; start it again, saying nothing of it to the user, while \`canary jobs list\` shows open checks for this session.
|
|
1351
1364
|
- When a conversation is resumed, or the user asks about Canary's checks, run \`canary jobs list\`. If this session has open checks and no listener is running, start one. Verifiers started before a resume are gone, even if \`list\` still shows their batches held on this machine: give each of those batches back with \`canary jobs finish <batch> --give-back\` and start a fresh verifier for it.
|
|
@@ -1428,52 +1441,52 @@ When the final report arrives, close with one short message, and write nothing a
|
|
|
1428
1441
|
- Don't stop processes or remove containers a verifier started; \`canary jobs finish\` does that.
|
|
1429
1442
|
- canary.md and secrets.env stay on this machine, outside the repository. Never copy them into the checkout, and never repeat secret values in chat.
|
|
1430
1443
|
- If the user asks about disk space: Canary keeps a copy of their code per repository under \`~/.canary/jobs/workspaces\` (two if two groups of checks ran at once), shared by the repository's worktrees, with what the checks installed and built, so later checks start faster. It removes a copy nothing has used for two weeks. A copy no running check uses (see \`canary jobs list\`) can be removed sooner with the user's yes; the next check builds it again.
|
|
1431
|
-
`}});var
|
|
1444
|
+
`}});var Pr=dn(Pi=>{w();var Bs=class extends Error{constructor(t,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=t,this.nestedError=void 0}},ji=class extends Bs{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Pi.CommanderError=Bs;Pi.InvalidArgumentError=ji});var Us=dn(Li=>{w();var{InvalidArgumentError:jy}=Pr(),Mi=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,r)=>{if(!this.argChoices.includes(n))throw new jy(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Py(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Li.Argument=Mi;Li.humanReadableArgName=Py});var Di=dn(Jl=>{w();var{humanReadableArgName:My}=Us(),Fi=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(t){let n=t.commands.filter(s=>!s._hidden),r=t._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,o)=>s.name().localeCompare(o.name())),n}compareOptions(t,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(t).localeCompare(r(n))}visibleOptions(t){let n=t.options.filter(s=>!s.hidden),r=t._getHelpOption();if(r&&!r.hidden){let s=r.short&&t._findOption(r.short),o=r.long&&t._findOption(r.long);!s&&!o?n.push(r):r.long&&!o?n.push(t.createOption(r.long,r.description)):r.short&&!s&&n.push(t.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let n=[];for(let r=t.parent;r;r=r.parent){let s=r.options.filter(o=>!o.hidden);n.push(...s)}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(r=>My(r)).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((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(t,n){return n.visibleOptions(t).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(t,n){return n.visibleGlobalOptions(t).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(t,n){return n.visibleArguments(t).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(t){let n=t._name;t._aliases[0]&&(n=n+"|"+t._aliases[0]);let r="";for(let s=t.parent;s;s=s.parent)r=s.name()+" "+r;return r+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(r=>JSON.stringify(r)).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(r=>JSON.stringify(r)).join(", ")}`),t.defaultValue!==void 0&&n.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return t.description?`${t.description} ${r}`:r}return t.description}formatHelp(t,n){let r=n.padWidth(t,n),s=n.helpWidth||80,o=2,i=2;function a(f,g){if(g){let m=`${f.padEnd(r+i)}${g}`;return n.wrap(m,s-o,r+i)}return f}function c(f){return f.join(`
|
|
1432
1445
|
`).replace(/^/gm," ".repeat(o))}let l=[`Usage: ${n.commandUsage(t)}`,""],d=n.commandDescription(t);d.length>0&&(l=l.concat([n.wrap(d,s,0),""]));let u=n.visibleArguments(t).map(f=>a(n.argumentTerm(f),n.argumentDescription(f)));u.length>0&&(l=l.concat(["Arguments:",c(u),""]));let h=n.visibleOptions(t).map(f=>a(n.optionTerm(f),n.optionDescription(f)));if(h.length>0&&(l=l.concat(["Options:",c(h),""])),this.showGlobalOptions){let f=n.visibleGlobalOptions(t).map(g=>a(n.optionTerm(g),n.optionDescription(g)));f.length>0&&(l=l.concat(["Global Options:",c(f),""]))}let p=n.visibleCommands(t).map(f=>a(n.subcommandTerm(f),n.subcommandDescription(f)));return p.length>0&&(l=l.concat(["Commands:",c(p),""])),l.join(`
|
|
1433
1446
|
`)}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,r,s=40){let o=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${o}]+`);if(t.match(i))return t;let a=n-r;if(a<s)return t;let c=t.slice(0,r),l=t.slice(r).replace(`\r
|
|
1434
1447
|
`,`
|
|
1435
1448
|
`),d=" ".repeat(r),h="\\s\u200B",p=new RegExp(`
|
|
1436
1449
|
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=l.match(p)||[];return c+f.map((g,m)=>g===`
|
|
1437
1450
|
`?"":(m>0?d:"")+g.trimEnd()).join(`
|
|
1438
|
-
`)}};
|
|
1451
|
+
`)}};Jl.Help=Fi});var qi=dn(Ui=>{w();var{InvalidArgumentError:Ly}=Pr(),Wi=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 r=Dy(t);this.short=r.shortFlag,this.long=r.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,r)=>{if(!this.argChoices.includes(n))throw new Ly(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Fy(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Bi=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,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(t,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,o=s!==void 0?s:!1;return n.negate===(o===t)}};function Fy(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function Dy(e){let t,n,r=e.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(t=r.shift()),n=r.shift(),!t&&/^-[^-]$/.test(n)&&(t=n,n=void 0),{shortFlag:t,longFlag:n}}Ui.Option=Wi;Ui.DualOptions=Bi});var Vl=dn(Yl=>{w();function Wy(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=e.length;s++){let o=1;e[s-1]===t[r-1]?o=0:o=1,n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+o),s>1&&r>1&&e[s-1]===t[r-2]&&e[s-2]===t[r-1]&&(n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1))}return n[e.length][t.length]}function By(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(i=>i.slice(2)));let r=[],s=3,o=.4;return t.forEach(i=>{if(i.length<=1)return;let a=Wy(e,i),c=Math.max(e.length,i.length);(c-a)/c>o&&(a<s?(s=a,r=[i]):a===s&&r.push(i))}),r.sort((i,a)=>i.localeCompare(a)),n&&(r=r.map(i=>`--${i}`)),r.length>1?`
|
|
1439
1452
|
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
1440
|
-
(Did you mean ${r[0]}?)`:""}
|
|
1441
|
-
- 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
|
|
1442
|
-
Expecting one of '${r.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,r){this._exitCallback&&this._exitCallback(new
|
|
1443
|
-
- already used by option '${n.flags}'`)}this.options.push(t)}_registerCommand(t){let n=s=>[s.name()].concat(s.aliases()),r=n(t).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),o=n(t).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),r=t.attributeName();if(t.negate){let o=t.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(r,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(r,t.defaultValue,"default");let s=(o,i,a)=>{o==null&&t.presetArg!==void 0&&(o=t.presetArg);let c=this.getOptionValue(r);o!==null&&t.parseArg?o=this._callParseArg(t,o,c,i):o!==null&&t.variadic&&(o=t._concatValue(o,c)),o==null&&(t.negate?o=!1:t.isBoolean()||t.optional?o=!0:o=""),this.setOptionValueWithSource(r,o,a)};return this.on("option:"+n,o=>{let i=`error: option '${t.flags}' argument '${o}' is invalid.`;s(o,i,"cli")}),t.envVar&&this.on("optionEnv:"+n,o=>{let i=`error: option '${t.flags}' value '${o}' from env '${t.envVar}' is invalid.`;s(o,i,"env")}),this}_optionEx(t,n,r,s,o){if(typeof n=="object"&&n instanceof
|
|
1453
|
+
(Did you mean ${r[0]}?)`:""}Yl.suggestSimilar=By});var Ql=dn(Zl=>{w();var Uy=jr("node:events").EventEmitter,Hi=jr("node:child_process"),It=jr("node:path"),Gi=jr("node:fs"),he=jr("node:process"),{Argument:qy,humanReadableArgName:Hy}=Us(),{CommanderError:Ji}=Pr(),{Help:Gy}=Di(),{Option:Kl,DualOptions:Jy}=qi(),{suggestSimilar:zl}=Vl(),Yi=class e extends Uy{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=>he.stdout.write(n),writeErr:n=>he.stderr.write(n),getOutHelpWidth:()=>he.stdout.isTTY?he.stdout.columns:void 0,getErrHelpWidth:()=>he.stderr.isTTY?he.stderr.columns:void 0,outputError:(n,r)=>r(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,r){let s=n,o=r;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,i,a]=t.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return s&&(c.description(s),c._executableHandler=!0),o.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(o.noHelp||o.hidden),c._executableFile=o.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(t){return new e(t)}createHelp(){return Object.assign(new Gy,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
|
|
1454
|
+
- 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 qy(t,n)}argument(t,n,r,s){let o=this.createArgument(t,n);return typeof r=="function"?o.default(s).argParser(r):o.default(r),this.addArgument(o),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[,r,s]=t.match(/([^ ]+) *(.*)/),o=n??"display help for command",i=this.createCommand(r);return i.helpOption(!1),s&&i.arguments(s),o&&i.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=i,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 r=["preSubcommand","preAction","postAction"];if(!r.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
1455
|
+
Expecting one of '${r.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,r){this._exitCallback&&this._exitCallback(new Ji(t,n,r)),he.exit(t)}action(t){let n=r=>{let s=this.registeredArguments.length,o=r.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),t.apply(this,o)};return this._actionHandler=n,this}createOption(t,n){return new Kl(t,n)}_callParseArg(t,n,r,s){try{return t.parseArg(n,r)}catch(o){if(o.code==="commander.invalidArgument"){let i=`${s} ${o.message}`;this.error(i,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(t){let n=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(n){let r=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 '${r}'
|
|
1456
|
+
- already used by option '${n.flags}'`)}this.options.push(t)}_registerCommand(t){let n=s=>[s.name()].concat(s.aliases()),r=n(t).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),o=n(t).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let n=t.name(),r=t.attributeName();if(t.negate){let o=t.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(r,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(r,t.defaultValue,"default");let s=(o,i,a)=>{o==null&&t.presetArg!==void 0&&(o=t.presetArg);let c=this.getOptionValue(r);o!==null&&t.parseArg?o=this._callParseArg(t,o,c,i):o!==null&&t.variadic&&(o=t._concatValue(o,c)),o==null&&(t.negate?o=!1:t.isBoolean()||t.optional?o=!0:o=""),this.setOptionValueWithSource(r,o,a)};return this.on("option:"+n,o=>{let i=`error: option '${t.flags}' argument '${o}' is invalid.`;s(o,i,"cli")}),t.envVar&&this.on("optionEnv:"+n,o=>{let i=`error: option '${t.flags}' value '${o}' from env '${t.envVar}' is invalid.`;s(o,i,"env")}),this}_optionEx(t,n,r,s,o){if(typeof n=="object"&&n instanceof Kl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(n,r);if(i.makeOptionMandatory(!!t.mandatory),typeof s=="function")i.default(o).argParser(s);else if(s instanceof RegExp){let a=s;s=(c,l)=>{let d=a.exec(c);return d?d[0]:l},i.default(o).argParser(s)}else i.default(s);return this.addOption(i)}option(t,n,r,s){return this._optionEx({},t,n,r,s)}requiredOption(t,n,r,s){return this._optionEx({mandatory:!0},t,n,r,s)}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,r){return this._storeOptionsAsProperties?this[t]=n:this._optionValues[t]=n,this._optionValueSources[t]=r,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(t)!==void 0&&(n=r.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){he.versions?.electron&&(n.from="electron");let s=he.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}t===void 0&&(t=he.argv),this.rawArgs=t.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=t[1],r=t.slice(2);break;case"electron":he.defaultApp?(this._scriptPath=t[1],r=t.slice(2)):r=t.slice(1);break;case"user":r=t.slice(0);break;case"eval":r=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",r}parse(t,n){let r=this._prepareUserArgs(t,n);return this._parseCommand([],r),this}async parseAsync(t,n){let r=this._prepareUserArgs(t,n);return await this._parseCommand([],r),this}_executeSubCommand(t,n){n=n.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(d,u){let h=It.resolve(d,u);if(Gi.existsSync(h))return h;if(s.includes(It.extname(u)))return;let p=s.find(f=>Gi.existsSync(`${h}${f}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Gi.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=It.resolve(It.dirname(d),a)}if(a){let d=o(a,i);if(!d&&!t._executableFile&&this._scriptPath){let u=It.basename(this._scriptPath,It.extname(this._scriptPath));u!==this._name&&(d=o(a,`${u}-${t._name}`))}i=d||i}r=s.includes(It.extname(i));let c;he.platform!=="win32"?r?(n.unshift(i),n=Xl(he.execArgv).concat(n),c=Hi.spawn(he.argv[0],n,{stdio:"inherit"})):c=Hi.spawn(i,n,{stdio:"inherit"}):(n.unshift(i),n=Xl(he.execArgv).concat(n),c=Hi.spawn(he.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{he.on(u,()=>{c.killed===!1&&c.exitCode===null&&c.kill(u)})});let l=this._exitCallback;c.on("close",d=>{d=d??1,l?l(new Ji(d,"commander.executeSubCommandAsync","(close)")):he.exit(d)}),c.on("error",d=>{if(d.code==="ENOENT"){let u=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${i}' does not exist
|
|
1444
1457
|
- if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1445
1458
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1446
|
-
- ${u}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)he.exit(1);else{let u=new
|
|
1459
|
+
- ${u}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)he.exit(1);else{let u=new Ji(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,l(u)}}),this.runningCommand=c}_dispatchSubcommand(t,n,r){let s=this._findCommand(t);s||this.help({error:!0});let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(r));else return s._parseCommand(n,r)}),o}_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=(r,s,o)=>{let i=s;if(s!==null&&r.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;i=this._callParseArg(r,s,o,a)}return i};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,s)=>{let o=r.defaultValue;r.variadic?s<this.args.length?(o=this.args.slice(s),r.parseArg&&(o=o.reduce((i,a)=>t(r,a,i),r.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],r.parseArg&&(o=t(r,o,r.defaultValue))),n[s]=o}),this.processedArgs=n}_chainOrCall(t,n){return t&&t.then&&typeof t.then=="function"?t.then(()=>n()):n()}_chainOrCallHooks(t,n){let r=t,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[n]!==void 0).forEach(o=>{o._lifeCycleHooks[n].forEach(i=>{s.push({hookedCommand:o,callback:i})})}),n==="postAction"&&s.reverse(),s.forEach(o=>{r=this._chainOrCall(r,()=>o.callback(o.hookedCommand,this))}),r}_chainOrCallSubCommandHook(t,n,r){let s=t;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(o=>{s=this._chainOrCall(s,()=>o(this,n))}),s}_parseCommand(t,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(r.operands),n=r.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(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(o,t,n)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,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():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),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(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});t.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=t.find(o=>r.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let n=[],r=[],s=n,o=t.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;o.length;){let c=o.shift();if(c==="--"){s===r&&s.push(c),s.push(...o);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let d=o.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;o.length>0&&!i(o[0])&&(d=o.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),o.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),d=this._findOption(c.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,c.slice(l+1));continue}}if(i(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),o.length>0&&r.push(...o);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),o.length>0&&n.push(...o);break}else if(this._defaultCommandName){r.push(c),o.length>0&&r.push(...o);break}}if(this._passThroughOptions){s.push(c),o.length>0&&s.push(...o);break}s.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let t={},n=this.options.length;for(let r=0;r<n;r++){let s=this.options[r].attributeName();t[s]=s===this._versionOptionName?this._version:this[s]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,n)=>Object.assign(t,n.opts()),{})}error(t,n){this._outputConfiguration.outputError(`${t}
|
|
1447
1460
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
1448
1461
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
1449
|
-
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,o=r.code||"commander.error";this._exit(s,o,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in he.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()}`,he.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new
|
|
1462
|
+
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,o=r.code||"commander.error";this._exit(s,o,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in he.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()}`,he.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new Jy(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&t.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"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 r=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(u=>u.negate&&a===u.attributeName()),d=this.options.find(u=>!u.negate&&a===u.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:d||i},s=i=>{let a=r(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${s(t)} cannot be used with ${s(n)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let n="";if(t.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let i=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);s=s.concat(i),o=o.parent}while(o&&!o._enablePositionalOptions);n=zl(t,s)}let r=`error: unknown option '${t}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${t.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),n=zl(t,s)}let r=`error: unknown command '${t}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(t,n,r){if(t===void 0)return this._version;this._version=t,n=n||"-V, --version",r=r||"output the version number";let s=this.createOption(n,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
1450
1463
|
`),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 r=this.parent?._findCommand(t);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${s}'`)}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(r=>Hy(r));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=It.basename(t,It.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},r;return n.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),n.write=t.write||r,n.command=this,n}outputHelp(t){let n;typeof t=="function"&&(n=t,t=void 0);let r=this._getHelpContext(t);this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(n&&(s=n(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",r))}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=he.exitCode||0;n===0&&t&&typeof t!="function"&&t.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(t,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
1451
1464
|
Expecting one of '${r.join("', '")}'`);let s=`${t}Help`;return this.on(s,o=>{let i;typeof n=="function"?i=n({error:o.error,command:o.command}):i=n,i&&o.write(`${i}
|
|
1452
|
-
`)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
1453
|
-
`,{flag:"wx"}),()=>{
|
|
1454
|
-
`,{mode:384}),
|
|
1465
|
+
`)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Xl(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",s="9229",o;return(o=t.match(/^(--inspect(-brk)?)$/))!==null?n=o[1]:(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=o[1],/^\d+$/.test(o[3])?s=o[3]:r=o[3]):(o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=o[1],r=o[3],s=o[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:t})}Zl.Command=Yi});var ru=dn(tt=>{w();var{Argument:eu}=Us(),{Command:Vi}=Ql(),{CommanderError:Yy,InvalidArgumentError:tu}=Pr(),{Help:Vy}=Di(),{Option:nu}=qi();tt.program=new Vi;tt.createCommand=e=>new Vi(e);tt.createOption=(e,t)=>new nu(e,t);tt.createArgument=(e,t)=>new eu(e,t);tt.Command=Vi;tt.Option=nu;tt.Argument=eu;tt.Help=Vy;tt.CommanderError=Yy;tt.InvalidArgumentError=tu;tt.InvalidOptionArgumentError=tu});import{execFileSync as Ky}from"node:child_process";import{randomUUID as zy}from"node:crypto";import{chmodSync as Xy,mkdirSync as Xi,readFileSync as Zi,renameSync as Zy,rmSync as lu,statSync as Qy,writeFileSync as uu}from"node:fs";import{homedir as ew}from"node:os";import{dirname as du,join as Qi}from"node:path";function K(){return process.env.CANARY_HOME||Qi(ew(),".canary")}function ea(){return Qi(K(),"config.json")}function hu(){let{config:e}=na();if(e.installId&&au.test(e.installId))return e.installId;cu??=zy();let t=cu;try{Ne(n=>n.installId&&au.test(n.installId)?n:{...n,installId:t})}catch{}return t}function V(){return na().config}function fu(e){return V().repoFingerprints?.[e]}function pu(e,t){try{Ne(n=>({...n,repoFingerprints:{...n.repoFingerprints,[e]:t}}))}catch{}}function mu(e){gu=e}function yu(){return`${ea()}.lock`}function aw(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Rt(e){try{let t=Ky("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 uw(e){let t;try{t=Zi(ta(e),"utf8").trim()}catch{return"unknown"}let[n,r]=t.split(" ").map(Number);if(!Number.isInteger(n)||n<=0||!Number.isFinite(r))return"unknown";try{process.kill(n,0)}catch(o){if(o.code==="ESRCH")return!1}let s=Rt(n);return s===null?!0:Math.abs(s-r)<=lw}function bu(e){try{return Zi(ta(e),"utf8").trim()===wu}catch{return!1}}function Ki(e){try{lu(e,{recursive:!0,force:!0})}catch{}}function ku(e=yu(),t="the config lock"){let n=Date.now()+iw();for(;;)try{return Xi(du(e),{recursive:!0,mode:448}),Xi(e),uu(ta(e),`${wu}
|
|
1466
|
+
`,{flag:"wx"}),()=>{bu(e)&&Ki(e)}}catch(r){if(r.code!=="EEXIST")throw r;let s=uw(e);if(s===!1){Ki(e);continue}if(s==="unknown")try{if(Date.now()-Qy(e).mtimeMs>sw){Ki(e);continue}}catch{}if(Date.now()>=n)throw new hn(`another canary process is holding ${t}`);aw(ow)}}function Mr(e,t,n){let r=ku(e,t);try{return n()}finally{r()}}function Ne(e,t={}){let n=()=>{let{config:s,unreadable:o}=na();if(o&&!t.overwriteUnreadable)return!1;let i=e(o?{}:s);if(!bu(yu()))throw new hn("the config lock changed hands during the write");return dw(i),!0};if(zi>0)return n();let r=ku();zi+=1;try{return n()}finally{zi-=1,r()}}function na(){let e;try{e=Zi(ea(),"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 dw(e){let t=ea();Xi(du(t),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;try{uu(n,JSON.stringify(e,null,2)+`
|
|
1467
|
+
`,{mode:384}),Xy(n,384),Zy(n,t)}catch(r){throw lu(n,{force:!0}),r}}function vu(){Ne(({apiUrl:e,webUrl:t,installId:n,agentSkills:r,repoFingerprints:s,gate:o,hooks:i})=>({...e?{apiUrl:e}:{},...t?{webUrl:t}:{},...n?{installId:n}:{},...r!==void 0?{agentSkills:r}:{},...s?{repoFingerprints:s}:{},...o?{gate:o}:{},...i?{hooks:i}:{}}))}function Q(){return process.env.CANARY_TOKEN||V().token}function ue(){return process.env.CANARY_API_URL||V().apiUrl||tw}function Tt(){let e=process.env.CANARY_WEB_URL||V().webUrl;if(e)return e;let t=process.env.CANARY_API_URL||V().apiUrl;return t?t.replace("//api.","//www."):nw}var tw,nw,au,cu,hn,rw,sw,ow,gu,iw,ta,cw,wu,lw,zi,ee=Z(()=>{"use strict";w();tw="https://api.runcanary.ai",nw="https://www.runcanary.ai";au=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,cu=null;hn=class extends Error{constructor(t="another canary process is holding the config lock"){super(`${t}; run the command again`),this.name="ConfigLockError"}},rw=15e3,sw=1e4,ow=20;iw=()=>gu??(Number(process.env.CANARY_CONFIG_LOCK_WAIT_MS)||rw);ta=e=>Qi(e,"owner");cw=Math.round(Date.now()-process.uptime()*1e3),wu=`${process.pid} ${cw}`,lw=3e3;zi=0});function hw(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function fw(e,t,n){let r=e.split(/\r?\n/),s="",o=(Math.log10(t+1)|0)+1;for(let i=t-1;i<=t+1;i++){let a=r[i-1];a&&(s+=i.toString().padEnd(o," "),s+=": ",s+=a,s+=`
|
|
1455
1468
|
`,i===t&&(s+=" ".repeat(o+n+2),s+=`^
|
|
1456
|
-
`))}return s}var
|
|
1469
|
+
`))}return s}var B,fn=Z(()=>{w();B=class e extends Error{line;column;codeblock;constructor(t,n){let[r,s]=hw(n.toml,n.ptr),o=fw(n.toml,r,s);super(`Invalid TOML document: ${t}
|
|
1457
1470
|
|
|
1458
|
-
${o}`,n),this.line=r,this.column=s,this.codeblock=o}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}}});function
|
|
1459
|
-
`:n===102?i+="\f":n===114?i+="\r":n===101?i+="\x1B":n===34?i+='"':n===92?i+="\\":W.x("unrecognised escape sequence",e),a=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&W.x("invalid escape: only line-ending whitespace may be escaped",e,a),c=!s&&n===92?1:0,a=e.p);W.x("unfinished string",e,t)}var na=Z(()=>{w();fn();});var fw,Mr,ra=Z(()=>{w();fw=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,Mr=class e extends Date{#t=!1;#n=!1;#e=null;constructor(t,n,r){let s=!0,o=!0,i="Z",a;if(typeof t=="string")if(n)e:{if(n<3){if(+t.slice(11,13)>23){t="";break e}n===2?(i=null,t+="Z"):(a=t.charCodeAt(t.length-1))!==90&&a!==122&&(i=t.slice(t.length-6)),r&&(t=t.slice(0,10)+"T"+t.slice(11))}else n===4&&(t=+t.slice(0,2)>23?"":`0000-01-01T${t}Z`);s=n!==4,o=n!==3}else{let c=t.match(fw);c?(c[1]||(s=!1,t=`0000-01-01T${t}`),o=!!c[2],o&&t[10]===" "&&(t=t.replace(" ","T")),c[2]&&+c[2]>23?t="":(i=c[3]||null,!i&&o&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=s,this.#n=o,this.#e=i)}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 r=new e(t);return r.#e=n,r}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 Ve(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function oa(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Fr(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||W.x("document contains excessively nested structures. aborting.",e);let s=r===91?xu(e):vu(e);return e.d++,s}return r===34||r===39?Hs(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&W.x("invalid value",e,n),e.p++,!0):r===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)&&W.x("invalid value",e,n),e.p++,!1):r===43||r===45?qs(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?pw(e,r,t):e.s.charCodeAt(e.p+2)===58?gw(e,r,t):qs(e,e.p,r,0,t)}function qs(e,t,n,r,s){let o=n,i=0,a=!1;if(o===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&W.x("invalid value",e,t),e.p++,(r||1)/0;if(o===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&W.x("invalid value",e,t),e.p++,NaN;if(o===48){if(++e.p>=e.s.length||oa(o=e.s.charCodeAt(e.p),s))return e.bi===!0?0n:0;if(!r){if(o===120)return sa(e,t,16,s);if(o===98)return sa(e,t,2,s);if(o===111)return sa(e,t,8,s)}o===46?i=2:o===101||o===69?i=4:W.x("illegal leading zero",e,t)}else Ve(o)||W.x("invalid value",e,t);for(;++e.p<e.s.length&&(o=e.s.charCodeAt(e.p),!oa(o,s));)i||(i=1),o===95?(i&1||W.x("illegal underscore",e),i+=11,a=!0):i===1&&o===46?i=2:(i===1||i===3)&&(o===101||o===69)?i=4:i===4&&(o===43||o===45)||(Ve(o)?i>9?i-=11:i&1||i++:W.x("illegal character in numeric literal",e));if(!i){let l=(n-48)*(r||1);return e.bi===!0?BigInt(l):l}i&1||W.x("unfinished numeric value",e,t);let c=e.s.slice(t,e.p);return a&&(c=c.replaceAll("_","")),i>1?parseFloat(c):ku(e,c,10,t)}function sa(e,t,n,r){let s,o=1;for(;++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!oa(s,r));)s===95?(o&1&&W.x("illegal underscore",e),o=3):Ve(s,n)?o&1&&o--:W.x("illegal character in numeric literal",e);o&1&&W.x("unfinished numeric value",e);let i=e.s.slice(t+2,e.p);return o&&(i=i.replaceAll("_","")),ku(e,i,n,t)}function ku(e,t,n,r){if(e.bi!==!0)e:{let s=parseInt(t,n);if(!Number.isSafeInteger(s)){if(e.bi)break e;W.x("integer value cannot be represented losslessly",e,r)}return s}return BigInt(n===10?t:(n===2?"0b":n===8?"0o":"0x")+t)}function pw(e,t,n){let r=e.p++,s;if(!Ve(t)||!Ve(e.s.charCodeAt(e.p++))||!Ve(e.s.charCodeAt(e.p++))||!Ve(e.s.charCodeAt(e.p++)))return qs(e,e.p=r,t,0,n);if(e.p+=5,Ve(e.s.charCodeAt(e.p++))||W.x("invalid date-time: date part is malformed",e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(s=!0,!Ve(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let i=e.s.slice(r,e.p);return Lr(e,i,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58&&W.x("invalid date-time: time part is malformed",e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;Ve(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let i=e.s.slice(r,++e.p);return Lr(e,i,1,s,r,"[+00:00]")}if(t===43||t===45){let i=e.s.slice(r,e.p+=6);return Lr(e,i,1,s,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let o=e.s.slice(r,e.p);return Lr(e,o,2,s,r)}function gw(e,t,n){let r=e.p;if(!Ve(t)||!Ve(e.s.charCodeAt(++e.p)))return qs(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;Ve(e.s.charCodeAt(++e.p)););let s=e.s.slice(r,e.p);return Lr(e,s,4,!1,r)}function Lr(e,t,n,r,s,o){if(e.ld){let i=new Mr(t,n,r);return i.isValid()||W.x("invalid date",e,s),i}try{switch(o&&(t+=o),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(i){W.x(i instanceof Error?i.message:""+i,e,s)}}var ia=Z(()=>{w();na();aa();fn();ra();});function mw(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)&&W.x("control characters are not allowed in comments",e)}}function lt(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;mw(e)}}var ca=Z(()=>{w();fn();});function Gs(e,t=61){let n,r=0,s=[],o,i=e.s.charCodeAt(n=e.p);do{if(i===t)return r||W.x("unexpected end of key",e),r===1&&s.push(e.s.slice(o,e.p)),e.p++,s;i===46?(r||W.x("illegal empty bare key",e),r===1&&s.push(e.s.slice(o,e.p)),r=0):!r&&(i===34||i===39)?(i===e.s.charCodeAt(e.p+1)&&i===e.s.charCodeAt(e.p+2)&&W.x("illegal quoted key: multiline strings are not allowed",e),s.push(Hs(e)),r=2,e.p--):i===32||i===9?r===1&&(s.push(e.s.slice(o,e.p)),r=2):r===2||i<48&&i!==45||i>57&&i<65||i>90&&i<97&&i!==95||i>122?W.x("illegal character in key",e):r||(r=1,o=e.p)}while(i=e.s.charCodeAt(++e.p));W.x("incomplete key-value: cannot find end of key",e,n)}function vu(e){let t=e.p++,n=Object.create(null),r=new Set,s;for(;e.p<e.s.length;){if(lt(e),(s=e.s.charCodeAt(e.p))===125)return e.p++,n;let o,i=n,a=!1,c=e.p,l=Gs(e);for(let u=0;u<l.length;u++){u&&(i=a?i[o]:i[o]=Object.create(null)),o=l[u],(a=Object.hasOwn(i,o))&&(typeof i[o]!="object"||r.has(i[o]))&&W.x("trying to redefine an already defined value",e,c);let h=o==="__proto__";if(e.uk&&(h||o==="constructor")){i=e.uk!==1&&W.x("document contains an unsafe property",e,c);break}!a&&h&&Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0})}a&&W.x("trying to redefine an already defined value",e,c),lt(e,!0,!0);let d=Fr(e,125);if(i&&typeof(i[o]=d)=="object"&&r.add(d),lt(e),(s=e.s.charCodeAt(e.p++))===125)return n;s!==44&&W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished table",e,t)}function xu(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(lt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Fr(e,93)),lt(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished array",e,t)}var aa=Z(()=>{w();na();ia();ca();fn();});function Su(e,t,n,r,s){let o=n,i=r,a,c=!1,l;for(let d=0;d<t.length;d++){if(d){if(o=c?o[a]:o[a]=Object.create(null),i=(l=i[a]).c,s===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=o.length-1;o=o[u],i=i[u].c}}if(a=t[d],(c=Object.hasOwn(o,a))&&i[a]?.t===0&&i[a]?.d)return null;if(!c){let u=a==="__proto__";if(e.uk&&(u||a==="constructor"))return!1;u&&(Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0})),i[a]={t:d<t.length-1&&s===2?3:s,d:!1,i:0,c:Object.create(null)}}}if(l=i[a],l.t!==s&&!(s===1&&l.t===3)||(s===2&&(l.d||(l.d=!0,o[a]=[]),o[a].push(o=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,s===1)o=c?o[a]:o[a]=Object.create(null);else if(s===0&&c)return null;return[a,o,l.c]}function Cu(e,t,n){(t===null||e.uk===2)&&W.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function la(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},r=Object.create(null),s=Object.create(null),o,i=!1,a=r,c=s;for(e.charCodeAt(0)===65279&&n.p++,lt(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let l=e.charCodeAt(++n.p)===91;o=n.p+=+l,i=!1;let d=Gs(n,93);l&&(e.charCodeAt(n.p)!==93&&W.x("expected end of table array declaration",n),n.p++);let u=Su(n,d,r,s,l?2:1);u?(c=u[2],a=u[1]):(Cu(n,u,o),i=!0)}else{o=n.p;let l=Gs(n),d=Su(n,l,a,c,0);!d&&!i&&Cu(n,d,o),lt(n,!0,!0);let u=Fr(n,void 0);d&&!i&&(d[1][d[0]]=u)}lt(n,!0),n.p<e.length&&(o=e.charCodeAt(n.p))!==10&&(o!==13||e.charCodeAt(n.p+1)!==10)&&W.x("each key-value declaration must be followed by an end-of-line",n),lt(n)}return r}var Au=Z(()=>{w();aa();ia();ca();fn();});var ZR,Iu=Z(()=>{w();ZR=!!"".isWellFormed});var Ru=Z(()=>{w();Au();Iu();ra();fn();});import{spawnSync as yw}from"node:child_process";import{createHash as ww,randomBytes as bw,randomUUID as kw}from"node:crypto";import{accessSync as da,chmodSync as vw,chownSync as xw,closeSync as Sw,constants as ha,existsSync as Cw,fstatSync as Aw,lstatSync as Nu,mkdirSync as Iw,mkdtempSync as Rw,openSync as Tw,readFileSync as _u,readlinkSync as Ew,realpathSync as Tu,renameSync as Ow,rmSync as Mt,statSync as Js,writeFileSync as fa}from"node:fs";import{tmpdir as $w}from"node:os";import{basename as Nw,delimiter as _w,dirname as Ys,join as Hn,resolve as jw}from"node:path";function qn(e){try{return{doc:la(e,{integersAsBigInt:"asNeeded"})}}catch(t){let n=(t instanceof Error?t.message:String(t)).split(`
|
|
1460
|
-
`)[0].replace(/^Invalid TOML document:\s*/,"");return{problem:{line:t instanceof
|
|
1471
|
+
${o}`,n),this.line=r,this.column=s,this.codeblock=o}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}}});function qs(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,s=n===39,o=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);o&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let i="",a=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),o&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c=c&&3;else if(n<32&&n!==9||n===127)B.x("control characters are not allowed in strings",e);else if((!c||c===3)&&n===r&&(!o||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(o&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let l=e.s.slice(a,e.p);i=i?i+l:l}return e.p+=o?3:1,i}else if(!c)!s&&n===92&&(i+=e.s.slice(a,a=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let l=e.p++-1,d=0,u=n===120?2:n===117?4:8;for(let h=0;h<u;h++,e.p++){let p=e.s.charCodeAt(e.p),f=p>=48&&p<=57?p-48:p>=65&&p<=70?p-65+10:p>=97&&p<=102?p-97+10:-1;f<0&&B.x("invalid non-hex character in unicode escape",e),d=d<<4|f}(d<0||d>1114111||d>=55296&&d<=57343)&&B.x("invalid unicode escape",e,l),i+=String.fromCodePoint(d),a=e.p--,c=0}else o&&(n===32||n===9)?c=2:(n===98?i+="\b":n===116?i+=" ":n===110?i+=`
|
|
1472
|
+
`:n===102?i+="\f":n===114?i+="\r":n===101?i+="\x1B":n===34?i+='"':n===92?i+="\\":B.x("unrecognised escape sequence",e),a=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&B.x("invalid escape: only line-ending whitespace may be escaped",e,a),c=!s&&n===92?1:0,a=e.p);B.x("unfinished string",e,t)}var ra=Z(()=>{w();fn();});var pw,Lr,sa=Z(()=>{w();pw=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,Lr=class e extends Date{#t=!1;#n=!1;#e=null;constructor(t,n,r){let s=!0,o=!0,i="Z",a;if(typeof t=="string")if(n)e:{if(n<3){if(+t.slice(11,13)>23){t="";break e}n===2?(i=null,t+="Z"):(a=t.charCodeAt(t.length-1))!==90&&a!==122&&(i=t.slice(t.length-6)),r&&(t=t.slice(0,10)+"T"+t.slice(11))}else n===4&&(t=+t.slice(0,2)>23?"":`0000-01-01T${t}Z`);s=n!==4,o=n!==3}else{let c=t.match(pw);c?(c[1]||(s=!1,t=`0000-01-01T${t}`),o=!!c[2],o&&t[10]===" "&&(t=t.replace(" ","T")),c[2]&&+c[2]>23?t="":(i=c[3]||null,!i&&o&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#t=s,this.#n=o,this.#e=i)}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 r=new e(t);return r.#e=n,r}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 Ve(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function ia(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Dr(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||B.x("document contains excessively nested structures. aborting.",e);let s=r===91?Cu(e):Su(e);return e.d++,s}return r===34||r===39?qs(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&B.x("invalid value",e,n),e.p++,!0):r===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)&&B.x("invalid value",e,n),e.p++,!1):r===43||r===45?Hs(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?gw(e,r,t):e.s.charCodeAt(e.p+2)===58?mw(e,r,t):Hs(e,e.p,r,0,t)}function Hs(e,t,n,r,s){let o=n,i=0,a=!1;if(o===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&B.x("invalid value",e,t),e.p++,(r||1)/0;if(o===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&B.x("invalid value",e,t),e.p++,NaN;if(o===48){if(++e.p>=e.s.length||ia(o=e.s.charCodeAt(e.p),s))return e.bi===!0?0n:0;if(!r){if(o===120)return oa(e,t,16,s);if(o===98)return oa(e,t,2,s);if(o===111)return oa(e,t,8,s)}o===46?i=2:o===101||o===69?i=4:B.x("illegal leading zero",e,t)}else Ve(o)||B.x("invalid value",e,t);for(;++e.p<e.s.length&&(o=e.s.charCodeAt(e.p),!ia(o,s));)i||(i=1),o===95?(i&1||B.x("illegal underscore",e),i+=11,a=!0):i===1&&o===46?i=2:(i===1||i===3)&&(o===101||o===69)?i=4:i===4&&(o===43||o===45)||(Ve(o)?i>9?i-=11:i&1||i++:B.x("illegal character in numeric literal",e));if(!i){let l=(n-48)*(r||1);return e.bi===!0?BigInt(l):l}i&1||B.x("unfinished numeric value",e,t);let c=e.s.slice(t,e.p);return a&&(c=c.replaceAll("_","")),i>1?parseFloat(c):xu(e,c,10,t)}function oa(e,t,n,r){let s,o=1;for(;++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!ia(s,r));)s===95?(o&1&&B.x("illegal underscore",e),o=3):Ve(s,n)?o&1&&o--:B.x("illegal character in numeric literal",e);o&1&&B.x("unfinished numeric value",e);let i=e.s.slice(t+2,e.p);return o&&(i=i.replaceAll("_","")),xu(e,i,n,t)}function xu(e,t,n,r){if(e.bi!==!0)e:{let s=parseInt(t,n);if(!Number.isSafeInteger(s)){if(e.bi)break e;B.x("integer value cannot be represented losslessly",e,r)}return s}return BigInt(n===10?t:(n===2?"0b":n===8?"0o":"0x")+t)}function gw(e,t,n){let r=e.p++,s;if(!Ve(t)||!Ve(e.s.charCodeAt(e.p++))||!Ve(e.s.charCodeAt(e.p++))||!Ve(e.s.charCodeAt(e.p++)))return Hs(e,e.p=r,t,0,n);if(e.p+=5,Ve(e.s.charCodeAt(e.p++))||B.x("invalid date-time: date part is malformed",e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(s=!0,!Ve(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let i=e.s.slice(r,e.p);return Fr(e,i,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58&&B.x("invalid date-time: time part is malformed",e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;Ve(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let i=e.s.slice(r,++e.p);return Fr(e,i,1,s,r,"[+00:00]")}if(t===43||t===45){let i=e.s.slice(r,e.p+=6);return Fr(e,i,1,s,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let o=e.s.slice(r,e.p);return Fr(e,o,2,s,r)}function mw(e,t,n){let r=e.p;if(!Ve(t)||!Ve(e.s.charCodeAt(++e.p)))return Hs(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;Ve(e.s.charCodeAt(++e.p)););let s=e.s.slice(r,e.p);return Fr(e,s,4,!1,r)}function Fr(e,t,n,r,s,o){if(e.ld){let i=new Lr(t,n,r);return i.isValid()||B.x("invalid date",e,s),i}try{switch(o&&(t+=o),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(i){B.x(i instanceof Error?i.message:""+i,e,s)}}var aa=Z(()=>{w();ra();ca();fn();sa();});function yw(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)&&B.x("control characters are not allowed in comments",e)}}function ut(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;yw(e)}}var la=Z(()=>{w();fn();});function Gs(e,t=61){let n,r=0,s=[],o,i=e.s.charCodeAt(n=e.p);do{if(i===t)return r||B.x("unexpected end of key",e),r===1&&s.push(e.s.slice(o,e.p)),e.p++,s;i===46?(r||B.x("illegal empty bare key",e),r===1&&s.push(e.s.slice(o,e.p)),r=0):!r&&(i===34||i===39)?(i===e.s.charCodeAt(e.p+1)&&i===e.s.charCodeAt(e.p+2)&&B.x("illegal quoted key: multiline strings are not allowed",e),s.push(qs(e)),r=2,e.p--):i===32||i===9?r===1&&(s.push(e.s.slice(o,e.p)),r=2):r===2||i<48&&i!==45||i>57&&i<65||i>90&&i<97&&i!==95||i>122?B.x("illegal character in key",e):r||(r=1,o=e.p)}while(i=e.s.charCodeAt(++e.p));B.x("incomplete key-value: cannot find end of key",e,n)}function Su(e){let t=e.p++,n=Object.create(null),r=new Set,s;for(;e.p<e.s.length;){if(ut(e),(s=e.s.charCodeAt(e.p))===125)return e.p++,n;let o,i=n,a=!1,c=e.p,l=Gs(e);for(let u=0;u<l.length;u++){u&&(i=a?i[o]:i[o]=Object.create(null)),o=l[u],(a=Object.hasOwn(i,o))&&(typeof i[o]!="object"||r.has(i[o]))&&B.x("trying to redefine an already defined value",e,c);let h=o==="__proto__";if(e.uk&&(h||o==="constructor")){i=e.uk!==1&&B.x("document contains an unsafe property",e,c);break}!a&&h&&Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0})}a&&B.x("trying to redefine an already defined value",e,c),ut(e,!0,!0);let d=Dr(e,125);if(i&&typeof(i[o]=d)=="object"&&r.add(d),ut(e),(s=e.s.charCodeAt(e.p++))===125)return n;s!==44&&B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished table",e,t)}function Cu(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(ut(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Dr(e,93)),ut(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished array",e,t)}var ca=Z(()=>{w();ra();aa();la();fn();});function Au(e,t,n,r,s){let o=n,i=r,a,c=!1,l;for(let d=0;d<t.length;d++){if(d){if(o=c?o[a]:o[a]=Object.create(null),i=(l=i[a]).c,s===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=o.length-1;o=o[u],i=i[u].c}}if(a=t[d],(c=Object.hasOwn(o,a))&&i[a]?.t===0&&i[a]?.d)return null;if(!c){let u=a==="__proto__";if(e.uk&&(u||a==="constructor"))return!1;u&&(Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0})),i[a]={t:d<t.length-1&&s===2?3:s,d:!1,i:0,c:Object.create(null)}}}if(l=i[a],l.t!==s&&!(s===1&&l.t===3)||(s===2&&(l.d||(l.d=!0,o[a]=[]),o[a].push(o=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,s===1)o=c?o[a]:o[a]=Object.create(null);else if(s===0&&c)return null;return[a,o,l.c]}function Iu(e,t,n){(t===null||e.uk===2)&&B.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function ua(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},r=Object.create(null),s=Object.create(null),o,i=!1,a=r,c=s;for(e.charCodeAt(0)===65279&&n.p++,ut(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let l=e.charCodeAt(++n.p)===91;o=n.p+=+l,i=!1;let d=Gs(n,93);l&&(e.charCodeAt(n.p)!==93&&B.x("expected end of table array declaration",n),n.p++);let u=Au(n,d,r,s,l?2:1);u?(c=u[2],a=u[1]):(Iu(n,u,o),i=!0)}else{o=n.p;let l=Gs(n),d=Au(n,l,a,c,0);!d&&!i&&Iu(n,d,o),ut(n,!0,!0);let u=Dr(n,void 0);d&&!i&&(d[1][d[0]]=u)}ut(n,!0),n.p<e.length&&(o=e.charCodeAt(n.p))!==10&&(o!==13||e.charCodeAt(n.p+1)!==10)&&B.x("each key-value declaration must be followed by an end-of-line",n),ut(n)}return r}var Ru=Z(()=>{w();ca();aa();la();fn();});var eT,Tu=Z(()=>{w();eT=!!"".isWellFormed});var Eu=Z(()=>{w();Ru();Tu();sa();fn();});import{spawnSync as ww}from"node:child_process";import{createHash as bw,randomBytes as kw,randomUUID as vw}from"node:crypto";import{accessSync as ha,chmodSync as xw,chownSync as Sw,closeSync as Cw,constants as fa,existsSync as Aw,fstatSync as Iw,lstatSync as ju,mkdirSync as Rw,mkdtempSync as Tw,openSync as Ew,readFileSync as Pu,readlinkSync as Ow,realpathSync as Ou,renameSync as $w,rmSync as Lt,statSync as Js,writeFileSync as pa}from"node:fs";import{tmpdir as Nw}from"node:os";import{basename as _w,delimiter as jw,dirname as Ys,join as qn,resolve as Pw}from"node:path";function Hn(e){try{return{doc:ua(e,{integersAsBigInt:"asNeeded"})}}catch(t){let n=(t instanceof Error?t.message:String(t)).split(`
|
|
1473
|
+
`)[0].replace(/^Invalid TOML document:\s*/,"");return{problem:{line:t instanceof B?t.line:0,message:n}}}}function Lw(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!ju(t).isSymbolicLink())return t;r=Ow(t)}catch{return t}t=Pw(Ys(t),r)}throw new Error("its symlinks do not end anywhere")}function Vs(e){let t;try{t=Lw(e)}catch(d){return{unreadable:d.message}}let n=null,r=null;try{let d=Ew(t,"r");try{r=Mw(Iw(d,{bigint:!0})),n=Pu(d)}finally{Cw(d)}}catch(d){let u=d.code;if(u!=="ENOENT")return{unreadable:`it cannot be read (${u??"error"})`};n=null,r=null}let s="";if(n)try{s=Fw.decode(n)}catch{return{unreadable:"it is not UTF-8 text, which TOML requires"}}let o=s.startsWith("\uFEFF"),i=o?s.slice(1):s,a=i.indexOf(`
|
|
1461
1474
|
`),c=a>0&&i[a-1]==="\r"?`\r
|
|
1462
1475
|
`:`
|
|
1463
|
-
`,l=n?
|
|
1476
|
+
`,l=n?Hn(i):{doc:{}};return{path:e,target:t,raw:n,identity:r,dangling:!n&&t!==e,text:i,bom:o,eol:c,doc:"doc"in l?l.doc:null,problem:"problem"in l?l.problem:null}}function dt(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(dt).join(",")}]`:Oe(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${dt(e[t])}`).join(",")}}`:JSON.stringify(e)}function Lu(e,t,n=[]){return Oe(e)&&Oe(t)?[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Lu(e[r],t[r],[...n,r])):dt(e)===dt(t)?[]:[{path:n,a:e,b:t}]}function Wr(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
|
|
1464
1477
|
`,n);if(r<0){t.push({content:e.slice(n),eol:""});break}let s=r>n&&e[r-1]==="\r";t.push({content:e.slice(n,s?r-1:r),eol:s?`\r
|
|
1465
1478
|
`:`
|
|
1466
|
-
`}),n=r+1}return t}function
|
|
1479
|
+
`}),n=r+1}return t}function Fu(e,t){let n=e.filter((r,s)=>s!==t);return t===e.length-1&&!e[t].eol&&t>0&&(n[t-1]={...n[t-1],eol:""}),ga(n)}function Hw(e,t){if(!e.doc)return null;let n=t[t.length-1],r=new RegExp(`(?:^|[\\s.{,])${Ks(n)}[ \\t]*=`),s=dt($u(e.doc,t)),o=Wr(e.text);for(let[i,a]of o.entries()){if(!r.test(a.content))continue;let c=Hn(Fu(o,i));if("doc"in c&&dt($u(c.doc,t))!==s)return i+1}return null}function $u(e,t){let n=e;for(let r of t){if(!Oe(n))return;n=n[r]}return n}function Gw(e){let t=e.doc;if(!t)return[];let n=[],r=(s,o,i)=>{if(Oe(s))for(let a of["hooks","codex_hooks"])a in s&&n.push({key:a,value:s[a],profile:i,line:Hw(e,[...o,a])})};if(r(t.features,["features"],null),Oe(t.profiles))for(let[s,o]of Object.entries(t.profiles))Oe(o)&&r(o.features,["profiles",s,"features"],s);return n}function Jw(e){if(!e.doc)return{refused:"it does not parse as TOML"};if(!e.raw)return{text:`[features]
|
|
1467
1480
|
${_e}
|
|
1468
1481
|
`,line:2,added:`[features]
|
|
1469
1482
|
${_e}
|
|
1470
|
-
`,shape:"new_file"};let t=
|
|
1471
|
-
`)?`${a}[features]${a}${_e}${a}`:`${a}${a}[features]${a}${_e}`:`[features]${a}${_e}${a}`;o.push({text:i+c,line:
|
|
1472
|
-
`)[0]||`it exited ${c.status}`}:l?{key:l[1],on:l[2]==="true"}:{why:"it lists no hooks feature"}}catch(a){i={why:a.message}}finally{
|
|
1473
|
-
`).length-1,Ks=e=>`(?:${e}|"${e}"|'${e}')`,
|
|
1474
|
-
`,{flag:"wx",mode:r===null?384:
|
|
1483
|
+
`,shape:"new_file"};let t=dt(Dw(e.doc)),n=d=>{let u=Hn(d);return"doc"in u&&dt(u.doc)===t},r=Wr(e.text),s=(d,u,h)=>{let p=ga(r.slice(0,d+1)),f=ga(r.slice(d+1)),g=r[d].eol?u+r[d].eol:e.eol+u;return{text:p+g+f,line:d+2,added:g,shape:h}},o=[];if(Oe(e.doc.features)){for(let[d,u]of r.entries())Bw.test(u.content)&&o.push(s(d,_e,"under_header"));for(let[d,u]of r.entries())Uw.test(u.content)&&o.push(s(d,Br,"dotted"))}let i=e.text,a=e.eol,c=i?/\n\s*\n$/.test(i)?`[features]${a}${_e}${a}`:i.endsWith(`
|
|
1484
|
+
`)?`${a}[features]${a}${_e}${a}`:`${a}${a}[features]${a}${_e}`:`[features]${a}${_e}${a}`;o.push({text:i+c,line:Ww(i+c.slice(0,c.indexOf(_e)))+1,added:c,shape:"new_table"});for(let d of o)if(n(d.text))return d;let l=r.findIndex(d=>qw.test(d.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 Du(e,t){if(!e.raw)return null;if(!e.doc)return Wr(e.text).some(c=>[_e,Br].includes(c.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,r=e.text,s=e.doc,o=Wr(r),i=[];for(let c=o.length-1;c>=0;c--){let l=o[c].content.trim();if(l!==_e&&l!==Br)continue;let d=Fu(o,c),u=Hn(d);if(!("doc"in u))continue;let h=Lu(s,u.doc);h.length!==1||h[0].path.join("\0")!=="features\0codex_hooks"||h[0].a!==!0||h[0].b!==void 0||(i.push(c+1),r=d,s=u.doc,o=Wr(r))}if(!i.length)return null;let a=!1;if(n?.added.includes("[features]")&&Oe(s.features)){let c=new Set([dt(s),...Object.keys(s.features).length?[]:[dt(Object.fromEntries(Object.entries(s).filter(([h])=>h!=="features")))]]),l=e.text.lastIndexOf(n.added),d=l<0?null:e.text.slice(0,l)+e.text.slice(l+n.added.length),u=d===null?null:Hn(d);d!==null&&u&&"doc"in u&&c.has(dt(u.doc))&&(r=d,a=!0)}return{text:n?.created&&!r.trim()?null:r,lines:i.sort((c,l)=>c-l),header:a}}function Bu(e){if(e.dangling)return"it is a symlink to a file that does not exist";if(e.raw){let t;try{t=Js(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{ha(e.target,fa.W_OK)}catch{return"it is read-only"}}try{ha(Ys(e.target),fa.W_OK)}catch{return`its folder (${Ys(e.target)}) is read-only`}return null}function Yw(e){let t;try{t=ju(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 Pu(e.target).equals(e.raw)}catch{return!1}}function ma(e,t,n){let r=Bu(e);if(r)return{refused:r};let s=e.identity?e.identity.mode&4095:384,o=null;if(e.raw)try{Rw(n,{recursive:!0,mode:448}),o=qn(n,`codex-config.toml.${new Date().toISOString().replace(/[:.]/g,"-")}.${kw(3).toString("hex")}.bak`),pa(o,e.raw,{flag:"wx",mode:384})}catch(a){return{refused:`no backup of it could be kept in ${n} (${a.code??"error"})`}}let i=qn(Ys(e.target),`.${_w(e.target)}.${vw()}.canary.tmp`);try{if(t!==null){if(pa(i,Buffer.from((e.bom?"\uFEFF":"")+t,"utf8"),{flag:"wx",mode:s}),e.identity&&Js(i).gid!==e.identity.gid)try{Sw(i,-1,e.identity.gid)}catch{}xw(i,s);let a=Js(i);if(e.identity&&(a.gid!==e.identity.gid||(a.mode&4095)!==s))return Lt(i,{force:!0}),o&&Lt(o,{force:!0}),{refused:"its group or permissions could not be kept on a replacement"}}return Yw(e)?(t===null?Lt(e.target):$w(i,e.target),{backup:o}):(Lt(i,{force:!0}),o&&Lt(o,{force:!0}),{refused:"it changed while Canary was editing it",changed:!0})}catch(a){Lt(i,{force:!0}),o&&Lt(o,{force:!0});let c=a.code;return{refused:c==="EACCES"||c==="EPERM"||c==="EROFS"?`its folder cannot be written (${c})`:`it cannot be written (${c??"error"})`}}}function ya(e=process.env,t=process.platform){let n=[],r=t==="win32"?["codex.cmd","codex.exe","codex"]:["codex"];e:for(let s of(e.PATH??"").split(jw).filter(Boolean))for(let o of r){let i=qn(s,o);try{if(ha(i,fa.X_OK),Js(i).isFile()){n.push(i);break e}}catch{}}return t==="darwin"&&Aw(da)&&!n.some(s=>Vw(s,da))&&n.push(da),n}function Vw(e,t){try{return Ou(e)===Ou(t)}catch{return e===t}}function _u(e,t,n){let r=`${e}\0${t?bw("sha256").update(t).digest("hex"):"-"}`,s=Nu.get(r);if(s)return s;let o=Tw(qn(Nw(),"canary-codex-")),i;try{t&&pa(qn(o,"config.toml"),t,{mode:384});let a=process.platform==="win32"&&/\.(cmd|bat)$/i.test(e),c=ww(a?`"${e}"`:e,["features","list"],{cwd:o,env:{...process.env,CODEX_HOME:o},encoding:"utf8",timeout:n,stdio:["ignore","pipe","pipe"],windowsHide:!0,shell:a}),l=/^(hooks|codex_hooks)\s.*?\s(true|false)\s*$/m.exec(c.stdout??"");i=c.error?{why:c.error.code==="ETIMEDOUT"?"it did not answer in time":c.error.message}:c.status!==0?{why:(c.stderr??"").trim().split(`
|
|
1485
|
+
`)[0]||`it exited ${c.status}`}:l?{key:l[1],on:l[2]==="true"}:{why:"it lists no hooks feature"}}catch(a){i={why:a.message}}finally{Lt(o,{recursive:!0,force:!0})}return Nu.set(r,i),i}function zw(e,t,n){let r=e,s=n&&typeof n.profile=="string"&&Oe(n.profiles)?n.profiles[n.profile]:void 0;for(let o of[n?.features,Oe(s)?s.features:void 0])Oe(o)&&(typeof o.codex_hooks=="boolean"&&(r=o.codex_hooks),t==="hooks"&&typeof o.hooks=="boolean"&&(r=o.hooks));return r}function Uu(e,t=Kw){return({raw:n,doc:r})=>{let s={answers:[],unanswered:[]};for(let o of e){let i=_u(o,n,t);if("key"in i){s.answers.push({binary:o,...i,derived:!1});continue}let a=n?_u(o,null,t):i;"key"in a?s.answers.push({binary:o,key:a.key,on:zw(a.on,a.key,r),derived:!0}):s.unanswered.push({binary:o,why:i.why})}return s}}function wa(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:r}=t({raw:e.raw,doc:e.doc});if(n.length&&!r.length&&n.every(a=>a.on))return{kind:"on",answers:n};let s=Gw(e).filter(a=>a.profile!==null||a.key==="codex_hooks"||a.value!==!0);if(s.length)return{kind:"person",settings:s,answers:n,unanswered:r};let o=Jw(e);if("refused"in o)return{kind:"cannot",why:o.refused,answers:n,unanswered:r,...o.inline?{inline:!0}:{}};let i=Bu(e);if(i)return{kind:"cannot",why:i,answers:n,unanswered:r,edit:o};if(n.length){let a=Buffer.from((e.bom?"\uFEFF":"")+o.text,"utf8"),c=t({raw:a,doc:Hn(o.text).doc}),l=(u,h)=>h.binary===u.binary&&(u.derived||!h.derived),d=n.filter(u=>!c.answers.some(h=>l(u,h)&&h.on));if(d.length)return{kind:"cannot",answers:n,unanswered:r,edit:o,why:c.answers.some(u=>l(d[0],u))?`Codex (${d[0].binary}) still reports its hooks off with the line added, so something outside this file switches them off`:`Codex (${d[0].binary}) could not load the file with the line added`}}return{kind:"edit",edit:o,answers:n,unanswered:r}}var Mu,_e,Br,Mw,Oe,Fw,Dw,ga,Ww,Ks,Bw,Uw,qw,zs,Wu,da,Kw,Nu,qu=Z(()=>{"use strict";w();Eu();Mu="# added by canary",_e=`codex_hooks = true ${Mu}`,Br=`features.codex_hooks = true ${Mu}`,Mw=e=>({dev:e.dev,ino:e.ino,mode:Number(e.mode),uid:Number(e.uid),gid:Number(e.gid)}),Oe=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Date);Fw=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Dw=e=>({...e,features:{...Oe(e.features)?e.features:{},codex_hooks:!0}});ga=e=>e.map(t=>t.content+t.eol).join("");Ww=e=>e.split(`
|
|
1486
|
+
`).length-1,Ks=e=>`(?:${e}|"${e}"|'${e}')`,Bw=new RegExp(`^[ \\t]*\\[[ \\t]*${Ks("features")}[ \\t]*\\][ \\t]*(?:#.*)?$`),Uw=new RegExp(`^[ \\t]*${Ks("features")}[ \\t]*\\.`),qw=new RegExp(`^[ \\t]*${Ks("features")}[ \\t]*=[ \\t]*\\{`);zs=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}")`:""}`;Wu=e=>qn(e,"backups");da="/Applications/ChatGPT.app/Contents/Resources/codex";Kw=3e3,Nu=new Map});import{accessSync as Xw,constants as Zw,existsSync as Hr,lstatSync as Qw,readFileSync as Xs,readlinkSync as eb,renameSync as tb,rmSync as Hu,statSync as zu,writeFileSync as nb}from"node:fs";import{randomUUID as rb}from"node:crypto";import{homedir as va}from"node:os";import{delimiter as sb,dirname as ba,join as mt,resolve as ob}from"node:path";function Qs(e,t=process.env,n=process.platform){let r=n==="win32"?[e,...(t.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(s=>e+s.toLowerCase())]:[e];for(let s of(t.PATH??"").split(sb).filter(Boolean))for(let o of r)try{if(Xw(mt(s,o),Zw.X_OK),zu(mt(s,o)).isFile())return!0}catch{}return!1}function ib(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!Qw(t).isSymbolicLink())return t;r=eb(t)}catch{return t}t=ob(ba(t),r)}throw new ht("its symlinks do not end anywhere")}function Gn(e,t){for(let n=0;n<3;n++){let r;try{r=Xs(e,"utf8")}catch(c){if(c.code!=="ENOENT")return{result:"refused",detail:"the file cannot be read"};r=null}let s={};if(r!==null&&r.trim())try{s=JSON.parse(r)}catch{return{result:"refused",detail:"the file is not valid JSON"}}if(!yt(s))return{result:"refused",detail:"the file does not hold a JSON object"};try{if(!t(s))return{result:"unchanged"}}catch(c){if(c instanceof ht)return{result:"refused",detail:c.message};throw c}let o=r?/^([ \t]+)"/m.exec(r)?.[1]??" ":" ",i;try{i=ib(e)}catch(c){return{result:"refused",detail:c.message}}if(i!==e&&!Hr(ba(i)))return{result:"refused",detail:"it is a symlink into a folder that does not exist"};let a=mt(ba(i),`.${rb()}.canary.tmp`);try{nb(a,JSON.stringify(s,null,o)+`
|
|
1487
|
+
`,{flag:"wx",mode:r===null?384:zu(i).mode&511});let c;try{c=Xs(e,"utf8")}catch{c=null}if(c!==r){Hu(a,{force:!0});continue}return tb(a,i),{result:"written"}}catch(c){return Hu(a,{force:!0}),{result:"refused",detail:`the file cannot be written (${c.code??"error"})`}}}return{result:"refused",detail:"the file kept changing while it was being edited"}}function cb(e,t,n){for(let r of e){if(!yt(r))throw new ht(`its \`hooks.${t}\` list holds an entry that is not an object`);if(n&&r[n]!==void 0&&!(Array.isArray(r[n])&&r[n].every(yt)))throw new ht(`its \`hooks.${t}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Ft(e,t,n,r="hooks"){if(e.hooks===void 0){if(!n)return null;e.hooks={}}if(!yt(e.hooks))throw new ht("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 ht(`its \`hooks.${t}\` entry is not a list`);return cb(e.hooks[t],t,r),e.hooks[t]}function Xu(e,t){yt(e.hooks)&&(Array.isArray(e.hooks[t])&&!e.hooks[t].length&&delete e.hooks[t],Object.keys(e.hooks).length||delete e.hooks)}function Zu(e){let t;try{t=JSON.parse(Xs(e,"utf8"))}catch(n){return n.code==="ENOENT"?{state:"missing"}:{state:"unreadable",detail:"the file cannot be read as JSON"}}return yt(t)?{doc:t}:{state:"unreadable",detail:"the file does not hold a JSON object"}}function Qu(e){let t=ab(e.harness),n=xa(e.harness),r=()=>({matcher:e.matcher,hooks:[{type:"command",command:t,timeout:Zs}]}),s=c=>yt(c)&&Array.isArray(c.hooks)&&c.hooks.some(n),o=c=>{let l=c.filter(s);return l.length===1&&JSON.stringify(l[0])===JSON.stringify(r())},i=c=>{let l=Ft(c,"PreToolUse",!1);if(!l)return!1;let d=!1;for(let u=l.length-1;u>=0;u--){let h=l[u];if(!yt(h)||!Array.isArray(h.hooks))continue;let p=h.hooks.filter(f=>!n(f));p.length!==h.hooks.length&&(d=!0,p.length?h.hooks=p:l.splice(u,1))}return d&&Xu(c,"PreToolUse"),d},a={harness:e.harness,file:e.file,summary:`a PreToolUse hook that runs \`${t}\` before shell and MCP tool calls (${Zs} s limit)`,snippet:JSON.stringify({hooks:{PreToolUse:[r()]}},null,2)};return{detected:()=>Hr(e.dir),plan:()=>[a],install:()=>[{...a,...Gn(e.file,c=>o(Ft(c,"PreToolUse",!0))?!1:(i(c),Ft(c,"PreToolUse",!0).push(r()),!0))}],uninstall:()=>{if(!Hr(e.file))return[{...a,result:"unchanged"}];let c=Gn(e.file,i);return[{...a,...c.result==="written"?{result:"removed"}:c}]},status:()=>{let c=Zu(e.file);if(!("doc"in c))return[{harness:e.harness,file:e.file,...c}];let l;try{l=Ft(c.doc,"PreToolUse",!1)}catch(d){return[{harness:e.harness,file:e.file,state:"unreadable",detail:d.message}]}return l?.some(s)?e.disabledKey&&c.doc[e.disabledKey]===!0?[{harness:e.harness,file:e.file,state:"disabled",detail:`\`${e.disabledKey}\` is set, so no hooks run`}]:o(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 lb(e){let t=mt(e,"hooks.json"),n=xa("cursor"),r=()=>({command:"canary hook cursor",timeout:Zs}),s=a=>Ur.every(c=>{let l=(Ft(a,c,!1,null)??[]).filter(n);return l.length===1&&JSON.stringify(l[0])===JSON.stringify(r())}),o=a=>{let c=!1;for(let l of Ur){let d=Ft(a,l,!1,null);if(!d)continue;let u=d.filter(h=>!n(h));u.length!==d.length&&(c=!0,a.hooks[l]=u,Xu(a,l))}return c},i={harness:"cursor",file:t,summary:`a command that runs \`canary hook cursor\` before shell commands and MCP tool calls (${Zs} s limit)`,snippet:JSON.stringify({version:1,hooks:Object.fromEntries(Ur.map(a=>[a,[r()]]))},null,2)};return{detected:()=>Hr(e),plan:()=>[i],install:()=>[{...i,...Gn(t,a=>{if(a.version!==void 0&&a.version!==1)throw new ht(`it is version ${JSON.stringify(a.version)} of Cursor's hooks file, which this CLI does not know`);if(s(a))return!1;o(a),a.version===void 0&&(a.version=1);for(let c of Ur)Ft(a,c,!0,null).push(r());return!0})}],uninstall:()=>{if(!Hr(t))return[{...i,result:"unchanged"}];let a=Gn(t,o);return[{...i,...a.result==="written"?{result:"removed"}:a}]},status:()=>{let a=Zu(t);if(!("doc"in a))return[{harness:"cursor",file:t,...a}];try{return Ur.some(c=>(Ft(a.doc,c,!1,null)??[]).some(n))?[s(a.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(c){return[{harness:"cursor",file:t,state:"unreadable",detail:c.message}]}}}}function db(e=process.env){let t=e.CLAUDE_CONFIG_DIR||mt(va(),".claude");return{id:"claude",label:"Claude Code",byDefault:!0,...Qu({harness:"claude",dir:t,file:mt(t,"settings.json"),matcher:ub,disabledKey:"disableAllHooks"})}}function hb(e=process.env,t=process.platform){let[n]=ya(e,t);return n===void 0?null:/[\s"']/.test(n)?`"${n}"`:n}function pb(e,t,n){if("unreadable"in e||!e.doc)return null;let r=e.doc.hooks,s=Oe(r)&&Oe(r.state)?r.state[`${t}:pre_tool_use:${n}:0`]:void 0;return Oe(s)&&typeof s.trusted_hash=="string"}function Ku(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(zs).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(zs).join("; ")}); the check runs only where they are on`:e.answers.some(n=>!n.on)?`${ed(e.answers)} reports its hooks off although its config.toml switches them on (${e.settings.map(zs).join("; ")}), so a setting outside that file switches them off`:null}function yb(e=process.env,t={}){let n=e.CODEX_HOME||mt(va(),".codex"),r=mt(n,"hooks.json"),s=Qu({harness:"codex",dir:n,file:r,matcher:".*"}),o=mt(n,"config.toml"),i=fb(hb(e)),a=t.ask??Uu(ya(e)),c=xa("codex"),l=()=>Wu(K()),d=()=>{try{return JSON.parse(Xs(r,"utf8")).hooks.PreToolUse.findIndex(x=>yt(x)&&Array.isArray(x.hooks)&&x.hooks.some(c))}catch{return-1}},u=()=>{let S=Vs(o);return{read:S,verdict:wa(S,a)}},h=()=>{try{return V().hooks?.codex??null}catch{return null}},p=S=>{try{Ne(x=>{let{codex:v,...I}=x.hooks??{};return{...x,hooks:S?{...I,codex:S}:I}})}catch{}},f=(S,x)=>({harness:"codex",file:o,summary:`the line \`${pn(S)}\` ${gb(S)}${x?`, because ${qr(x)}`:""}`,snippet:S.shape==="new_table"||S.shape==="new_file"?`[features]
|
|
1475
1488
|
${_e}`:pn(S)}),g={harness:"codex",file:o,summary:`the line \`${_e}\` under \`[features]\``,snippet:`[features]
|
|
1476
|
-
${_e}`},m={harness:"codex",file:o,summary:"`codex_hooks = true` inside the inline `features = { \u2026 }` table",snippet:"features = { \u2026, codex_hooks = true }"},C=(S,x)=>x.kind==="cannot"?{...x.edit?f(x.edit):x.inline?m:g,result:"refused",detail:`${x.why}; ${
|
|
1489
|
+
${_e}`},m={harness:"codex",file:o,summary:"`codex_hooks = true` inside the inline `features = { \u2026 }` table",snippet:"features = { \u2026, codex_hooks = true }"},C=(S,x)=>x.kind==="cannot"?{...x.edit?f(x.edit):x.inline?m:g,result:"refused",detail:`${x.why}; ${qr(x)}`}:x.kind==="broken"?{...g,result:"refused",detail:Vu(S)}:x.kind==="unreadable"?{...g,result:"refused",detail:x.why}:null,A=()=>{for(let S=0;S<3;S++){let{read:x,verdict:v}=u();if(v.kind!=="edit")return C(x,v);let I=v.edit,$=ma(x,I.text,l());if("backup"in $)return p({file:x.target,added:I.added,line:pn(I),at:new Date().toISOString(),...I.shape==="new_file"?{created:!0}:{},...$.backup?{backup:$.backup}:{}}),{...f(I,v),result:"written",detail:`line ${I.line} now reads \`${pn(I)}\`, because ${qr(v)}`,edit:{line:I.line,text:pn(I),backup:$.backup,created:I.shape==="new_file"}};if(!$.changed)return{...f(I),result:"refused",detail:`${$.refused}; ${qr(v)}`}}return{...g,result:"refused",detail:"it kept changing while Canary was editing it"}},b=()=>{let S=h(),x=S?.line??_e;for(let v=0;v<3;v++){let I=Vs(o);if("unreadable"in I)return S?{...g,result:"refused",detail:`${I.unreadable}: if it still holds \`${x}\`, take that line out yourself`}:null;let $=Du(I,S);if(!$)return S&&p(null),null;if("refused"in $)return{...g,result:"refused",detail:`${$.refused}: take \`${x}\` out of it yourself`};let y=ma(I,$.text,l());if("backup"in y){p(null);let k=$.text===null,N=k?"deleted it: Canary had created it, and nothing else was in it":`took out line${$.lines.length===1?"":"s"} ${$.lines.join(", ")} (\`${x}\`${$.header?" and the `[features]` header Canary added with it":""})`;return{...g,result:"removed",detail:N,removed:{lines:$.lines,header:$.header,deleted:k,backup:y.backup}}}if(!y.changed)return{...g,result:"refused",detail:`${y.refused}: take \`${x}\` out of it yourself`}}return{...g,result:"refused",detail:"it kept changing while Canary was editing it"}};return{id:"codex",label:"Codex",byDefault:!0,afterInstall:Gu(i),detected:s.detected,plan:()=>{let{verdict:S}=u();return S.kind==="edit"?[...s.plan(),f(S.edit,S)]:s.plan()},install:()=>{let{verdict:S}=u(),[x]=s.install();if(x.result==="refused")return[x];let v=S.kind==="person"?Ku(S):null,I=A();return[v?{...x,detail:x.detail?`${x.detail}; ${v}`:v}:x,...I?[I]:[]]},uninstall:()=>{let[S]=s.uninstall();if(S.result==="refused")return[S];let x=b();return x?[S,x]:[S]},status:()=>{let[S]=s.status();if(S.state!=="registered")return[S];let x=Vs(o),v="unreadable"in x?null:wa(x,a),I=v?v.kind==="broken"?Vu(x):v.kind==="person"?Ku(v):v.kind==="edit"&&Ju(v)?`Codex's hooks feature is off: ${qr(v)} (\`${pn(v.edit)}\` ${ka(v.edit)} in its config.toml); \`canary hooks install\` adds it`:v.kind==="cannot"&&Ju(v)?`Codex's hooks feature is off, and Canary cannot switch it on: ${v.why}${Yu(v)}`:null:null;if(I)return[{...S,state:"disabled",detail:I}];let $=v?.kind==="edit"?`Codex before 0.124 also runs no hooks until \`${pn(v.edit)}\` is ${ka(v.edit)} in its config.toml, and it is not there: \`canary hooks install\` adds it.`:v?.kind==="cannot"?`Codex before 0.124 also runs no hooks until \`codex_hooks = true\` is in its config.toml, and Canary cannot add it: ${v.why}${Yu(v)}.`:null,y=d();if(y<0)return[$?{...S,detail:$}:S];let k=pb(x,r,y);if(k===!0)return[$?{...S,detail:$}:S];let N=[k===null?"Codex's config.toml could not be read, so whether the hook is trusted is unknown.":null,Gu(i),$].filter(Boolean).join(" ");return[{...S,state:"untrusted",detail:N,pending:i}]}}}function wb(e=process.env){let t=e.CURSOR_CONFIG_DIR||mt(va(),".cursor");return{id:"cursor",label:"Cursor",byDefault:!0,...lb(t)}}var yt,ht,Zs,ab,xa,Ur,ub,fb,Gu,pn,ed,qr,Ju,gb,mb,ka,Yu,Vu,Gr,Sa=Z(()=>{"use strict";w();qu();ee();yt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ht=class extends Error{};Zs=10,ab=(e,t=process.platform)=>t==="win32"?`canary hook ${e}`:`command -v canary >/dev/null 2>&1 || exit 0; canary hook ${e}`,xa=e=>t=>yt(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);Ur=["beforeShellExecution","beforeMCPExecution"];ub="^(Bash|PowerShell|Monitor|mcp__.*)$";fb=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.'}),Gu=e=>`${e.why} Run \`${e.command}\` in a terminal. ${e.after}`;pn=e=>e.shape==="dotted"?Br:_e,ed=e=>{let t=e.find(n=>!n.on)??e[0];return t?`your Codex (${t.binary})`:"Codex"},qr=e=>e.answers.some(t=>!t.on)?`${ed(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",Ju=e=>e.answers.some(t=>!t.on),gb=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",mb=e=>e.shape==="dotted"?"features.codex_hooks = true":"codex_hooks = true",ka=e=>e.shape==="dotted"?"beside the other `features.` keys":e.shape==="under_header"?"under `[features]`":"in a `[features]` table",Yu=e=>e.edit?`; add \`${mb(e.edit)}\` ${ka(e.edit)} yourself`:"",Vu=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`;Gr=(e=process.env)=>[db(e),yb(e),wb(e)]});var rd={};_i(rd,{installAgentPlugin:()=>Ta});import{existsSync as Ia,mkdirSync as bb,readFileSync as kb,renameSync as td,rmSync as Ca,writeFileSync as vb}from"node:fs";import{homedir as xb}from"node:os";import{dirname as Sb,join as Jn}from"node:path";function Ab(e,t){return Object.entries(t).every(([n,r])=>{try{return kb(Jn(e,n),"utf8")===r}catch{return!1}})}function Ib(e,t){let n=`${e}.next`,r=`${e}.old`;Ca(n,{recursive:!0,force:!0});for(let[s,o]of Object.entries(t))bb(Sb(Jn(n,s)),{recursive:!0}),vb(Jn(n,s),o);Ca(r,{recursive:!0,force:!0}),Ia(e)&&td(e,r),td(n,e),Ca(r,{recursive:!0,force:!0})}function Rb(e,t){for(let i of["extraKnownMarketplaces","enabledPlugins"])if(e[i]===void 0&&(e[i]={}),!Cb(e[i]))throw new ht(`its \`${i}\` entry is not an object`);let n=e.extraKnownMarketplaces,r=e.enabledPlugins,s={source:{source:"directory",path:t}},o=!1;return JSON.stringify(n[Ra])!==JSON.stringify(s)&&(n[Ra]=s,o=!0),r[nd]===void 0&&(r[nd]=!0,o=!0),o}function Ta(e=process.env){if(!Aa||V().agentSkills===!1)return{result:"skipped"};let t=e.CLAUDE_CONFIG_DIR||Jn(xb(),".claude");if(!Ia(t))return{result:"skipped"};let n=Jn(K(),"plugins"),r=Jn(t,"settings.json");try{let s=!Ia(n),o=!Ab(n,Aa);o&&Ib(n,Aa);let i=Gn(r,a=>Rb(a,n));return i.result==="refused"?{result:"refused",file:r,detail:i.detail}:s?{result:"added",file:r}:{result:o||i.result==="written"?"updated":"current",file:r}}catch(s){return{result:"refused",file:n,detail:`the folder couldn't be written (${s.code??"error"})`}}}var Aa,Ra,nd,Cb,Ea=Z(()=>{"use strict";w();ee();Sa();Aa=typeof O=="object"?O:null,Ra="runcanary",nd=`canary@${Ra}`,Cb=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});var Oa,sd=Z(()=>{Oa=`---
|
|
1477
1490
|
name: canary
|
|
1478
1491
|
description: >-
|
|
1479
1492
|
Use whenever you finish a code change and are about to report it done, or whenever a change
|
|
@@ -1555,7 +1568,12 @@ the one above. Each time:
|
|
|
1555
1568
|
new checks.
|
|
1556
1569
|
- \`answer\`: a check asks \`question\`. Answer facts about this project yourself by running
|
|
1557
1570
|
\`command\` with your answer in place of \`<answer>\`; access and approvals come only from the
|
|
1558
|
-
user, so ask them first.
|
|
1571
|
+
user, so ask them first. When \`command\` starts with \`canary answer\`, the request asks which
|
|
1572
|
+
part of the code to read instead: if what you know from this chat settles it, run \`command\`
|
|
1573
|
+
with your answer. Otherwise ask the user \`question\` with your tool for asking a question with
|
|
1574
|
+
options (in Claude Code, AskUserQuestion; header "Canary"), offering \`options\` in their order,
|
|
1575
|
+
word for word (the first is Canary's pick), and run \`command\` with their words and
|
|
1576
|
+
\`--from person\` added. Answer within 5 minutes: after that, Canary reads its pick.
|
|
1559
1577
|
- \`stop_verifier\`: stop the verifier for \`batchId\`, then run \`then\` when it has one. Start a
|
|
1560
1578
|
fresh one only when \`restart\` is \`when_user_agrees\`, the user says to go ahead, and that batch
|
|
1561
1579
|
still has checks left (the \`local-jobs\` skill says how to see them).
|
|
@@ -1584,7 +1602,8 @@ the one above. Each time:
|
|
|
1584
1602
|
|
|
1585
1603
|
When \`"ended"\` is true, \`result\` is Canary's result, and \`result.score.answer\` says whether the
|
|
1586
1604
|
change is safe to push: \`yes\` (nothing must be fixed and no check is left) or \`not_yet\` (a must-fix
|
|
1587
|
-
is open, or checks are left to finish).
|
|
1605
|
+
is open, or checks are left to finish). When the request read an area of the code (its report
|
|
1606
|
+
starts "Canary report on"), its score is that area's health: say nothing about pushing from it. A result can come while some checks still run: they finish
|
|
1588
1607
|
on their own and update it. Until they end, keep the listener the \`local-jobs\` skill describes
|
|
1589
1608
|
running, and start it if it isn't. When one of them passes, or its verifier ends, say nothing. When
|
|
1590
1609
|
one fails, it is another must-fix, found on the code as it was when the user asked: if you are
|
|
@@ -1637,34 +1656,34 @@ If \`canary\` is not installed: \`npm i -g @runcanary/cli\`, then start at step
|
|
|
1637
1656
|
"Getting started" section covers logging in.
|
|
1638
1657
|
Output that begins with \`OFFLINE COPY\` could not be refreshed and may be outdated \u2014 say so if
|
|
1639
1658
|
you act on it.
|
|
1640
|
-
`});var
|
|
1641
|
-
`,{flag:"wx",mode:384}),
|
|
1642
|
-
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${
|
|
1643
|
-
`);if(!n)return{};let o={worktreeId:
|
|
1644
|
-
`).filter(Boolean).sort()[0]:void 0;a&&
|
|
1645
|
-
`).map(s=>s.trim()).filter(s=>s.length>0);if(r[r.length-1]==="*")return}catch{}try{
|
|
1659
|
+
`});var id={};_i(id,{installAgentSkill:()=>Jr});import{existsSync as Na,lstatSync as Eb,mkdirSync as Ob,readFileSync as od,rmSync as $b,rmdirSync as Nb,writeFileSync as _b}from"node:fs";import{homedir as $a}from"node:os";import{join as gn}from"node:path";function Mb(e){let t=gn(e,"skills",Pb),n=gn(t,"SKILL.md");if(eo(t)||eo(n)||!Na(n))return;let r;try{r=od(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{$b(n,{force:!1})}catch{return}try{Nb(t)}catch{}}}function eo(e){try{return Eb(e).isSymbolicLink()}catch{return!1}}function Lb(){return[gn($a(),".claude"),gn($a(),".agents"),gn($a(),".codex")].filter(e=>Na(e))}function Jr(){let e={installed:[],refreshed:[],current:[],skipped:[]};if(V().agentSkills===!1)return e;for(let t of Lb()){Mb(t);let n=gn(t,"skills",jb),r=gn(n,"SKILL.md");try{if(eo(n)||eo(r)){e.skipped.push(r);continue}let s=Na(r)?od(r,"utf8"):null;if(s===Oa){e.current.push(r);continue}Ob(n,{recursive:!0}),_b(r,Oa),(s===null?e.installed:e.refreshed).push(r)}catch{}}return e}var jb,Pb,to=Z(()=>{"use strict";w();ee();sd();jb="canary",Pb="canary-setup"});import{createHash as Fb,randomUUID as Db}from"node:crypto";import{mkdirSync as Wb,readFileSync as Bb,renameSync as Ub,rmSync as ad,writeFileSync as qb}from"node:fs";import{dirname as _a,join as Hb,resolve as cd}from"node:path";function dd(e,t,n=Date.now()){try{let r=ud(e),s=`${r}.${Db()}.tmp`;Wb(_a(r),{recursive:!0,mode:448});try{qb(s,JSON.stringify({version:1,chat:t,at:n})+`
|
|
1660
|
+
`,{flag:"wx",mode:384}),Ub(s,r)}catch(o){throw ad(s,{force:!0}),o}}catch{}}function hd(e,t=Date.now()){for(let n=cd(e);;n=_a(n)){let r=ud(n),s=null;try{s=JSON.parse(Bb(r,"utf8")),ad(r,{force:!0})}catch{}if(s&&s.version===1&&typeof s.chat=="string"&&s.chat&&typeof s.at=="number"&&t-s.at>=0&&t-s.at<Gb)return s.chat;if(_a(n)===n)return null}}var Gb,Jb,ld,ud,ja=Z(()=>{"use strict";w();ee();Gb=1e4,Jb=/(?:^|[;&|(]|\$\()\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:[^\s;&|()]*\/)?canary(?=[\s;&|)]|$)/m,ld=e=>e.some(t=>Jb.test(t)),ud=e=>Hb(K(),"hold",`chat-${Fb("sha256").update(cd(e)).digest("hex").slice(0,32)}.json`)});import{mkdirSync as Yb,readFileSync as Vb,writeFileSync as Kb}from"node:fs";import{homedir as zb}from"node:os";import{dirname as Xb,join as fd}from"node:path";function gd(){try{return JSON.parse(Vb(Pa(),"utf8"))}catch{return{}}}function Qb(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let s=0;s<3;s+=1){let o=(n[s]||0)-(r[s]||0);if(o!==0)return o>0}return!1}function md(){if(wt==="0.0.0-dev")return;let{latest:e}=gd();e&&Qb(e,wt)&&console.error(`A newer Canary CLI is available (${wt} -> ${e}): npm install -g ${pd}`)}function Yn(){if(wt==="0.0.0-dev")return;let e=gd();e.checkedAt&&Date.now()-e.checkedAt<Zb||(async()=>{let t=n=>{try{Yb(Xb(Pa()),{recursive:!0}),Kb(Pa(),JSON.stringify({checkedAt:Date.now(),latest:n??e.latest})+`
|
|
1661
|
+
`)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${pd}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return t();let{version:r}=await n.json();t(r||void 0)}catch{t()}})()}var wt,pd,Zb,Pa,mn=Z(()=>{"use strict";w();wt="0.1.18",pd="@runcanary/cli",Zb=1440*60*1e3,Pa=()=>fd(process.env.CANARY_HOME||fd(zb(),".canary"),"update-check.json")});import{createHash as e0}from"node:crypto";import{execFileSync as t0,spawn as n0}from"node:child_process";function Ke(e){Dt={...Dt,...e},Yr=null}function La(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 yn(e=process.env,t=process.cwd()){let n=e.CLAUDE_CODE_SESSION_ID?.trim(),r=e.CODEX_THREAD_ID?.trim();return n&&!r?n:(Ma===void 0&&(Ma=hd(t)),Ma??r??n??null)}function r0(e,t){return e0("sha256").update(`${t}\0${e}`).digest("hex").slice(0,24)}function no(){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 yd(e,t){try{let n=no();return t0("git",e,{cwd:t,env:n,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function s0(e,t){let[n,r,s]=(yd(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],e)??"").split(`
|
|
1662
|
+
`);if(!n)return{};let o={worktreeId:r0(n,t)};if(s!=="true"){let i=fu(o.worktreeId);i&&yd(["cat-file","-e",`${i}^{commit}`],n)!==null?o.repoFingerprint=i:o0(n,o.worktreeId)}return o.branch=r&&r!=="HEAD"?r:"HEAD",o}function o0(e,t){wd.has(t)||wd.set(t,new Promise(n=>{try{let r=no(),s=n0("git",["rev-list","--max-parents=0","HEAD"],{cwd:e,env:r,stdio:["ignore","pipe","ignore"],timeout:6e4}),o="";s.stdout.on("data",i=>{o+=i.toString("utf8")}),s.on("error",()=>n()),s.on("close",i=>{let a=i===0?o.trim().split(`
|
|
1663
|
+
`).filter(Boolean).sort()[0]:void 0;a&&pu(t,a),n()}),s.unref(),s.stdout.unref?.()}catch{n()}}))}function i0(){if(Yr)return Yr;let e=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",t=La(),n=Dt.harness??t.harness,r=t.harness===n?t.chatId:void 0,s="",o={};try{s=hu(),o=s0(Dt.cwd??process.cwd(),s)}catch{}return Yr={cliVersion:wt,command:e,installId:s,...o,harness:n,...r?{chatId:r}:{},...Dt.agent!==void 0?{agent:Dt.agent}:{},...Dt.mode?{mode:Dt.mode}:{}},Yr}function Wt(){let e=i0(),t=r=>r.replace(/[^\x20-\x7e]/g,"?").slice(0,200),n={[pe.cli]:e.cliVersion,[pe.harness]:e.harness};return e.installId&&(n[pe.install]=e.installId),e.command&&(n[pe.command]=t(e.command)),e.worktreeId&&(n[pe.worktree]=e.worktreeId),e.repoFingerprint&&(n[pe.repo]=e.repoFingerprint),e.branch&&(n[pe.branch]=t(e.branch)),e.chatId&&(n[pe.chat]=t(e.chatId)),e.agent!==void 0&&(n[pe.agent]=e.agent?"1":"0"),e.mode&&(n[pe.mode]=e.mode),n}var pe,Dt,Yr,Ma,wd,nt=Z(()=>{"use strict";w();ee();ja();mn();pe={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"},Dt={},Yr=null;wd=new Map});async function W(e,t={}){let n=(t.baseUrl||ue()).replace(/\/+$/,""),r={...Wt(),...t.headers};t.token&&(r.authorization=`Bearer ${t.token}`),t.body!==void 0&&(r["content-type"]="application/json");let s;try{s=await fetch(n+e,{method:t.method??"GET",headers:r,body:t.body!==void 0?JSON.stringify(t.body):void 0,signal:t.signal})}catch(o){throw new L(0,`could not reach ${n} (${o instanceof Error?o.message:String(o)})`)}if(!s.ok){let o=s.statusText,i,a,c;try{let l=await s.json();o=l.error||l.message||o,typeof l.fix=="string"&&l.fix&&(i=l.fix),typeof l.runId=="string"&&l.runId&&(a=l.runId),typeof l.code=="string"&&l.code&&(c=l.code)}catch{}throw new L(s.status,o,i,a,c)}return s.status===204?null:await s.json()}var L,be,fe=Z(()=>{"use strict";w();ee();nt();L=class extends Error{constructor(n,r,s,o,i){super(r);this.status=n;this.fix=s;this.runId=o;this.code=i;this.name="ApiError"}},be=e=>e instanceof L&&(e.status===0||e.status===408||e.status===429||e.status===502||e.status===503||e.status===504)});function bd(e){return Ne(t=>({...t,gate:{...t.gate,mode:e}}))}var wn,ro=Z(()=>{"use strict";w();ee();wn=()=>V().gate?.mode==="off"?"off":"on"});var uE,so,a0,dE,kd=Z(()=>{"use strict";w();uE=Object.freeze({name:"Canary Verify",email:"verify@runcanary.ai",date:"@0 +0000",message:e=>`canary verify: tree ${e}`}),so=e=>`tree:${e.slice(0,12)}`,a0=[["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"]],dE=a0.flatMap(([e,t])=>["-c",`${e}=${t}`])});import{createHash as c0}from"node:crypto";import{existsSync as l0,mkdirSync as Fa,readFileSync as Vn,writeFileSync as oo}from"node:fs";import{join as Et}from"node:path";function Kn(e){return Et(e,".canary")}function Sd(e){let t=e.trim();if(!t)return null;if(!t.includes("://")){let n=t.match(/^[^@]+@([^:]+):(.+)$/);if(n){let r=n[2].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);return r.length>=2?{host:n[1],owner:r[0],name:r.slice(1).join("/")}:null}}try{let n=new URL(t),r=n.pathname.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean);if(r.length>=2)return{host:n.host,owner:r[0],name:r.slice(1).join("/")}}catch{}return null}function Vr(e){let t=Kn(e),n=Et(t,".gitignore");try{let r=Vn(n,"utf8").split(`
|
|
1664
|
+
`).map(s=>s.trim()).filter(s=>s.length>0);if(r[r.length-1]==="*")return}catch{}try{Fa(t,{recursive:!0});let r="";try{r=Vn(n,"utf8"),r&&!r.endsWith(`
|
|
1646
1665
|
`)&&(r+=`
|
|
1647
1666
|
`)}catch{}oo(n,`${r}*
|
|
1648
|
-
`)}catch{}}function
|
|
1649
|
-
`),
|
|
1650
|
-
`}catch{}oo(Et(r,"run.json"),o),n.push(".canary/run.json")}let s=Object.entries(t.envOverrides??{});return s.length>0&&(
|
|
1651
|
-
`,{flag:"wx",mode:384});try{
|
|
1652
|
-
`,{flag:"wx",mode:384}),
|
|
1653
|
-
`,{flag:"wx",mode:384}),
|
|
1667
|
+
`)}catch{}}function Bt(e){let t=Kn(e),n;try{n=Vn(Et(t,"setup.sh"),"utf8")}catch{throw new ze("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 ze("recipe_invalid",".canary/setup.sh is empty.");let r;try{r=JSON.parse(Vn(Et(t,"run.json"),"utf8"))}catch(a){throw new ze("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let s=[],o={},i=Et(t,"env.json");if(l0(i)){let a;try{a=JSON.parse(Vn(i,"utf8"))}catch(l){throw new ze("recipe_invalid",`Cannot read .canary/env.json: ${l instanceof Error?l.message:String(l)}`)}if(a===null||typeof a!="object"||Array.isArray(a))throw new ze("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let c=a;s=Ad(c.manifest),o=Id(c.values),d0(s)}return{setupSh:n,runJson:r,envManifest:s,envValues:o}}function bn(e){return c0("sha256").update(JSON.stringify([e.setupSh,e.runJson,e.envManifest,e.envValues])).digest("hex")}function Da(e,t){let n=e.filter(r=>r.neededAt==="boot").map(r=>r.name).filter(r=>!Object.prototype.hasOwnProperty.call(t,r)||t[r]==="");return{missing:[...new Set(n)]}}function Ad(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.name=="string"):[]}function d0(e){for(let t of e){if(!vd.has(String(t.class)))throw new ze("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has unknown class "${String(t.class)}"`,`use one of: ${[...vd].join(", ")}`);if(!u0.has(String(t.neededAt)))throw new ze("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has invalid neededAt "${String(t.neededAt)}"`,'use "boot" or "runtime"')}}function Id(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function h0(e){try{let t=JSON.parse(Vn(Et(Kn(e),"env.json"),"utf8"));return{manifest:Ad(t.manifest),values:Id(t.values)}}catch{return{manifest:[],values:{}}}}function f0(e,t){Fa(Kn(e),{recursive:!0}),oo(Et(Kn(e),"env.json"),JSON.stringify(t,null,2)+`
|
|
1668
|
+
`),Vr(e)}function Wa(e,t){if(t.length===0)return;let n=h0(e),r=new Map(n.manifest.map(s=>[s.name,s]));for(let s of t){n.values[s.name]=s.value;let o=r.get(s.name);if(o)s.class&&xd.has(s.class)&&!xd.has(o.class??"")&&(o.class=s.class,o.neededAt="boot");else{let i={name:s.name,class:s.class??"config",neededAt:"boot",why:s.why??"added during cloud verification"};r.set(s.name,i),n.manifest.push(i)}}f0(e,n)}function Rd(e,t){let n=[],r=Kn(e);if(Fa(r,{recursive:!0}),typeof t.setupSh=="string"&&t.setupSh.trim()&&(oo(Et(r,"setup.sh"),t.setupSh),n.push(".canary/setup.sh")),typeof t.runJson=="string"&&t.runJson.trim()){let o=t.runJson;try{o=JSON.stringify(JSON.parse(t.runJson),null,2)+`
|
|
1669
|
+
`}catch{}oo(Et(r,"run.json"),o),n.push(".canary/run.json")}let s=Object.entries(t.envOverrides??{});return s.length>0&&(Wa(e,s.map(([o,i])=>({name:o,value:i,why:"authored by the cloud verifier while fixing the boot"}))),n.push(".canary/env.json")),Vr(e),n}var ze,Cd,vd,u0,xd,Ba=Z(()=>{"use strict";w();ze=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="RecipeError"}};Cd=new Set(["github.com","ssh.github.com"]);vd=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),u0=new Set(["boot","runtime"]);xd=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"])});import{execFileSync as p0}from"node:child_process";import{createHash as Od,randomUUID as ao}from"node:crypto";import{linkSync as g0,lstatSync as $d,mkdirSync as co,readdirSync as m0,readFileSync as qa,realpathSync as io,renameSync as Nd,rmSync as lo,writeFileSync as Ha}from"node:fs";import{basename as Ga,dirname as _d,isAbsolute as y0,join as Xe,relative as w0,resolve as Ja,sep as b0}from"node:path";function k0(e){let t=Sd(e);if(!(!t||!Cd.has(t.host.toLowerCase().replace(/:\d+$/,"")))&&!(!Td.test(t.owner)||!Td.test(t.name)))return`${t.owner}/${t.name}`}function Xn(e=process.cwd()){let t={...Object.fromEntries(Object.entries(process.env).filter(([a])=>!a.startsWith("GIT_")||["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM"].includes(a))),GIT_OPTIONAL_LOCKS:"0",GIT_TRACE2:"0",GIT_TRACE2_EVENT:"0",GIT_TRACE2_PERF:"0"},n=a=>p0("git",a,{cwd:e,env:t,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").replace(/\r?\n$/,""),r,s;try{r=io(n(["rev-parse","--show-toplevel"])),s=io(Ja(io(e),n(["rev-parse","--git-common-dir"])))}catch{throw new re("not_a_git_repository","Run this command inside the Git repository you want Canary to use.")}let o;try{o=k0(n(["remote","get-url","origin"]))}catch{}if(o)return{root:r,commonDirectory:s,name:o,githubFullName:o};let i=Ga(r).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:r,commonDirectory:s,name:i}}function v0(e){let t;try{t=new URL(e)}catch{throw new re("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 re("invalid_api_url","The Canary API URL must be HTTP(S) without credentials, a query, or a fragment.");return t.href.replace(/\/+$/,"")}function uo(e){try{return io(e)}catch(t){if(t.code!=="ENOENT")throw t;if($d(e,{throwIfNoEntry:!1})?.isSymbolicLink())throw new re("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=_d(e);if(n===e)throw t;return Xe(uo(n),Ga(e))}}function Ua(e,t){let n=w0(e,t);return n===""||!y0(n)&&n!==".."&&!n.startsWith(`..${b0}`)}function Zn(e,t){let n=uo(t);if(!Ua(e,n))throw new re("cache_outside_home","Something under CANARY_HOME/local-repositories links outside CANARY_HOME. Remove that link, then run the command again.");return n}function Qn(e){if(!zn.test(e.userId)||!zn.test(e.workspaceId))throw new re("invalid_account_context","Sign in with canary login and select a workspace with canary workspace use <id>, then run the command again.");let t=Xn(e.directory),n=v0(e.apiUrl),r=uo(Ja(K())),s=Ga(t.commonDirectory)===".git"?_d(t.commonDirectory):t.commonDirectory,o=Od("sha256").update(JSON.stringify([Kr,n,e.userId,e.workspaceId,t.githubFullName?`github:${t.githubFullName.toLowerCase()}`:t.commonDirectory])).digest("hex"),i=Xe(r,"local-repositories"),a=Zn(i,Xe(i,o));if([t.root,t.commonDirectory,s].some(c=>Ua(c,r)||Ua(c,a)))throw new re("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:o,cacheRoot:i,cacheDirectory:a}}function Ed(e,t){let n=Zn(e.cacheRoot,Xe(e.cacheDirectory,t)),r;try{r=qa(n,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw new re("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 s;try{s=JSON.parse(r)}catch{}let o=t==="identity.json"?["version","scope","localKey"]:["version","scope","localKey","repositoryId"];if(!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).some(i=>!o.includes(i))||s.version!==Kr||s.scope!==e.scope||typeof s.localKey!="string"||!zn.test(s.localKey)||t==="repository.json"&&(typeof s.repositoryId!="string"||!zn.test(s.repositoryId)))throw new re("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 s}function kn(e){let t=Ed(e,"identity.json"),n=Ed(e,"repository.json");if(!t&&!n)return null;if(!t||n&&n.localKey!==t.localKey)throw new re("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 Ya(e,t,n){co(e.cacheDirectory,{recursive:!0,mode:448});let r=Xe(e.cacheDirectory,`${t}.${ao()}.tmp`);try{Ha(r,JSON.stringify({version:Kr,scope:e.scope,...n})+`
|
|
1670
|
+
`,{flag:"wx",mode:384});try{g0(r,Xe(e.cacheDirectory,t))}catch(s){if(s.code!=="EEXIST")throw s}}finally{lo(r,{force:!0})}}function jd(e,t){co(e.cacheDirectory,{recursive:!0,mode:448});let n=Xe(e.cacheDirectory,`repository.json.${ao()}.tmp`);Ha(n,JSON.stringify({version:Kr,scope:e.scope,...t})+`
|
|
1671
|
+
`,{flag:"wx",mode:384}),Nd(n,Xe(e.cacheDirectory,"repository.json"))}function Pd(e){return kn(Qn(e))}function Va(e,t){let n=Qn(e),r=kn(n);!r?.repositoryId||r.repositoryId===t||jd(n,{localKey:r.localKey,repositoryId:t})}function Ut(e,t){if(!/^[a-z0-9-]+\.json(?:\.gz)?$/.test(t))throw new re("invalid_receipt_name","Invalid cache file name.");let n=Qn(e);return co(n.cacheDirectory,{recursive:!0,mode:448}),Zn(n.cacheRoot,Xe(n.cacheDirectory,t))}function x0(e){return Md(Qn(e))}function Md(e){let t=kn(e);return t||(Ya(e,"identity.json",{localKey:ao()}),kn(e))}function S0(e){try{let t=JSON.parse(qa(Zn(e.cacheRoot,Xe(e.cacheDirectory,Ka)),"utf8"));return t.version===1&&t.checkout===za(e.githubFullName)}catch{return!1}}function C0(e){co(e.cacheDirectory,{recursive:!0,mode:448});let t=Zn(e.cacheRoot,Xe(e.cacheDirectory,Ka)),n=`${t}.${ao()}.tmp`;try{Ha(n,JSON.stringify({version:1,at:new Date().toISOString(),checkout:za(e.githubFullName)})+`
|
|
1672
|
+
`,{flag:"wx",mode:384}),Nd(n,t)}finally{lo(n,{force:!0})}}async function Ld(e,t){let n=Qn(e),r=kn(n);if(r?.repositoryId)return r;let{githubFullName:s}=n;if(!s||S0({...n,githubFullName:s}))return null;let o=await t(s);if(!o)return null;if("notConnected"in o)return C0({...n,githubFullName:s}),null;if(!zn.test(o.repositoryId))return null;let i=Md(n);return i.repositoryId||Ya(n,"repository.json",{localKey:i.localKey,repositoryId:o.repositoryId}),kn(n)}function Fd(){let e=Xe(uo(Ja(K())),"local-repositories"),t=Zn(e,e),n;try{n=m0(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}return n.map(r=>Xe(t,r,Ka)).filter(r=>$d(r,{throwIfNoEntry:!1})?.isFile())}function ho(){try{for(let e of Fd())lo(e,{force:!0})}catch{}}function fo(e){try{let t=Fd();if(!t.length)return;let{githubFullName:n}=Xn(e??process.cwd());if(!n)return;let r=za(n);for(let s of t)try{JSON.parse(qa(s,"utf8")).checkout===r&&lo(s,{force:!0})}catch{}}catch{}}function A0(e,t,n,r){let s=e,o=n.githubFullName?"github":"local";if(!s||typeof s.repositoryId!="string"||!zn.test(s.repositoryId)||s.provider!==o||t.repositoryId&&s.repositoryId!==t.repositoryId&&o!=="github"||(o==="local"?s.localKey!==t.localKey:s.localKey!==void 0)||typeof s.name!="string"||!s.name.trim()||s.name.length>512||/[\u0000-\u001f\u007f]/.test(s.name)||!s.workspace||s.workspace.id!==r||typeof s.workspace.name!="string")throw new re("invalid_repository_response","Canary returned an unexpected answer while looking up this repository. Run the command again; if it repeats, update the CLI.");return s}async function vn(e,t=W){if(!e.token)throw new re("not_logged_in","Run canary login first.");let n=Qn(e),r=x0(e),s={token:e.token,baseUrl:n.apiUrl},o=r.repositoryId?await t(`/api/v1/cli/local-repositories/${r.repositoryId}?workspaceId=${encodeURIComponent(e.workspaceId)}`,s):await t("/api/v1/cli/local-repositories",{...s,method:"POST",body:{workspaceId:e.workspaceId,localKey:r.localKey,name:n.name,...n.githubFullName?{githubFullName:n.githubFullName}:{}}}),i=A0(o,r,n,e.workspaceId);r.repositoryId&&r.repositoryId!==i.repositoryId?jd(n,{localKey:r.localKey,repositoryId:i.repositoryId}):Ya(n,"repository.json",{localKey:r.localKey,repositoryId:i.repositoryId});let a=kn(n);if(a?.repositoryId!==i.repositoryId||a.localKey!==r.localKey)throw new re("binding_conflict","Another canary process registered this repository at the same time. Run the command again.");return i}var zn,Kr,Td,re,Ka,za,Fe=Z(()=>{"use strict";w();fe();ee();Ba();zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Kr=2,Td=/^[A-Za-z0-9_.-]+$/,re=class extends Error{constructor(n,r){super(r);this.code=n;this.name="LocalRepositoryError"}};Ka="not-connected.json",za=e=>Od("sha256").update(JSON.stringify([Kr,`github:${e.toLowerCase()}`])).digest("hex")});async function xn(e,t,n=ue()){let r=V().team?.id;if(!r)throw new re("workspace_selection_required","Select a workspace with canary workspace list and canary workspace use <id>, then run the command again.");let s=await W("/api/v1/cli/auth/whoami",{token:t,baseUrl:n});if(!s?.user?.id)throw new re("invalid_identity_response","Canary could not tell which account this token belongs to. Run canary login again.");return{apiUrl:n,userId:s.user.id,workspaceId:r,directory:e}}async function po(e,t,n){let r=Pd(e);if(!r?.repositoryId)return;let s=await W(`/api/v1/cli/local-repositories/${r.repositoryId}/status?workspaceId=${encodeURIComponent(e.workspaceId)}`,{token:t,baseUrl:e.apiUrl,signal:n});if(typeof s?.repositoryId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.repositoryId)||!["setup_required","ready"].includes(s.state))throw new re("invalid_readiness_response","Canary returned an unexpected answer about this repository's setup. Run the command again.");return s.repositoryId!==r.repositoryId&&Va(e,s.repositoryId),s}function Dd(e=process.cwd()){try{return Xn(e).name}catch{return}}var zr=Z(()=>{"use strict";w();fe();ee();Fe()});import{spawn as I0}from"node:child_process";import{createHash as So}from"node:crypto";import{constants as Wd}from"node:fs";import{lstat as nc,mkdir as Ud,mkdtemp as qd,open as Hd,readFile as R0,readdir as T0,readlink as E0,realpath as Ot,rm as Gd,writeFile as O0}from"node:fs/promises";import{tmpdir as Jd}from"node:os";import{basename as $0,dirname as N0,isAbsolute as _0,join as De,relative as j0,resolve as Yd,sep as P0}from"node:path";import{promisify as M0}from"node:util";import{deflate as L0}from"node:zlib";function rc(e,t){let n=e.split("/");(!e||Buffer.byteLength(e)>t.maxPathBytes||n.length>t.maxDepth||n.some(r=>!r||Buffer.byteLength(r)>255||r==="."||r===".."||Kd(r)||r.includes("\0")||r.includes("\\")))&&q("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(e)}.`)}function W0(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 zd(e,t){return Cn(e).map(n=>{let r=n.indexOf(" "),[s,o,i]=n.slice(0,r).split(" ");return r<0||!(t?wo.test(o):wo.test(i))?q("git_source_error","Git returned an invalid source entry."):(t&&i!=="0"&&q("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:n.slice(r+1),mode:s,oid:t?o:i})})}function sc(e){return(e??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256)||void 0}async function Za(e,t){let n=await e.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,r=await Xa(e),s={headSha:n,branch:r,baseRef:null,baseSha:null,baselineMode:"whole-project"};if(t!==void 0){(!t||t.startsWith("-")||t.length>1024||/[\x00-\x1f\x7f]/.test(t))&&q("invalid_base","--base must name a local Git commit or ref.");let a=await e.text(["rev-parse","--verify","--quiet",`${t}^{commit}`],!0);return wo.test(a)||q("invalid_base",`--base ${JSON.stringify(t)} is not a local commit or ref. Canary does not fetch; pass one that exists locally.`),{...s,baseRef:t,baseSha:a,baselineMode:"explicit"}}if(!n)return s;let o=await e.text(["symbolic-ref","--quiet","refs/remotes/origin/HEAD"],!0),i;for(let a of[[o],["refs/remotes/origin/main","refs/remotes/origin/master"],["main","master"].filter(c=>c!==r).map(c=>`refs/heads/${c}`)]){for(let c of[...new Set(a.filter(Boolean))]){let l=await e.text(["rev-parse","--verify","--quiet",`${c}^{commit}`],!0);if(!l)continue;let d=await e.text(["merge-base",n,l],!0);if(!d)continue;let u=Number(await e.text(["rev-list","--count",`${d}..${n}`]));(!i||u<i.distance)&&(i={ref:c,base:d,distance:u})}if(i)break}return i?{...s,baseRef:i.ref,baseSha:i.base,baselineMode:"merge-base"}:s}async function Xd(e,t){let{git:n}=await oc(e,t);return(await Za(n)).baseSha}async function Qa(e){return new Set(Cn(await e.run(["ls-files","--cached","--ignored","--exclude-standard","-z"])))}async function Sn(e,t,n){if(!t.length)return;let r=Cn(await e.run(["check-attr",...n?["--cached"]:[],"-z","--stdin","filter"],{input:`${t.join("\0")}\0`}));for(let s=0;s<r.length;s+=3)r[s+2]==="lfs"&&q("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(r[s])}. Remove the LFS attribute for it, or ignore the file.`)}function U0(e,t){(e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
|
|
1654
1673
|
`)||e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1\r
|
|
1655
|
-
`))&&
|
|
1674
|
+
`))&&q("unsupported_lfs",`${JSON.stringify(t)} is a Git LFS pointer. Canary needs the real file contents.`)}function ec(e,t){(e.length>t.maxTreeFiles||e.reduce((o,i)=>o+i.size,0)>t.maxTreeBytes)&&q("snapshot_limit","This repository has too many files, or too many bytes, to upload.");let n=new Map,r=new Map,s=new Map;for(let o of e){rc(o.path,t),o.link!==void 0&&s.set(o.path,o.link);let i=o.path.split("/");for(let a=1;a<=i.length;a++){let c=i.slice(0,a).join("/"),l=c.normalize("NFC").toLowerCase();n.has(l)&&n.get(l)!==c&&q("unsupported_path",`Source paths differ only by case or Unicode normalization: ${JSON.stringify(c)}.`),n.set(l,c);let d=a<i.length;r.has(c)&&r.get(c)!==d&&q("unsupported_path",`Source path is both a directory and a file: ${JSON.stringify(c)}.`),r.set(c,d)}}[...r.values()].filter(Boolean).length+1>t.maxObjects&&q("snapshot_limit","This repository has too many directories to upload.");for(let[o,i]of s){(!i||Buffer.byteLength(i)>t.maxSymlinkBytes||i.startsWith("/")||i.includes("\0")||i.includes("\\")||/^[a-z]:/i.test(i))&&q("unsafe_symlink",`Unsafe symlink target at ${JSON.stringify(o)}.`);let a=i.split("/"),c=o.split("/").slice(0,-1),l=0;for(;a.length;){let d=a.shift();if(!d||d===".")continue;if(d===".."){c.length||q("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(o)}.`),c.pop();continue}Kd(d)&&q("unsafe_symlink",`Symlink enters Git metadata: ${JSON.stringify(o)}.`),c.push(d);let u=n.get(c.join("/").normalize("NFC").toLowerCase());if(u!==void 0&&s.has(u)){++l>t.maxDepth&&q("unsafe_symlink",`Symlink cycle or excessive chain depth at ${JSON.stringify(o)}.`);let h=s.get(u);(h.startsWith("/")||h.includes("\\")||/^[a-z]:/i.test(h))&&q("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(o)}.`),c.pop(),a.unshift(...h.split("/"))}a.length+c.length>t.maxPathBytes&&q("unsafe_symlink","Symlink expansion exceeds the source limit.")}}}async function vo(e,t){let n=new Map;for(let s of e){let o=s.path.split("/"),i=n;for(let a of o.slice(0,-1))i.has(a)||i.set(a,new Map),i=i.get(a);i.set(o.at(-1),s)}let r=async s=>{let o=[];for(let[i,a]of s)o.push(a instanceof Map?{name:i,mode:"40000",oid:await r(a)}:{name:i,mode:a.mode,oid:a.oid});return o.sort((i,a)=>Buffer.compare(Buffer.from(i.name+(i.mode==="40000"?"/":"")),Buffer.from(a.name+(a.mode==="40000"?"/":"")))),t.put("tree",Buffer.concat(o.map(i=>Buffer.concat([Buffer.from(`${i.mode} ${i.name}\0`),Buffer.from(i.oid,"hex")]))))};return r(n)}async function Zd(e,t){let n=t.split("/");for(let r=1;r<=n.length;r++)try{let s=await nc(De(e,...n.slice(0,r)));if(r===n.length)return s;if(!s.isDirectory())return null}catch(s){if(["ENOENT","ENOTDIR"].includes(s.code??""))return null;throw s}return null}async function q0(e,t,n,r){let s=await Zd(e,t);if(n.set(t,s?er(s):null),!s||s.isDirectory())return null;if(!s.isFile()&&!s.isSymbolicLink()&&q("unsupported_file",`This is not a regular file or symlink and cannot be uploaded: ${JSON.stringify(t)}.`),s.size>(s.isSymbolicLink()?r.maxSymlinkBytes:r.maxObjectBytes)&&q("snapshot_limit",`This file is too large to upload: ${JSON.stringify(t)}.`),s.isSymbolicLink())return{data:await E0(De(e,t),{encoding:"buffer"}),mode:"120000"};let o=await Hd(De(e,t),Wd.O_RDONLY|Wd.O_NOFOLLOW);try{er(await o.stat())!==er(s)&&q("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.");let i=Buffer.alloc(s.size+1),a=0;for(;a<i.length;){let l=await o.read(i,a,i.length-a);if(!l.bytesRead)break;a+=l.bytesRead}return(a!==s.size||er(await o.stat())!==er(s))&&q("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped."),{data:i.subarray(0,a),mode:s.mode&73?"100755":"100644"}}finally{await o.close()}}async function H0(e,t,n,r,s){let o=Buffer.from(`# v2 git bundle
|
|
1656
1675
|
${n} refs/canary/base
|
|
1657
1676
|
${r} refs/canary/head
|
|
1658
1677
|
|
|
1659
|
-
`),i=await
|
|
1660
|
-
`);for await(let p of a.stdout)await h(p);return await u!==0&&
|
|
1661
|
-
`).some(c=>/^extensions\.objectformat\s+(?!sha1$)/i.test(c))&&
|
|
1662
|
-
`).some(c=>/^extensions\.partialclone\s/i.test(c)||/^remote\..*\.promisor(?:\s|$)/i.test(c)&&!/\s(false|no|off|0)$/i.test(c))||(await
|
|
1678
|
+
`),i=await Hd(t,"wx",384);try{let a=e.child(["pack-objects","--stdout","--revs","--no-reuse-delta","--no-reuse-object","--window=0","--threads=1","--compression=6"]),c=So("sha256"),l=0,d="";a.stderr.on("data",p=>{d.length<8192&&(d+=p.toString())}),a.stdin.on("error",()=>{});let u=new Promise((p,f)=>{a.on("close",p),a.on("error",f)});u.catch(()=>{});let h=async p=>{l+=p.length,l>s.maxBundleBytes&&q("snapshot_limit","This repository is too large to upload, even compressed."),c.update(p),await i.writeFile(p)};try{await h(o),a.stdin.end(`${r}
|
|
1679
|
+
`);for await(let p of a.stdout)await h(p);return await u!==0&&q("git_source_error",`Cannot package source: ${d.trim()}`),{bytes:l,sha256:c.digest("hex")}}finally{a.kill(),await u.catch(()=>{})}}finally{await i.close()}}function Qd(e){let t={...Xr,...e};for(let[n,r]of Object.entries(t))(!Object.hasOwn(Xr,n)||!Number.isSafeInteger(r)||r<=0||r>Xr[n])&&q("invalid_limit",`Invalid source snapshot limit ${n}.`);return t}async function oc(e,t){let n=await Ot(e),r=new qt(n,t),s;try{s=await Ot(await r.text(["rev-parse","--show-toplevel"]))}catch(c){if(t?.aborted)throw c;return q("not_a_git_repository","Run this command inside a Git repository.")}let o=new qt(s,t),i=await Ot(Yd(s,await o.text(["rev-parse","--git-common-dir"]))),a=await o.text(["config","--get-regexp","^(extensions\\.partialclone|remote\\..*\\.promisor|extensions\\.objectformat)$"],!0);return a.split(`
|
|
1680
|
+
`).some(c=>/^extensions\.objectformat\s+(?!sha1$)/i.test(c))&&q("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(a.split(`
|
|
1681
|
+
`).some(c=>/^extensions\.partialclone\s/i.test(c)||/^remote\..*\.promisor(?:\s|$)/i.test(c)&&!/\s(false|no|off|0)$/i.test(c))||(await T0(De(i,"objects","pack")).catch(()=>[])).some(c=>c.endsWith(".promisor")))&&q("partial_clone","This is a partial clone. Canary needs every Git object on disk and will not fetch them; use a full clone."),{root:s,common:i,git:o}}async function G0(e,t,n){let r=De(e,n,".git"),s=await nc(r).catch(()=>null);if(!s?.isFile()||s.size>4096)return!1;let o=/^gitdir: (.+?)\r?\n?$/.exec(await R0(r,"utf8").catch(()=>""))?.[1];if(!o)return!1;let[i,a]=await Promise.all([Ot(Yd(e,n,o)).catch(()=>null),Ot(De(t,"worktrees")).catch(()=>null)]);return i!==null&&a!==null&&N0(i)===a}async function xo(e,t,n,r){let s=zd(await e.run(["ls-files","--stage","-z"]),!0),o=r.likeClone?new Set:await Qa(e),i=s.filter(d=>th(d,o)),a=[];for(let d of Cn(await e.run(["ls-files","--others","--exclude-standard","-z"])).filter(u=>!eh(u)))d.endsWith("/")&&(r.likeClone||await G0(t,n,d.slice(0,-1)))||a.push(d);let c=new Set(Cn(await e.run(["ls-files","-t","-z"])).filter(d=>d.startsWith("S ")).map(d=>d.slice(2))),l=new Set(i.filter(Ht).map(d=>d.path));return{tracked:i,paths:[...new Set([...i.map(d=>d.path),...a])].sort(),skip:c,gitlinks:l}}async function nh(e){return async()=>So("sha256").update(await e.run(["ls-files","--stage","-v","-z"])).digest("hex")}function rh(e,t){for(let n of e)rc(n.path,t),["100644","100755","120000",Co].includes(n.mode)||q("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(n.path)}.`)}function oh(e,t){let n=e.filter(r=>r.endsWith("/")).map(r=>r.slice(0,-1));if(n.length){let[r]=n,s=n.length===1;q("embedded_repo",`${s?"This directory is a separate Git repository, so its":"These directories are separate Git repositories, so their"} files cannot be uploaded: ${sh(n)}.`,`remove ${r}/.git to upload its files, add it as a submodule, or ignore ${r}/ in .gitignore or .git/info/exclude${s?"":" (and the same for each directory listed)"}`)}for(let r of e)rc(r,t)}function ih(e,t){let n=new Map;return async(r,s,o)=>{U0(s,r.path);let i=await e.put("blob",s);r.oid&&r.oid!==i&&q("invalid_source_object",`Git blob contents do not match their hash: ${JSON.stringify(r.path)}.`);let a=(n.get(o)??0)+s.length;n.set(o,a),a>t.maxTreeBytes&&q("snapshot_limit","This repository has too many bytes to upload."),o.push({...r,oid:i,size:s.length,...r.mode==="120000"?{link:Vd(s)}:{}})}}async function ah(e,t){let n=t.filter(i=>["100644","100755"].includes(i.mode)).map(i=>i.path);if(!n.length)return new Set;let r=["true","yes","on","1","input"].includes((await e.text(["config","--get","core.autocrlf"],!0)).toLowerCase()),s=new Map,o=Cn(await e.run(["check-attr","-z","--stdin","text","eol"],{input:`${n.join("\0")}\0`}));for(let i=0;i+2<o.length;i+=3)s.set(o[i],{...s.get(o[i]),[o[i+1]]:o[i+2]});return new Set(n.filter(i=>{let{text:a,eol:c}=s.get(i)??{};return a==="unset"?!1:a==="set"||a==="auto"||c==="lf"||c==="crlf"||r}))}function J0(e,t){if(!e.includes(`\r
|
|
1663
1682
|
`)||e.subarray(0,8e3).includes(0))return null;let n=Buffer.allocUnsafe(e.length),r=0,s=0;for(let i=e.indexOf(`\r
|
|
1664
1683
|
`);i!==-1;i=e.indexOf(`\r
|
|
1665
|
-
`,i+2))r+=e.copy(n,r,s,i),s=i+1;r+=e.copy(n,r,s);let o=n.subarray(0,r);return So("sha1").update(`blob ${r}\0`).update(o).digest("hex")===t.oid?o:null}async function
|
|
1666
|
-
`);if(!o||!i||!wo.test(i))return null;let[a,c]=await Promise.all([Ot(o).catch(()=>null),Ot(r).catch(()=>null)]);return a!==null&&a===c?i:null}async function
|
|
1667
|
-
`)+1)))}catch(r){if(r instanceof We&&r.code==="git_source_error")return new Set;throw r}}async function
|
|
1684
|
+
`,i+2))r+=e.copy(n,r,s,i),s=i+1;r+=e.copy(n,r,s);let o=n.subarray(0,r);return So("sha1").update(`blob ${r}\0`).update(o).digest("hex")===t.oid?o:null}async function ch(e,t,n){let r=De(e,t);if(!await nc(De(r,".git")).then(()=>!0,()=>!1))return null;let s;try{s=(await new qt(r,n).run(["rev-parse","--show-toplevel","--verify","--quiet","HEAD^{commit}"],{optional:!0})).toString("utf8")}catch(l){if(l instanceof We&&l.code==="git_source_error")return null;throw l}let[o,i]=s.trim().split(`
|
|
1685
|
+
`);if(!o||!i||!wo.test(i))return null;let[a,c]=await Promise.all([Ot(o).catch(()=>null),Ot(r).catch(()=>null)]);return a!==null&&a===c?i:null}async function lh(e){let{root:t,current:n,trustFileMode:r,limits:s,stamps:o,heads:i,capture:a,out:c}=e,l=new Map(n.tracked.map(d=>[d.path,d]));for(let d of n.paths){e.signal?.throwIfAborted();let u=l.get(d);if(e.likeClone&&u&&Ht(u)){c.push(yo(d,u.oid));continue}let h=await q0(t,d,o,s);if(h){let p=!r&&h.mode!=="120000"&&u&&["100644","100755"].includes(u.mode)?u.mode:h.mode,f=u&&h.mode!=="120000"&&e.converts.has(d)?J0(h.data,u):null;await a({path:d,mode:p,oid:""},f??h.data,c)}else if(u&&Ht(u))if(o.get(d)!==null){let p=await ch(t,d,e.signal);i.set(d,p),c.push(yo(d,p??u.oid))}else n.skip.has(d)&&c.push(yo(d,u.oid));else if(o.get(d)===null&&n.skip.has(d)){let p=l.get(d);await a(p,await e.blob(p.oid),c)}}}async function uh(e,t){for(let[n,r]of t){let s=await Zd(e,n);(s?er(s):null)!==r&&q("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}}async function dh(e,t,n){for(let[r,s]of t)await ch(e,r,n)!==s&&q("source_changed","A submodule moved to another commit while the source was being captured. Run the command again once it has settled.")}async function Y0(e,t,n){if(!n.some(r=>r.path===".gitmodules"&&r.mode.startsWith("100")))return new Set;try{let r=Cn(await e.run(["config","-z","--blob",`${t}:.gitmodules`,"--get-regexp","^submodule\\..*\\.path$"],{optional:!0}));return new Set(r.map(s=>s.slice(s.indexOf(`
|
|
1686
|
+
`)+1)))}catch(r){if(r instanceof We&&r.code==="git_source_error")return new Set;throw r}}async function V0(e,t,n,r){let s=new Map(n.filter(Ht).map(d=>[d.path,d.oid])),o=r.filter(d=>Ht(d)&&s.get(d.path)!==d.oid);if(!o.length)return;let i=await Y0(e,t,r),a=o.map(d=>d.path).filter(d=>!i.has(d));if(!a.length)return;let[c]=a,l=a.length===1;q("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: ${sh(a)}.`,`add it as a submodule, or run \`git rm --cached -f ${c}\` and remove ${c}/.git so its files are uploaded as plain files${l?"":" (and the same for each path listed)"}`)}function K0(e,t){return e?t?e.oid===t.oid&&e.mode===t.mode?null:Bd(e.mode)===Bd(t.mode)?"M":"T":"D":"A"}async function An(e,t={}){let n=Qd(t.limits),{root:r,common:s,git:o}=await oc(e,t.signal),i=await Ot(Jd());(bo(r,i)||bo(s,i))&&q("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await qd(De(i,"canary-source-")),c,l=()=>Gd(a,{recursive:!0,force:!0});try{let d=await Za(o,t.baseRef),u=await nh(o),h=await u(),p=new qt(r,t.signal,!1,{GIT_INDEX_FILE:De(a,"baseline-index")});await p.run(["read-tree",d.baseSha??"--empty"]);let f=d.baseSha?zd(await o.run(["ls-tree","-r","-z","--full-tree",d.baseSha]),!1):[],g=t.likeClone?new Set:await Qa(p),m=f.filter(z=>th(z,g)),C=await xo(o,r,s,t),A=await o.text(["config","--bool","--get","core.fileMode"],!0)!=="false";(m.length>n.maxTreeFiles||C.paths.length>n.maxTreeFiles)&&q("snapshot_limit","This repository has too many files to upload."),rh([...m,...C.tracked],n),oh(C.paths,n),await Sn(p,mo(m),!0),await Sn(o,tc(C),!1);let b=De(a,"repository.git");await Ud(b);let S=new qt(b,t.signal,!0);await S.run(["init","--bare","--quiet","--template="]);let x=new Zr(b,n,t.signal);c=new ko(o,n);let v=[],I=[],$=ih(x,n),y=c;for(let z of m)Ht(z)?v.push(yo(z.path,z.oid)):await $(z,await c.get(z.oid),v);let k=new Map,N=new Map,G=t.likeClone?await ah(o,C.tracked):new Set;await lh({root:r,current:C,trustFileMode:A,limits:n,signal:t.signal,stamps:k,heads:N,capture:$,blob:z=>y.get(z),out:I,converts:G,likeClone:t.likeClone===!0}),ec(v,n),ec(I,n);let Le=await vo(v,x),Ce=await vo(I,x);for(let[z,gt]of[[Le,v],[Ce,I]])await S.run(["read-tree",z]),await Sn(S,mo(gt),!0);await V0(S,Ce,v,I);let ae=await x.put("commit",Buffer.from(`tree ${Le}
|
|
1668
1687
|
author ${go}
|
|
1669
1688
|
committer ${go}
|
|
1670
1689
|
|
|
@@ -1675,50 +1694,50 @@ author ${go}
|
|
|
1675
1694
|
committer ${go}
|
|
1676
1695
|
|
|
1677
1696
|
Canary snapshot current
|
|
1678
|
-
`)),M=De(a,"source.bundle"),E=await H0(S,M,ae,T,n),U=await xo(o,r,s,t);(h!==await u()||JSON.stringify(C.paths)!==JSON.stringify(U.paths)||!t.likeClone&&JSON.stringify([...g].sort())!==JSON.stringify([...await
|
|
1697
|
+
`)),M=De(a,"source.bundle"),E=await H0(S,M,ae,T,n),U=await xo(o,r,s,t);(h!==await u()||JSON.stringify(C.paths)!==JSON.stringify(U.paths)||!t.likeClone&&JSON.stringify([...g].sort())!==JSON.stringify([...await Qa(p)].sort())||JSON.stringify(d)!==JSON.stringify(await Za(o,t.baseRef)))&&q("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped."),await uh(r,k),await dh(r,N,t.signal),await Sn(p,mo(m),!0),await Sn(o,tc(C),!1);let J=new Map(v.map(z=>[z.path,z])),ne=new Map(I.map(z=>[z.path,z])),Ye=[];for(let z of[...new Set([...J.keys(),...ne.keys()])].sort()){let gt=K0(J.get(z),ne.get(z));gt&&Ye.push({path:z,status:gt})}await c.close(),c=void 0;let St=I.map(z=>({path:z.path,mode:z.mode,oid:z.oid})),et=I.filter(Ht).map(z=>z.path);return{bundlePath:M,manifest:{kind:"local_snapshot",version:2,...E,baseTreeHash:Le,treeHash:Ce,baseSha:ae,headSha:T,provenance:d},files:Ye,entries:St,submodules:et,dispose:l}}catch(d){throw await c?.close(),await l(),d}}async function z0(e,t,n,r,s,o){let i=await Ot(Jd());(bo(e,i)||bo(t,i))&&q("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await qd(De(i,"canary-identity-"));try{let c=new qt(a,o,!0);await c.run(["init","--bare","--quiet","--template="]);let l=new Zr(a,s,o);for(let d of r.values())await l.put("blob",d);await c.run(["read-tree",await vo(n,l)]),await Sn(c,mo(n),!0)}finally{await Gd(a,{recursive:!0,force:!0})}}async function Qr(e,t={}){let n=Qd(t.limits),{root:r,common:s,git:o}=await oc(e,t.signal),i;try{let a=await Xa(o),c=await nh(o),l=await c(),d=await xo(o,r,s,t),u=await o.text(["config","--bool","--get","core.fileMode"],!0)!=="false";d.paths.length>n.maxTreeFiles&&q("snapshot_limit","This repository has too many files to upload."),rh(d.tracked,n),oh(d.paths,n),await Sn(o,tc(d),!1);let h=new Zr(null,n,t.signal),p=[],f=new Map,g=new Map,m=new Map,C=ih(h,n),A=(v,I,$)=>($0(v.path)===".gitattributes"&&m.set(v.path,I),C(v,I,$)),b=t.likeClone?await ah(o,d.tracked):new Set;await lh({root:r,current:d,trustFileMode:u,limits:n,signal:t.signal,stamps:f,heads:g,capture:A,blob:v=>(i??=new ko(o,n)).get(v),out:p,converts:b,likeClone:t.likeClone===!0}),ec(p,n);let S=await vo(p,h);[...m.values()].some(v=>/(?:^|\s)filter=lfs(?:\s|$)/m.test(v.toString("utf8")))&&await z0(r,s,p,m,n,t.signal);let x=await xo(o,r,s,t);return(l!==await c()||JSON.stringify(d.paths)!==JSON.stringify(x.paths)||a!==await Xa(o))&&q("source_changed","The Git state changed while the source was being read. Run the command again once editing has stopped."),await uh(r,f),await dh(r,g,t.signal),{root:r,treeHash:S,branch:a,files:p.map(v=>({path:v.path,mode:v.mode,oid:v.oid}))}}finally{await i?.close()}}var Xr,We,q,F0,D0,wo,Co,go,bo,Vd,Cn,Kd,B0,qt,Xa,ko,Zr,er,eh,th,Ht,tc,mo,sh,yo,Bd,Gt=Z(()=>{"use strict";w();Xr={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},We=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="SourceSnapshotError"}},q=(e,t,n)=>{throw new We(e,t,n)},F0=M0(L0),D0=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),wo=/^[a-f0-9]{40}$/,Co="160000",go="Canary Snapshot <snapshot@runcanary.ai> 0 +0000",bo=(e,t)=>{let n=j0(e,t);return n===""||!n.startsWith(`..${P0}`)&&n!==".."&&!_0(n)},Vd=e=>{try{return D0.decode(e)}catch{return q("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},Cn=e=>e.length?Vd(e).split("\0").filter(Boolean):[],Kd=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)};B0=["-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"],qt=class{constructor(t,n,r=!1,s={}){this.cwd=t;this.signal=n;this.isolated=r;this.extra=s}child(t){return this.signal?.throwIfAborted(),I0("git",[...B0,...t],{cwd:this.cwd,env:{...W0(this.isolated),...this.extra},signal:this.signal,stdio:"pipe"})}async run(t,n={}){let r=this.child(t),s=[],o=0,i="",a;r.on("error",l=>{a=l}),r.stdout.on("data",l=>{o+=l.length,o>(n.maxBytes??256*1024*1024)?(a=new We("snapshot_limit","This repository's Git metadata is too large to upload."),r.kill()):s.push(l)}),r.stderr.on("data",l=>{i.length<8192&&(i+=l.toString("utf8"))}),r.stdin.on("error",()=>{}),r.stdin.end(n.input);let c=await new Promise(l=>r.on("close",l));if(a)throw a;return c!==0&&!(n.optional&&c===1)&&q("git_source_error",`Cannot read local Git source: ${i.trim()||`git ${t[0]} failed`}`),c===1?Buffer.alloc(0):Buffer.concat(s)}async text(t,n=!1){return(await this.run(t,{optional:n})).toString("utf8").trim()}};Xa=async e=>await e.text(["symbolic-ref","--quiet","--short","HEAD"],!0)||null;ko=class{constructor(t,n){this.limits=n;this.child=t.child(["cat-file","--batch"]),this.child.on("error",r=>{this.error=r}),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=[],r=t;for(;r;){if(!this.pending.length){let o=await this.iterator.next();if(o.done)throw this.error??new We("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=o.value}let s=Math.min(r,this.pending.length);n.push(this.pending.subarray(0,s)),this.pending=this.pending.subarray(s),r-=s}return Buffer.concat(n,t)}async get(t){this.child.stdin.write(`${t}
|
|
1679
1698
|
`);let n="";for(;!n.endsWith(`
|
|
1680
|
-
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[r,s,o]=n.trim().split(" "),i=Number(o);(r!==t||s!=="blob"||!Number.isSafeInteger(i)||i<0)&&H("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),i>this.limits.maxObjectBytes&&H("snapshot_limit","A file in this repository is too large to upload.");let a=await this.read(i);return(await this.read(1))[0]!==10&&H("git_source_error","Invalid Git object framing."),a}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())))}},Xr=class{constructor(t,n,r){this.directory=t;this.limits=n;this.signal=r}sizes=new Map;expanded=0;async put(t,n){this.signal?.throwIfAborted(),n.length>this.limits.maxObjectBytes&&H("snapshot_limit","A file in this repository is too large to upload.");let r=Buffer.from(`${t} ${n.length}\0`),s=So("sha1").update(r).update(n).digest("hex");if(!this.sizes.has(s)&&((this.sizes.size+1>this.limits.maxObjects||this.expanded+n.length>this.limits.maxExpandedBytes)&&H("snapshot_limit","This repository has too many files, or too many bytes, to upload."),this.sizes.set(s,n.length),this.expanded+=n.length,this.directory!==null)){let o=De(this.directory,"objects",s.slice(0,2));await Wd(o,{recursive:!0}),await E0(De(o,s.slice(2)),await L0(Buffer.concat([r,n]),{level:6}),{mode:384,flag:"wx"})}return s}};er=e=>`${e.dev}:${e.ino}:${e.mode}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`;Zd=e=>e.split("/").some(t=>t.toLowerCase()===".git"),Qd=(e,t)=>!t.has(e.path)&&!Zd(e.path),Ht=e=>e.mode===Co;ec=e=>e.paths.filter(t=>!e.gitlinks.has(t)),mo=e=>e.filter(t=>!Ht(t)).map(t=>t.path);nh=e=>e.slice(0,5).map(t=>JSON.stringify(t)).join(", ")+(e.length>5?` and ${e.length-5} more`:"");yo=(e,t)=>({path:e,mode:Co,oid:t,size:0});Dd=e=>e==="120000"?"symlink":e===Co?"submodule":"file"});import{readFileSync as z0,renameSync as UE,rmSync as X0,writeFileSync as HE}from"node:fs";async function Qr(e,t,n={}){try{await B("/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 uh(e,t){return!t||e.decision!=="allow"||!Z0.has(e.cause)?Promise.resolve():Qr(`gate_allow:${e.cause}`,t,{timeoutMs:500})}function dh(e,t=Date.now()){try{let n=Bt(e,Q0),r=Date.parse(JSON.parse(z0(n,"utf8")).at??"");return X0(n,{force:!0}),Number.isFinite(r)&&t-r>=0&&t-r<ek}catch{return!1}}var Z0,Q0,ek,Ao=Z(()=>{"use strict";w();fe();Fe();Z0=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);Q0="last-denial.json",ek=1440*60*1e3});import{randomUUID as tk}from"node:crypto";import{readdirSync as nk,readFileSync as zE,renameSync as rk,rmSync as hh,statSync as sk,writeFileSync as ok}from"node:fs";import{dirname as fh,join as ik}from"node:path";import{gunzipSync as QE,gzipSync as ak}from"node:zlib";function ph(e,t,n){try{let r=Bt(e,lk(t)),s=`${r}.${tk()}.tmp`,o=ak(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:t,entries:n.map(i=>[i.path,i.mode,i.oid])})));try{ok(s,o,{flag:"wx",mode:384}),rk(s,r)}catch(i){throw hh(s,{force:!0}),i}for(let i of nk(fh(r))){if(!i.startsWith("tree-")||!i.endsWith(".json.gz"))continue;let a=ik(fh(r),i);try{Date.now()-sk(a).mtimeMs>ck&&hh(a,{force:!0})}catch{}}}catch{}}var ck,lk,oc=Z(()=>{"use strict";w();Fe();ck=720*60*60*1e3,lk=e=>`tree-${e}.json.gz`});import{createHash as uk}from"node:crypto";import{constants as gh}from"node:fs";import{open as dk}from"node:fs/promises";import{Readable as hk}from"node:stream";function To(e){if(!ic(e,vh))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<=zr.maxBundleBytes&&[e.baseTreeHash,e.treeHash,e.baseSha,e.headSha].every(n=>typeof n=="string"&&mh.test(n))&&ic(t,xh)&&[t.headSha,t.baseSha].every(n=>n===null||typeof n=="string"&&mh.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 fk(e,t){return vh.filter(n=>n!=="provenance").every(n=>e[n]===t[n])&&xh.every(n=>e.provenance[n]===t.provenance[n])}function es(e,t){if(!ic(e,["uploadId","expiresAt","status","source"])||typeof e.uploadId!="string"||!Ro.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)||!To(e.source)||t?.uploadId!==void 0&&t.uploadId!==e.uploadId||t?.manifest!==void 0&&!fk(t.manifest,e.source))throw new ke(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 Sh(e){if(!Ro.test(e))throw new ke(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${kh}/${e}`}function pk(e,t){return e instanceof ke?new ke(e.status,e.code,e.message,e.fix,t):e instanceof L?new ke(e.status,"source_upload_failed",e.message,e.fix,t):new ke(0,"source_upload_failed",e instanceof Error?e.message:"The source upload failed.","Run the command again to continue the upload.",t)}function Io(e){if(e.status==="completed")return e;throw e.status==="cancelled"?new ke(410,"source_upload_cancelled","This upload was cancelled.",void 0,e.uploadId):new ke(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",e.uploadId)}async function yh(e,t,n={}){let r=await(n.request??B)(Sh(e),{...t});return es(r,{uploadId:e})}async function*Ch(e,t,n){let r=0;for(;r<t;){n?.throwIfAborted();let s=Buffer.allocUnsafe(Math.min(64*1024,t-r)),o=await e.read(s,0,s.length,r);if(!o.bytesRead)throw new ke(0,"source_changed","The source changed while it was being uploaded. Run the command again.");r+=o.bytesRead,yield s.subarray(0,o.bytesRead)}}async function wh(e,t,n){let r=await e.stat();if(!r.isFile()||r.size!==t.bytes)throw new ke(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let s=uk("sha256");for await(let i of Ch(e,t.bytes,n))s.update(i);let o=await e.stat();if(s.digest("hex")!==t.sha256||o.size!==r.size||o.mtimeMs!==r.mtimeMs||o.ctimeMs!==r.ctimeMs)throw new ke(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function bh(e,t,n,r){let s=hk.from(Ch(e,t.manifest.bytes,t.signal));try{let o=await(r.fetch??fetch)(`${t.baseUrl.replace(/\/+$/,"")}${Sh(n)}/content`,{method:"PUT",headers:{...(r.headers??Dt)(),authorization:`Bearer ${t.token}`,"content-type":"application/octet-stream","content-length":String(t.manifest.bytes)},body:s,duplex:"half",signal:t.signal,redirect:"error"});if(!o.ok){let i={};try{i=await o.json()}catch{}throw new ke(o.status,typeof i.code=="string"?i.code:"source_upload_failed",typeof i.error=="string"?i.error:o.statusText,typeof i.fix=="string"?i.fix:void 0,n)}return Io(es(await o.json(),{uploadId:n,manifest:t.manifest}))}catch(o){throw o instanceof ke?o:new ke(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{s.destroy()}}async function Ah(e,t={}){if(!To(e.manifest)||!Ro.test(e.workspaceId)||!Ro.test(e.repositoryId))throw new ke(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},r;if(e.uploadId&&(r=es(await yh(e.uploadId,n,t),{uploadId:e.uploadId,manifest:e.manifest}),r.status!=="pending"))return Io(r);let s=await dk(e.bundlePath,gh.O_RDONLY|gh.O_NOFOLLOW);try{if(await wh(s,e.manifest,e.signal),r||(r=es(await(t.request??B)(kh,{...n,method:"POST",body:{workspaceId:e.workspaceId,repositoryId:e.repositoryId,source:e.manifest}}),{manifest:e.manifest})),e.onReceipt?.(r),r.status!=="pending")return Io(r);try{return await bh(s,e,r.uploadId,t)}catch(o){if(e.signal?.aborted||!(be(o)||o instanceof L&&o.status===409))throw o;let i=es(await yh(r.uploadId,n,t),{uploadId:r.uploadId,manifest:e.manifest});return i.status!=="pending"?Io(i):(await wh(s,e.manifest,e.signal),await bh(s,e,r.uploadId,t))}}catch(o){throw r?pk(o,r.uploadId):o}finally{await s.close()}}var ke,kh,Ro,mh,vh,xh,ic,ac=Z(()=>{"use strict";w();fe();nt();qt();ke=class extends L{constructor(n,r,s,o,i){super(n,s,o);this.code=r;this.uploadId=i;this.name="SourceUploadError"}},kh="/api/v1/cli/source-uploads",Ro=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,mh=/^[a-f0-9]{40}$/,vh=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],xh=["headSha","branch","baseRef","baseSha","baselineMode"],ic=(e,t)=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))});import{createHash as gk,randomUUID as mk}from"node:crypto";import{readFileSync as yk,renameSync as wk,rmSync as Ih,writeFileSync as bk}from"node:fs";function Rh(e,t,n,r="verify"){let s=gk("sha256").update(JSON.stringify([n,e,r])).digest("hex");return Bt(t,`source-upload-${s}.json`)}function Th(e){try{let t=JSON.parse(yk(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 ke(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 ts(e,t,n,r){let s=Rh(e,t,n,r.requestKey),o=Th(s);o&&(!r.uploadId||o.uploadId===r.uploadId)&&Ih(s,{force:!0})}async function tr(e,t,n,r,s={}){let o=Rh(e.manifest,t,n,s.requestKey),i=s.fresh?void 0:Th(o),a=i&&Date.parse(i.expiresAt)>Date.now()?i.uploadId:void 0,c=await Ah({bundlePath:e.bundlePath,manifest:e.manifest,workspaceId:t.workspaceId,repositoryId:n,token:r,baseUrl:t.apiUrl,...a?{uploadId:a}:{},onReceipt:({uploadId:l,expiresAt:d})=>{let u=`${o}.${mk()}.tmp`;try{bk(u,JSON.stringify({uploadId:l,expiresAt:d})+`
|
|
1681
|
-
`,{flag:"wx",mode:384}),
|
|
1682
|
-
`),do:Array.isArray(e.do)?e.do:[]}}function
|
|
1683
|
-
`);let n=[e.failed?`\u2717 ${rt(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 r of e.findings)t.push(""),t.push(`${
|
|
1699
|
+
`)&&n.length<128;)n+=(await this.read(1)).toString("ascii");let[r,s,o]=n.trim().split(" "),i=Number(o);(r!==t||s!=="blob"||!Number.isSafeInteger(i)||i<0)&&q("missing_source_object","A file's Git object is missing on disk. Canary does not fetch; restore it, then run the command again."),i>this.limits.maxObjectBytes&&q("snapshot_limit","A file in this repository is too large to upload.");let a=await this.read(i);return(await this.read(1))[0]!==10&&q("git_source_error","Invalid Git object framing."),a}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())))}},Zr=class{constructor(t,n,r){this.directory=t;this.limits=n;this.signal=r}sizes=new Map;expanded=0;async put(t,n){this.signal?.throwIfAborted(),n.length>this.limits.maxObjectBytes&&q("snapshot_limit","A file in this repository is too large to upload.");let r=Buffer.from(`${t} ${n.length}\0`),s=So("sha1").update(r).update(n).digest("hex");if(!this.sizes.has(s)&&((this.sizes.size+1>this.limits.maxObjects||this.expanded+n.length>this.limits.maxExpandedBytes)&&q("snapshot_limit","This repository has too many files, or too many bytes, to upload."),this.sizes.set(s,n.length),this.expanded+=n.length,this.directory!==null)){let o=De(this.directory,"objects",s.slice(0,2));await Ud(o,{recursive:!0}),await O0(De(o,s.slice(2)),await F0(Buffer.concat([r,n]),{level:6}),{mode:384,flag:"wx"})}return s}};er=e=>`${e.dev}:${e.ino}:${e.mode}:${e.size}:${e.mtimeMs}:${e.ctimeMs}`;eh=e=>e.split("/").some(t=>t.toLowerCase()===".git"),th=(e,t)=>!t.has(e.path)&&!eh(e.path),Ht=e=>e.mode===Co;tc=e=>e.paths.filter(t=>!e.gitlinks.has(t)),mo=e=>e.filter(t=>!Ht(t)).map(t=>t.path);sh=e=>e.slice(0,5).map(t=>JSON.stringify(t)).join(", ")+(e.length>5?` and ${e.length-5} more`:"");yo=(e,t)=>({path:e,mode:Co,oid:t,size:0});Bd=e=>e==="120000"?"symlink":e===Co?"submodule":"file"});import{readFileSync as X0,renameSync as HE,rmSync as Z0,writeFileSync as GE}from"node:fs";async function es(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 hh(e,t){return!t||e.decision!=="allow"||!Q0.has(e.cause)?Promise.resolve():es(`gate_allow:${e.cause}`,t,{timeoutMs:500})}function fh(e,t=Date.now()){try{let n=Ut(e,ek),r=Date.parse(JSON.parse(X0(n,"utf8")).at??"");return Z0(n,{force:!0}),Number.isFinite(r)&&t-r>=0&&t-r<tk}catch{return!1}}var Q0,ek,tk,Ao=Z(()=>{"use strict";w();fe();Fe();Q0=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);ek="last-denial.json",tk=1440*60*1e3});import{randomUUID as nk}from"node:crypto";import{readdirSync as rk,readFileSync as ZE,renameSync as sk,rmSync as ph,statSync as ok,writeFileSync as ik}from"node:fs";import{dirname as gh,join as ak}from"node:path";import{gunzipSync as tO,gzipSync as ck}from"node:zlib";function mh(e,t,n){try{let r=Ut(e,uk(t)),s=`${r}.${nk()}.tmp`,o=ck(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:t,entries:n.map(i=>[i.path,i.mode,i.oid])})));try{ik(s,o,{flag:"wx",mode:384}),sk(s,r)}catch(i){throw ph(s,{force:!0}),i}for(let i of rk(gh(r))){if(!i.startsWith("tree-")||!i.endsWith(".json.gz"))continue;let a=ak(gh(r),i);try{Date.now()-ok(a).mtimeMs>lk&&ph(a,{force:!0})}catch{}}}catch{}}var lk,uk,ic=Z(()=>{"use strict";w();Fe();lk=720*60*60*1e3,uk=e=>`tree-${e}.json.gz`});import{createHash as dk}from"node:crypto";import{constants as yh}from"node:fs";import{open as hk}from"node:fs/promises";import{Readable as fk}from"node:stream";function To(e){if(!ac(e,Sh))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<=Xr.maxBundleBytes&&[e.baseTreeHash,e.treeHash,e.baseSha,e.headSha].every(n=>typeof n=="string"&&wh.test(n))&&ac(t,Ch)&&[t.headSha,t.baseSha].every(n=>n===null||typeof n=="string"&&wh.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 pk(e,t){return Sh.filter(n=>n!=="provenance").every(n=>e[n]===t[n])&&Ch.every(n=>e.provenance[n]===t.provenance[n])}function ts(e,t){if(!ac(e,["uploadId","expiresAt","status","source"])||typeof e.uploadId!="string"||!Ro.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)||!To(e.source)||t?.uploadId!==void 0&&t.uploadId!==e.uploadId||t?.manifest!==void 0&&!pk(t.manifest,e.source))throw new ke(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 Ah(e){if(!Ro.test(e))throw new ke(0,"invalid_upload_id","Canary's record of an earlier upload is invalid. Run the command again.");return`${xh}/${e}`}function gk(e,t){return e instanceof ke?new ke(e.status,e.code,e.message,e.fix,t):e instanceof L?new ke(e.status,"source_upload_failed",e.message,e.fix,t):new ke(0,"source_upload_failed",e instanceof Error?e.message:"The source upload failed.","Run the command again to continue the upload.",t)}function Io(e){if(e.status==="completed")return e;throw e.status==="cancelled"?new ke(410,"source_upload_cancelled","This upload was cancelled.",void 0,e.uploadId):new ke(409,"source_upload_in_progress","An earlier upload is still in progress.","Run the command again to continue it.",e.uploadId)}async function bh(e,t,n={}){let r=await(n.request??W)(Ah(e),{...t});return ts(r,{uploadId:e})}async function*Ih(e,t,n){let r=0;for(;r<t;){n?.throwIfAborted();let s=Buffer.allocUnsafe(Math.min(64*1024,t-r)),o=await e.read(s,0,s.length,r);if(!o.bytesRead)throw new ke(0,"source_changed","The source changed while it was being uploaded. Run the command again.");r+=o.bytesRead,yield s.subarray(0,o.bytesRead)}}async function kh(e,t,n){let r=await e.stat();if(!r.isFile()||r.size!==t.bytes)throw new ke(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.");let s=dk("sha256");for await(let i of Ih(e,t.bytes,n))s.update(i);let o=await e.stat();if(s.digest("hex")!==t.sha256||o.size!==r.size||o.mtimeMs!==r.mtimeMs||o.ctimeMs!==r.ctimeMs)throw new ke(0,"invalid_source_bundle","The captured source changed before it could be uploaded. Run the command again.")}async function vh(e,t,n,r){let s=fk.from(Ih(e,t.manifest.bytes,t.signal));try{let o=await(r.fetch??fetch)(`${t.baseUrl.replace(/\/+$/,"")}${Ah(n)}/content`,{method:"PUT",headers:{...(r.headers??Wt)(),authorization:`Bearer ${t.token}`,"content-type":"application/octet-stream","content-length":String(t.manifest.bytes)},body:s,duplex:"half",signal:t.signal,redirect:"error"});if(!o.ok){let i={};try{i=await o.json()}catch{}throw new ke(o.status,typeof i.code=="string"?i.code:"source_upload_failed",typeof i.error=="string"?i.error:o.statusText,typeof i.fix=="string"?i.fix:void 0,n)}return Io(ts(await o.json(),{uploadId:n,manifest:t.manifest}))}catch(o){throw o instanceof ke?o:new ke(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{s.destroy()}}async function Rh(e,t={}){if(!To(e.manifest)||!Ro.test(e.workspaceId)||!Ro.test(e.repositoryId))throw new ke(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},r;if(e.uploadId&&(r=ts(await bh(e.uploadId,n,t),{uploadId:e.uploadId,manifest:e.manifest}),r.status!=="pending"))return Io(r);let s=await hk(e.bundlePath,yh.O_RDONLY|yh.O_NOFOLLOW);try{if(await kh(s,e.manifest,e.signal),r||(r=ts(await(t.request??W)(xh,{...n,method:"POST",body:{workspaceId:e.workspaceId,repositoryId:e.repositoryId,source:e.manifest}}),{manifest:e.manifest})),e.onReceipt?.(r),r.status!=="pending")return Io(r);try{return await vh(s,e,r.uploadId,t)}catch(o){if(e.signal?.aborted||!(be(o)||o instanceof L&&o.status===409))throw o;let i=ts(await bh(r.uploadId,n,t),{uploadId:r.uploadId,manifest:e.manifest});return i.status!=="pending"?Io(i):(await kh(s,e.manifest,e.signal),await vh(s,e,r.uploadId,t))}}catch(o){throw r?gk(o,r.uploadId):o}finally{await s.close()}}var ke,xh,Ro,wh,Sh,Ch,ac,cc=Z(()=>{"use strict";w();fe();nt();Gt();ke=class extends L{constructor(n,r,s,o,i){super(n,s,o);this.code=r;this.uploadId=i;this.name="SourceUploadError"}},xh="/api/v1/cli/source-uploads",Ro=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,wh=/^[a-f0-9]{40}$/,Sh=["kind","version","sha256","bytes","baseTreeHash","treeHash","baseSha","headSha","provenance"],Ch=["headSha","branch","baseRef","baseSha","baselineMode"],ac=(e,t)=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))});import{createHash as mk,randomUUID as yk}from"node:crypto";import{readFileSync as wk,renameSync as bk,rmSync as Th,writeFileSync as kk}from"node:fs";function Eh(e,t,n,r="verify"){let s=mk("sha256").update(JSON.stringify([n,e,r])).digest("hex");return Ut(t,`source-upload-${s}.json`)}function Oh(e){try{let t=JSON.parse(wk(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 ke(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 ns(e,t,n,r){let s=Eh(e,t,n,r.requestKey),o=Oh(s);o&&(!r.uploadId||o.uploadId===r.uploadId)&&Th(s,{force:!0})}async function tr(e,t,n,r,s={}){let o=Eh(e.manifest,t,n,s.requestKey),i=s.fresh?void 0:Oh(o),a=i&&Date.parse(i.expiresAt)>Date.now()?i.uploadId:void 0,c=await Rh({bundlePath:e.bundlePath,manifest:e.manifest,workspaceId:t.workspaceId,repositoryId:n,token:r,baseUrl:t.apiUrl,...a?{uploadId:a}:{},onReceipt:({uploadId:l,expiresAt:d})=>{let u=`${o}.${yk()}.tmp`;try{kk(u,JSON.stringify({uploadId:l,expiresAt:d})+`
|
|
1700
|
+
`,{flag:"wx",mode:384}),bk(u,o)}finally{Th(u,{force:!0})}}});return{...c.source,uploadId:c.uploadId}}var Eo=Z(()=>{"use strict";w();Fe();cc()});import{readFileSync as $h}from"node:fs";function os(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(`
|
|
1701
|
+
`),do:Array.isArray(e.do)?e.do:[]}}function Ak(e){if(e===void 0)return;let t=e;try{e==="-"?t=$h(0,"utf8"):e.startsWith("@")&&(t=$h(e.slice(1),"utf8"))}catch(n){throw new bt("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 kt(e){return e==="P3"?null:e==="P0"||e==="P1"?e:"P2"}function Ik(e,t){if(kt(e.materiality)===null)return null;let r=t??null;return e.result==="fail"?{checkRunId:e.checkRunId,kind:"fail",proof:r?.isStatic===!1?"runtime":"source",headline:F(r?.finding?.headline)||F(e.title),summary:F(r?.verdict?.reasonOneLiner??r?.finding?.whatWasTested),location:Ph(r?.finding?.nextActionCodeRef??r?.codeRefs?.[0]),fix:F(r?.finding?.reproduce)||null}:e.result==="blocked"?{checkRunId:e.checkRunId,kind:"blocked",proof:"none",headline:F(e.title),summary:F(r?.verdict?.reasonOneLiner)||(is[e.blockedReason??""]??""),location:Ph(r?.checkReadback?.codeRefs?.[0]??r?.codeRefs?.[0]),fix:null}:null}function dc(e,t,n){let r=Q();W("/api/v1/cli/events",{method:"POST",...r?{token:r}:{},...n?{baseUrl:n}:{},body:{outcome:e,...t?{runId:t}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function Lh(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 hc(e,t,n={}){let r=u=>W(u,{token:t,...n.baseUrl?{baseUrl:n.baseUrl}:{}}),s=new Map,o="",i=new Set,a=!1,c=!1,l=null,d=Date.now();for(;;){let u;try{u=(await r(`/api/v1/red-team/runs/${e}`)).run,l=null}catch(f){if(be(f)&&(l??=Date.now(),Date.now()-l<vk)){n.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await rs(lc);continue}throw f}for(let f of u.stageC.checks)if(!(!(f.status==="completed"&&(f.result==="fail"||f.result==="blocked"))||s.has(f.checkRunId))){if(!st.test(f.checkRunId)){s.set(f.checkRunId,null);continue}try{s.set(f.checkRunId,await r(`/api/v1/red-team/runs/${e}/checks/${f.checkRunId}/finding`))}catch(m){be(m)||s.set(f.checkRunId,null)}}for(let f of u.stageC.checks){if(i.has(f.checkRunId)||!(f.status==="completed"||f.status==="failed"||f.status==="cancelled")||kt(f.materiality)===null)continue;i.add(f.checkRunId);let m=s.get(f.checkRunId),C=f.status!=="completed"?"!":f.result==="pass"?"\u2713":f.result==="fail"?"\u2717":"\u23F8",A=f.status!=="completed"?"errored":f.result==="pass"?"passed":f.result==="fail"?m?.isStatic===!1?"verified failure":"finding from the code":"could not verify";n.onProgress?.(`${C} ${A}: ${F(f.title)}`)}u.stageB.status!=="completed"&&(c=!0);let h=u.stageC.checks.length>0||u.stageB.finalChecksCount===0||uc.has(u.status);!a&&u.stageB.status==="completed"&&h&&(a=!0,n.onProgress?.(Tk(u,c?Date.now()-d:null,s)));let p=Rk(u);if(p!==o&&(n.onProgress?.(p),o=p),uc.has(u.status)){for(let g=0;g<3;g++){let m=u.stageC.checks.filter(C=>C.status==="completed"&&(C.result==="fail"||C.result==="blocked")&&!s.has(C.checkRunId));if(m.length===0)break;await rs(Math.min(lc,1e3));for(let C of m)try{s.set(C.checkRunId,await r(`/api/v1/red-team/runs/${e}/checks/${C.checkRunId}/finding`))}catch(A){(!be(A)||g===2)&&s.set(C.checkRunId,null)}}let f=u.stageC.checks.filter(g=>g.status==="completed"&&(g.result==="fail"||g.result==="blocked")).sort((g,m)=>Mh[kt(g.materiality)??"P2"]-Mh[kt(m.materiality)??"P2"]).map(g=>Ik(g,s.get(g.checkRunId)??null)).filter(g=>g!==null);return{run:u,findings:f}}if(Date.now()-d>Nh)throw new bt("still_running",`run ${e} is still ${u.status} after ${Math.round(Nh/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await rs(lc)}}function Rk(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 Tk(e,t,n=new Map){let r=e.stageC.checks.filter(u=>kt(u.materiality)!==null),s=u=>u.result==="fail"&&n.get(u.checkRunId)?.isStatic!==!1,o=r.filter(s).length,i=e.stageC.checks.filter(u=>u.status==="failed"||u.status==="cancelled").length,a=r.filter(u=>!s(u)&&u.status!=="failed"&&u.status!=="cancelled").length,c=e.stageC.results.pass+e.stageC.results.blocked+r.filter(u=>u.result==="fail"&&n.get(u.checkRunId)?.isStatic===!1).length,l=uc.has(e.status)?c>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 ${rt(o,"finding")} from the code \xB7 ${a} runtime check${a===1?"":"s"}${i?` \xB7 ${i} errored`:""} \xB7 ${l}`}function Ek(e,t,n){let r=e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns;if(Lh(e)===2)return`Verification did not complete (${e.status})${r?`: ${rt(r,"check")} errored`:""}; nothing was verified.`;let s=t.filter(d=>d.kind==="fail"&&d.proof==="runtime").length,o=t.filter(d=>d.kind==="fail"&&d.proof==="source").length,i=t.filter(d=>d.kind==="blocked").length,a=e.stageC.results.pass,c=[`${rt(s,"verified failure")}`,`${rt(a,"check")} passed`,`${rt(o,"finding")} from the code (source-reasoned, not run)`,...i?[`${i} could not be verified`]:[],`${rt(r,"check")} errored`],l=a===0&&s===0&&i===0&&r===0;return`${c.join("; ")}.${l?" Nothing in this change was executed.":""}${Ok(n)}`}function Ok(e){let t=e?e.reverifiable-e.carried:0;return!e||t<=0?"":` ${t} of run ${e.sourceRunId.slice(0,8)}'s ${rt(e.reverifiable,"failed check")} ${t===1?"was":"were"} not re-run (reported disputed or skipped).`}function $k(e,t){let n=e.slice(0,8);if(!t)return`re-checking the failed set of run ${n} \u2014`;let r=`of run ${n}'s ${rt(t.reverifiable,"failed check")}`;return t.excludedReported>0?`re-checking ${t.carried} ${r} (${t.excludedReported} reported disputed or skipped, not re-run) \u2014`:`re-checking all ${t.reverifiable} failed checks of run ${n} \u2014`}function fc(e,t,n,r){return{ok:!0,runId:e.runId,treeHash:t,status:e.status,findings:n,summary:Ek(e,n,r),failed:n.filter(s=>s.kind==="fail").length,passed:e.stageC.results.pass,blocked:n.filter(s=>s.kind==="blocked").length,errored:e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns,exitCode:Lh(e),failureMessage:e.failure?.publicMessage??null,...r?{reverify:r}:{}}}function pc(e){let t=[];if(t.push(`Receipt ${so(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(` ${rt(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(`
|
|
1702
|
+
`);let n=[e.failed?`\u2717 ${rt(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 r of e.findings)t.push(""),t.push(`${Nk[r.kind]} ${F(r.headline)}${_k[r.kind]}`),r.summary&&t.push(` ${F(r.summary)}`),r.location&&t.push(` \u2192 ${F(r.location)}`),r.fix&&t.push(` reproduce: ${F(r.fix)}`);return e.errored>0&&t.push(`
|
|
1684
1703
|
(${rt(e.errored,"check")} errored and could not be verified.)`),t.push(`
|
|
1685
1704
|
${e.summary}`),t.join(`
|
|
1686
|
-
`)}function
|
|
1705
|
+
`)}function as(e){let t=e;return!t||!["EPERM","EACCES","EROFS"].includes(t.code??"")||typeof t.path!="string"||!t.path.startsWith(K())?null:{message:`Canary keeps its records under ${K()} and cannot write there from here (${t.code})`,fix:"run the command outside the sandbox, or let it write under that folder"}}function D(e,t,n,r,s,o={}){if(e)console.log(JSON.stringify({ok:!1,error:t,message:n,...r?{fix:r}:{},exitCode:s,...o}));else{let i=typeof o.runId=="string"?o.runId:null;console.error(`\u2717 ${F(n)}${r?`
|
|
1687
1706
|
fix: ${F(r)}`:""}${i?`
|
|
1688
|
-
run: ${F(i)}`:""}`)}process.exitCode=s}async function
|
|
1689
|
-
${S.next}`);return}let C;try{C=await
|
|
1690
|
-
`).map(
|
|
1691
|
-
`).trim(),
|
|
1692
|
-
|
|
1693
|
-
`);
|
|
1694
|
-
`).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${
|
|
1695
|
-
`)}function
|
|
1696
|
-
${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}`:""}${
|
|
1697
|
-
`));return}if(e.plan){console.log(e.json?JSON.stringify({ok:!0,plan:s}):
|
|
1707
|
+
run: ${F(i)}`:""}`)}process.exitCode=s}async function jk(e,t,n,r,s={}){let o={baseUrl:s.baseUrl??ue()};Ke({cwd:e,agent:n,mode:r!==void 0?"reverify_failed":"full"});let i=(b,S,x,v=3,I={})=>{D(n,b,S,x,v,I),dc(`exit${v}:${b}`,I.runId,o.baseUrl)},a=Q();if(!a)return i("not_logged_in","Not logged in","run `canary login` first");if(r!==void 0&&!st.test(r))return i("bad_run_id",`"${r}" 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 c,l;try{c=Ak(t),l=await An(e,{baseRef:s.baseRef})}catch(b){if(b instanceof We||b instanceof bt)return i(b.code,b.message,b.fix);throw b}if(l.manifest.treeHash===l.manifest.baseTreeHash&&r===void 0)return await l.dispose(),i("nothing_to_verify","The current source matches the selected baseline","make a change, or choose a different baseline with --base <ref>");let d,u,h;try{d=await xn(e,a,o.baseUrl),u=await vn({...d,token:a});let b=AbortSignal.timeout(3e3);if((await po(d,a,b).catch(x=>{throw b.aborted?new L(0,"Checking this repository's setup timed out","run `canary verify` again"):x}))?.state!=="ready")throw new bt("setup_required",`This repository isn't set up for you in ${F(u.workspace.name)} yet`,"run `canary setup`");h=await tr(l,d,u.repositoryId,a,{fresh:!0}),mh(d,l.manifest.treeHash,l.entries)}catch(b){if(b instanceof re||b instanceof bt)return i(b.code,b.message,"fix"in b?b.fix:void 0);if(b instanceof L)return i("api_error",b.message,b.fix,b.status>=400&&b.status<500?3:2);throw b}finally{await l.dispose()}c===void 0&&r===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."),Yn();let p=b=>{n?console.error(` ${b}`):console.log(` ${b}`)};l.manifest.provenance.baselineMode==="whole-project"?p("No comparison branch found: reviewing the whole eligible project against an empty baseline."):p(`Baseline: ${F(l.manifest.provenance.baseRef)} \xB7 source ${so(l.manifest.treeHash)}`);let f,g,m;{let b,S=sc(l.manifest.provenance.branch),x=()=>W("/api/v1/cli/runs",{method:"POST",token:a,...o,body:{repositoryId:u.repositoryId,workspaceId:d.workspaceId,source:h,...c!==void 0?{brief:c}:{},...S?{branch:S}:{},...r!==void 0?{reverifySourceRunId:r}:{}}});try{for(let I=1;;I+=1)try{b=await x();break}catch($){if(I>=_h||!be($)||$ instanceof L&&$.runId&&st.test($.runId))throw $;p(`${$.message} \u2014 retrying (${I}/${_h-1})`),await rs(jh*I)}}catch(I){if(I instanceof L){let $=!be(I)&&I.status>=400&&I.status<500,y=I.fix??(I.status===401||I.status===403?"run `canary login`":$?void 0:"run `canary verify` again in a minute"),k={httpStatus:I.status,...I.runId?{runId:I.runId}:{}};return $?D(n,"api_error",I.message,y,3,k):i("api_error",I.message,y,2,k)}throw I}if(b.treeHash!==l.manifest.treeHash||b.headSha!==l.manifest.headSha)return D(n,"api_error","Canary's answer does not match the source that was uploaded","run `canary verify` again",2);if(!st.test(b.runId))return D(n,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);f=b.runId;let v=r?$k(r,b.reverify):b.created?"submitted":"same verification inputs as an existing run \u2014 following it:";p(`${v} ${so(l.manifest.treeHash)} \xB7 run ${f} \xB7 ${rt(l.files.length,"file")}`),g=b.reverify,m=b.created,m&&es(`started_by:${fh(d)?"hook":n||La().harness!=="unknown"?"skill":"manual"}`,{token:a,apiUrl:o.baseUrl},{runId:f})}if(s.noWait){let b=!1;if(r!==void 0&&!g&&!m)for(let x=0;x<3&&!g;x++)try{g=(await W(`/api/v1/red-team/runs/${f}`,{token:a,...o})).run.reverify;break}catch(v){if(!be(v)||x===2){b=!0;break}await rs(jh*(x+1))}let S={ok:!0,runId:f,runUrl:Sk(f),treeHash:l.manifest.treeHash,created:m,...g?{reverify:g}:{},next:`${Ck(f)}${b?" What this re-check carried could not be read just now; the document from `canary run wait` will say.":""}`};console.log(n?JSON.stringify(S):`Run ${f} is under way: ${S.runUrl}
|
|
1708
|
+
${S.next}`);return}let C;try{C=await hc(f,a,{...o,onProgress:p})}catch(b){if(b instanceof bt)return i(b.code,b.message,b.fix,2,{runId:f});if(b instanceof L){let S=b.status===401||b.status===403;return i("api_error",`${b.message} \u2014 run ${f} may still be running`,b.fix??(S?"run `canary login`, then run `canary verify` again to resume it":"run `canary verify` again to resume it"),2,{runId:f,httpStatus:b.status})}throw b}let A={...fc(C.run,l.manifest.treeHash,C.findings,g),source:l.manifest,repositoryId:u.repositoryId};console.log(n?JSON.stringify(A):pc(A)),process.exitCode=A.exitCode}function Fh(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(()=>(In(),Dh))).installByDefault({json:t.json===!0}),await jk(t.dir??process.cwd(),t.brief,t.json===!0,t.failed,{baseRef:t.base,noWait:t.wait===!1})}catch(n){let r=as(n);if(r){D(t.json===!0,"home_not_writable",r.message,r.fix,2),dc("exit2:home_not_writable");return}D(t.json===!0,"internal_error",n instanceof Error?n.message:String(n),void 0,2),dc("exit2:internal_error")}})}var lc,vk,Nh,uc,bt,F,xk,$t,ss,st,Sk,Ck,rs,_h,jh,Ph,Mh,is,Nk,_k,rt,Jt=Z(()=>{"use strict";w();fe();nt();ee();kd();zr();Fe();Gt();Ao();ic();Eo();mn();lc=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,vk=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,Nh=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,uc=new Set(["completed","failed","cancelled"]),bt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="VerifyError"}},F=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ").trim(),xk=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ").trimEnd(),$t=e=>e.split(`
|
|
1709
|
+
`).map(xk).join(`
|
|
1710
|
+
`).trim(),ss=e=>e.map($t).filter(t=>t!=="").join(`
|
|
1711
|
+
|
|
1712
|
+
`);st=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Sk=e=>`${Tt().replace(/\/+$/,"")}/runs/${e}`,Ck=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).`,rs=e=>new Promise(t=>setTimeout(t,e)),_h=3,jh=1e3;Ph=e=>e?e.startLine?`${e.file}:${e.startLine}`:e.file:null;Mh={P0:0,P1:1,P2:2},is={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"};Nk={fail:"\u2717",blocked:"\u23F8"},_k={fail:"",blocked:" (could not be verified)"},rt=(e,t)=>`${e} ${t}${e===1?"":"s"}`});var Dh={};_i(Dh,{hooksStatus:()=>cs,installByDefault:()=>ls,pendingPushCheck:()=>yc,registerHooks:()=>wc,runHooksInstall:()=>qh,runHooksUninstall:()=>Hh,statusLines:()=>Oo});function mc(e,t=[]){try{Ne(n=>({...n,hooks:{...n.hooks?.codex?{codex:n.hooks.codex}:{},state:e,at:new Date().toISOString(),...t.length?{refused:t}:{}}}))}catch{}}function Pk(e){return[gc,"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(`
|
|
1713
|
+
`).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${Wh}`].join(`
|
|
1714
|
+
`)}function Uh(e){for(let t of e)t.result==="refused"?console.log(`\u2717 ${t.file} was left alone: ${t.detail}. To do it by hand:
|
|
1715
|
+
${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}`:""}${Bh(t.edit?.backup??t.removed?.backup)}`)}function Mk(e,t){for(let n of t)n.afterInstall&&e.some(r=>r.harness===n.id&&r.result==="written")&&console.log(`${n.label}: ${n.afterInstall}`);Qs("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")&&wn()==="off"&&console.log("The check itself is switched off (`canary gate on` turns it on).")}function Lk(e,t){return t?.length?{targets:e.filter(n=>t.includes(n.id)&&n.detected()),unknown:t.filter(n=>!e.some(r=>r.id===n&&r.detected()))}:{targets:e.filter(n=>n.byDefault&&n.detected()),unknown:[]}}async function qh(e){let t=e.targets??Gr(),{targets:n,unknown:r}=Lk(t,e.harnesses),s=n.flatMap(i=>i.plan());if(r.length)return D(e.json,"harness_not_found",`not found on this machine: ${r.join(", ")}`,`known: ${t.map(i=>i.id).join(", ")}; one counts as found once its settings folder exists`,3);if(!n.length){let i=t.filter(a=>!a.byDefault&&a.detected()).map(a=>`\`canary hooks install --harness ${a.id}\` registers ${a.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(a=>a.byDefault).map(a=>a.label).join(", ")}).`,...i].join(`
|
|
1716
|
+
`));return}if(e.plan){console.log(e.json?JSON.stringify({ok:!0,plan:s}):Pk(s));return}let o=n.flatMap(i=>i.install());o.some(i=>i.result!=="refused")&&mc("installed"),e.json?console.log(JSON.stringify({ok:!o.some(i=>i.result==="refused"),outcomes:o,canaryOnPath:Qs("canary"),mode:wn(),notes:n.filter(i=>i.afterInstall&&o.some(a=>a.harness===i.id&&a.result==="written")).map(i=>`${i.label}: ${i.afterInstall}`)})):(Uh(o),Mk(o,n)),o.some(i=>i.result==="refused")&&(process.exitCode=2)}function Hh(e){let t=(e.targets??Gr()).flatMap(n=>n.uninstall());mc("removed"),e.json?console.log(JSON.stringify({ok:!t.some(n=>n.result==="refused"),outcomes:t})):Uh(t),t.some(n=>n.result==="refused")&&(process.exitCode=2)}function cs(e=Gr()){return{mode:wn(),registration:V().hooks?.state??null,canaryOnPath:Qs("canary"),harnesses:e.map(t=>({harness:t.id,label:t.label,detected:t.detected(),items:t.status()}))}}function yc(e){try{return wn()==="off"?[]:cs(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 Oo(e){let t=[];for(let n of e.harnesses){if(!n.detected&&n.items.every(r=>r.state==="missing")){t.push(`${n.label}: not found on this machine`);continue}for(let r of n.items)t.push(`${n.label}: ${r.state==="registered"?"registered":r.state==="untrusted"?"registered, not yet trusted":r.state==="missing"?"not registered":r.state} (${r.file})${r.detail?`: ${r.detail}`:""}`)}return e.harnesses.some(n=>n.items.some(r=>r.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(r=>r.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 ls(e){try{if(process.env.CI||!e.targets&&process.env.NODE_TEST_CONTEXT)return;let t=V();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 r=(e.targets??Gr()).filter(u=>u.byDefault&&u.detected());if(!r.length)return;let s=r.flatMap(u=>u.install()),o=s.filter(u=>u.result==="written"),i=s.filter(u=>u.result==="refused"&&!n.has(u.file)),a=s.filter(u=>u.result==="refused").map(u=>u.file);if(s.some(u=>u.result!=="refused")||t.hooks?.state==="installed")mc("installed",a);else if(a.length)try{Ne(u=>({...u,hooks:{...u.hooks,refused:a}}))}catch{}let c=r.filter(u=>u.afterInstall&&o.some(h=>h.harness===u.id)).map(u=>`${u.label}: ${u.afterInstall}`),l=o.filter(u=>!u.edit),d=o.filter(u=>u.edit);if(e.json){(o.length||i.length)&&console.error(JSON.stringify({notice:"push_check",added:o.map(u=>u.file),leftAlone:i.map(u=>({file:u.file,why:u.detail})),...d.length?{edits:d.map(u=>({file:u.file,line:u.edit.line,text:u.edit.text,backup:u.edit.backup,created:u.edit.created}))}:{},message:gc,off:"canary gate off",remove:"canary hooks uninstall",notes:c}));return}if(l.length){let u=r.filter(h=>l.some(p=>p.harness===h.id)).map(h=>h.label).join(" and ");console.error(`
|
|
1698
1717
|
Canary added its push check to ${u} (${l.map(h=>h.file).join(", ")}).
|
|
1699
|
-
${
|
|
1700
|
-
${
|
|
1718
|
+
${gc}
|
|
1719
|
+
${Wh}`)}for(let u of d)console.error(`Canary ${u.edit.created?"created":"edited"} ${u.file}: ${u.detail}${Bh(u.edit.backup)}. \`canary hooks uninstall\` takes it out again.`);for(let u of c)console.error(u);for(let u of i)console.error(`Canary left ${u.file} alone (${u.detail}): not added there: ${u.summary}. \`canary hooks install --plan\` shows what to add by hand.`)}catch{}}function wc(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 qh({plan:n.plan===!0,json:n.json===!0,harnesses:n.harness})}catch(r){D(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),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{Hh({json:n.json===!0})}catch(r){D(n.json===!0,"internal_error",r instanceof Error?r.message:String(r),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 r=cs();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(`The push check is ${r.mode}.`);for(let s of Oo(r))console.log(s)}})}var gc,Wh,Bh,In=Z(()=>{"use strict";w();ee();ro();Sa();Jt();gc="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.",Wh="Switch it off: `canary gate off` \xB7 take it out: `canary hooks uninstall`.";Bh=e=>e?` (the file as it was: ${e})`:""});w();w();var su=Ny(ru(),1),{program:aR,createCommand:cR,createArgument:lR,createOption:uR,CommanderError:dR,InvalidArgumentError:hR,InvalidOptionArgumentError:fR,Command:ou,Argument:pR,Option:iu,Help:gR}=su.default;w();Ea();to();fe();mn();ee();In();Fe();import{createHash as Vk,randomBytes as sf}from"node:crypto";import{spawn as Kk}from"node:child_process";import{createServer as zk}from"node:http";w();fe();zr();function Gh(e){try{return new URL(e).href.replace(/\/+$/,"")}catch{return}}var bc=Dd;async function Jh(e,t,n,r){let s=await W("/api/v1/cli/workspaces",{token:e.token,baseUrl:r,signal:AbortSignal.timeout(3e3)});if(!Array.isArray(s?.workspaces)||s.workspaces.some(u=>!u||typeof u.id!="string"||!u.id||typeof u.name!="string"))throw new Error("The service returned an invalid workspace list. Run canary login again.");let o=[...new Map(s.workspaces.map(({id:u,name:h})=>[u,{id:u,name:h}])).values()],a=t.user?.id===e.user.id&&Gh(n)===Gh(r)?o.find(u=>u.id===t.team?.id):void 0,c=o.length===1?o[0]:void 0,l=a??c??o.find(u=>u.id===e.team.id)??o[0]??{id:"",name:"No workspace selected"},d=bc();return{workspace:l,workspaces:o,source:a?"saved in CLI":c?"only workspace":"active on platform",selectionRequired:!a&&!c,...d?{repository:d}:{},...o.length?{}:{workspaceNotice:"Create or join a workspace in Canary, then run canary login again."}}}async function $o(e,t,n,r=AbortSignal.timeout(3e3)){try{let s=await po({apiUrl:e.apiUrl,userId:e.userId,workspaceId:n},e.token,r);return s?{state:s.state}:void 0}catch{return}}function No(e,t){let n=/^\d+$/.test(t)?Number(t)-1:-1,r=n>=0?e.workspaces.filter((s,o)=>o===n):e.workspaces.filter(s=>s.id===t||s.name.toLowerCase()===t.toLowerCase());if(r.length!==1)throw new Error(r.length?"Workspace name is ambiguous. Use its ID.":"Workspace not found. Run canary workspace list.");return r[0]}w();w();import{stripVTControlCharacters as Yh}from"node:util";var ve="\x1B[";function ds(e,t,n){let r={gold:"38;2;255;212;0",text:"39",muted:"90",green:"32"}[t];return n?`${ve}${r}m${e}${ve}0m`:e}function ie(e){return Yh(e).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var kc=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Vh(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 us(e){return[...kc.segment(Yh(e))].reduce((t,n)=>t+Vh(n.segment),0)}function _o(e,t){let n=0,r="";for(let s of e.split(/(\x1b\[[0-9;]*m)/)){if(s.startsWith(ve)){r+=s;continue}for(let{segment:o}of kc.segment(s))n+=Vh(o),n<=t&&(r+=o)}return r}function Yt(e,t){let n=[],r="";for(let s of ie(e).split(/\s+/)){r&&us(r+" "+s)>t&&(n.push(r),r="");for(let{segment:o}of kc.segment((r?" ":"")+s))us(r+o)>t&&r&&(n.push(r),r=""),r+=o}return r&&n.push(r),n}function nr(e){let t=[];return{render(n){if(n.join(`
|
|
1701
1720
|
`)===t.join(`
|
|
1702
|
-
`))return;let r=Math.max(2,e.columns||80),s=Math.max(3,e.rows||24),o=Math.min(s-1,t.reduce((i,a)=>i+Math.max(1,Math.ceil(
|
|
1721
|
+
`))return;let r=Math.max(2,e.columns||80),s=Math.max(3,e.rows||24),o=Math.min(s-1,t.reduce((i,a)=>i+Math.max(1,Math.ceil(us(a)/r)),0));e.write((o?`\r${ve}${o}A`:"")+`${ve}0J`+(n.length?n.join(`\r
|
|
1703
1722
|
`)+`\r
|
|
1704
|
-
`:"")),t=n}}}function
|
|
1723
|
+
`:"")),t=n}}}function Kh(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:
|
|
1705
1724
|
`:" ")+n+`
|
|
1706
|
-
`]}function Vh(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 jo(e){return`Repository ${ie(e)}`}var Rn="Next: in your coding agent, type /canary to check your changes.";function Kh(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}w();import{stripVTControlCharacters as Lk}from"node:util";w();var rr=[[" "," \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 ds="\x1B[",Fk={gold:"33",text:"39",muted:"90",green:"32"};function Dk(e,t,n){if(!n)return e;let r=t==="gold"?"38;2;255;212;0":Fk[t];return`${ds}${r}m${e}${ds}0m`}function zh(e){return Lk(e).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var Xh=1.4;function Wk(e){let{phase:t,seconds:n,columns:r,rows:s,color:o,open:i}=e,a=e.phaseSeconds??n,c=1.4,d=n%(c+.2),u=b=>Math.sin(b/c*Math.PI*2)*Math.sin(b/c*Math.PI),h=t==="waiting"&&d<c?u(d):t==="success"&&a<Xh?u(a):0,p=rr[Math.max(0,Math.min(16,Math.round(h*10)+8))],f=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",g=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.":i&&n<1.5?"Opening your browser...":"Finish signing in at the link above.",m=(b,S="text")=>Dk(b,S,o),C=t==="success"?"green":t==="failed"?"muted":"gold",A;if(s<5)A=[m(f)];else if(r>=72&&s>=18){let b={1:m("CANARY","gold"),3:m(f,t==="success"?"green":"text"),5:m(g,"muted")};A=["",...p.map((S,x)=>` ${m(S,C)} ${b[x]??""}`)]}else r>=42&&s>=23?A=["",...p.map(b=>` ${m(b,C)}`),` ${m("CANARY","gold")}`,"",` ${m(f)}`,` ${m(g,"muted")}`]:A=["",` ${m("CANARY","gold")}`,` ${m(f)}`];return s>=10&&(A.push("",` ${m("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(t==="waiting"||t==="saving")&&A.push(` ${m("Ctrl+C","muted")} ${m("cancel sign-in","muted")}`),A.push("")),A.slice(0,Math.max(1,s-2)).map(b=>{let S=0;return b.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,x=>x.startsWith("\x1B")||++S<r?x:"")})}function Zh(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,r=performance.now(),s="waiting",o=r,i=m=>{s=m,o=performance.now()},a=nr(t),c=!1;function l(){if(c)return;let m=Math.max(2,t.columns||80),C=Math.max(3,t.rows||24),A=performance.now(),b=Wk({phase:s,seconds:(A-r)/1e3,phaseSeconds:(A-o)/1e3,columns:m,rows:C,color:n,open:e.open});a.render(b)}let d=()=>t.write(`${ds}0m${ds}?25h`);function u(){c||(c=!0,clearInterval(g),t.removeListener("resize",l),process.removeListener("SIGINT",p),process.removeListener("SIGTERM",f),process.removeListener("exit",d),d())}function h(m){i("failed"),l(),u(),t.write(`Sign-in cancelled.
|
|
1707
|
-
`),process.exit(m)}let p=()=>h(130),f=()=>h(143),g=setInterval(l,80);return g.unref(),t.on("resize",l),process.once("SIGINT",p),process.once("SIGTERM",f),process.once("exit",d),t.write(`${
|
|
1708
|
-
Workspace ${
|
|
1725
|
+
`]}function zh(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 jo(e){return`Repository ${ie(e)}`}var Rn="Next: in your coding agent, type /canary to check your changes.";function Xh(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}w();import{stripVTControlCharacters as Fk}from"node:util";w();var rr=[[" "," \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 hs="\x1B[",Dk={gold:"33",text:"39",muted:"90",green:"32"};function Wk(e,t,n){if(!n)return e;let r=t==="gold"?"38;2;255;212;0":Dk[t];return`${hs}${r}m${e}${hs}0m`}function Zh(e){return Fk(e).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var Qh=1.4;function Bk(e){let{phase:t,seconds:n,columns:r,rows:s,color:o,open:i}=e,a=e.phaseSeconds??n,c=1.4,d=n%(c+.2),u=b=>Math.sin(b/c*Math.PI*2)*Math.sin(b/c*Math.PI),h=t==="waiting"&&d<c?u(d):t==="success"&&a<Qh?u(a):0,p=rr[Math.max(0,Math.min(16,Math.round(h*10)+8))],f=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",g=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.":i&&n<1.5?"Opening your browser...":"Finish signing in at the link above.",m=(b,S="text")=>Wk(b,S,o),C=t==="success"?"green":t==="failed"?"muted":"gold",A;if(s<5)A=[m(f)];else if(r>=72&&s>=18){let b={1:m("CANARY","gold"),3:m(f,t==="success"?"green":"text"),5:m(g,"muted")};A=["",...p.map((S,x)=>` ${m(S,C)} ${b[x]??""}`)]}else r>=42&&s>=23?A=["",...p.map(b=>` ${m(b,C)}`),` ${m("CANARY","gold")}`,"",` ${m(f)}`,` ${m(g,"muted")}`]:A=["",` ${m("CANARY","gold")}`,` ${m(f)}`];return s>=10&&(A.push("",` ${m("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(t==="waiting"||t==="saving")&&A.push(` ${m("Ctrl+C","muted")} ${m("cancel sign-in","muted")}`),A.push("")),A.slice(0,Math.max(1,s-2)).map(b=>{let S=0;return b.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,x=>x.startsWith("\x1B")||++S<r?x:"")})}function ef(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,r=performance.now(),s="waiting",o=r,i=m=>{s=m,o=performance.now()},a=nr(t),c=!1;function l(){if(c)return;let m=Math.max(2,t.columns||80),C=Math.max(3,t.rows||24),A=performance.now(),b=Bk({phase:s,seconds:(A-r)/1e3,phaseSeconds:(A-o)/1e3,columns:m,rows:C,color:n,open:e.open});a.render(b)}let d=()=>t.write(`${hs}0m${hs}?25h`);function u(){c||(c=!0,clearInterval(g),t.removeListener("resize",l),process.removeListener("SIGINT",p),process.removeListener("SIGTERM",f),process.removeListener("exit",d),d())}function h(m){i("failed"),l(),u(),t.write(`Sign-in cancelled.
|
|
1726
|
+
`),process.exit(m)}let p=()=>h(130),f=()=>h(143),g=setInterval(l,80);return g.unref(),t.on("resize",l),process.once("SIGINT",p),process.once("SIGTERM",f),process.once("exit",d),t.write(`${hs}?25l`),l(),{saving(){i("saving"),l()},celebrate(){return i("success"),l(),new Promise(m=>setTimeout(m,Qh*1e3+100))},succeed(m,C){i("success"),l(),u(),process.stdout.write(` Account ${Zh(m)}
|
|
1727
|
+
Workspace ${Zh(C)}
|
|
1709
1728
|
|
|
1710
|
-
`)},fail(){i("failed"),l(),u()},clear(){a.render([]),u()},stop:u}}w();import{spawn as
|
|
1729
|
+
`)},fail(){i("failed"),l(),u()},clear(){a.render([]),u()},stop:u}}w();import{spawn as Uk}from"node:child_process";import{createInterface as qk,emitKeypressEvents as Hk}from"node:readline";function vc(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 xc(e){return e.workspaces.length>1}function Gk(e){return!e||e.result==="skipped"?null:e.result==="refused"?`Not added \xB7 ${e.detail}`:"Added \xB7 new Claude Code chats load it"}var tf="/canary";async function nf(e){let t=process.stdin,n=process.stderr,r=t.readableFlowing===!0;n.write(`Choose a workspace:
|
|
1711
1730
|
`),e.workspaces.forEach((i,a)=>{let c=e.workspaces.some(l=>l.id!==i.id&&l.name===i.name);n.write(` ${a+1}. ${ie(i.name)}${c?` (${ie(i.id)})`:""}
|
|
1712
|
-
`)});let s=
|
|
1713
|
-
Workspace (number or name): `)}}finally{process.off("SIGINT",o),s.close(),r||t.pause()}}function
|
|
1731
|
+
`)});let s=qk({input:t,output:n,terminal:!1}),o=()=>s.close();process.once("SIGINT",o);try{n.write("Workspace (number or name): ");for await(let i of s)try{return No(e,i.trim())}catch(a){n.write(`${a instanceof Error?a.message:"Choose a listed workspace."}
|
|
1732
|
+
Workspace (number or name): `)}}finally{process.off("SIGINT",o),s.close(),r||t.pause()}}function Jk(e,t,n,r){let{context:s}=e,o=Math.max(1,t-5),i=(h,p="text")=>ds(ie(h),p,r),a=(h="",p="text")=>` ${i(h,p)}`,c=[];if(t>=90&&n>=36&&!e.picker){let h={1:i("CANARY","gold"),3:i("You're connected."),5:i("Let's give your agent the next step.","muted")};c.push("",...rr[8].map((p,f)=>` ${i(p,"green")} ${h[f]??""}`),"")}else c.push(a("CANARY","gold"),a("You're connected."),"");if(c.push(a(`Account ${ie(e.email)}`)),c.push(a(`Workspace ${s.selectionRequired?"Choose below":ie(s.workspace.name)}`)),c.push(a(` ${s.source}${!e.done&&xc(s)?" \xB7 [w] Change":""}`,"muted")),e.picker){c.push("",a("Choose a workspace","gold"));let h=Math.max(1,Math.min(8,n-c.length-5)),p=Math.max(0,Math.min(e.highlighted-Math.floor(h/2),s.workspaces.length-h));for(let f=p;f<Math.min(p+h,s.workspaces.length);f++){let g=s.workspaces[f],C=s.workspaces.some(b=>b.id!==g.id&&b.name===g.name)?` \xB7 ${ie(g.id)}`:"",A=!s.selectionRequired&&g.id===s.workspace.id?" \xB7 current":"";c.push(a(`${f===e.highlighted?"\u203A":" "} ${f+1}. ${ie(g.name)}${C}${A}`,f===e.highlighted?"gold":"text"))}c.push(a(`${e.highlighted+1} of ${s.workspaces.length}`,"muted"),"",a("\u2191 \u2193 choose \xB7 number highlight \xB7 Enter select \xB7 Esc back","muted"))}else{let h=s.repository?ie(s.repository):void 0;c.push(a(h?`Repository ${h}`:"Repository Open a local Git repository to continue")),c.push(a(`Agent skill ${vc(e.skill)}`,e.skill&&vc(e.skill).startsWith("Installed")?"green":"muted"));let p=Gk(e.plugin);p&&c.push(a(`Plugin ${p}`,e.plugin?.result==="refused"?"muted":"green")),s.workspaceNotice&&c.push(...Yt(s.workspaceNotice,o).map(g=>a(g,"muted"))),c.push("",a("\u2500".repeat(Math.min(68,o)),"muted"),a("NEXT \xB7 CHECK A CHANGE","gold"));let f=!!e.skill&&vc(e.skill).startsWith("Installed");c.push(a(f?"In your coding agent, type:":"In your coding agent, run canary skills, then type:","muted")),c.push(...Yt(tf,o-2).map(g=>a(`\u2502 ${g}`))),e.done||c.push("",a(`${xc(s)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),e.message&&c.push(...Yt(e.message,o).map(g=>a(g,"muted"))),c.push("",a("Signed in","green"))}let d=Math.max(1,n-2);return(d<=3?c.slice(0,d):c.length>d?[...c.slice(0,Math.max(0,d-3)),...c.slice(-3)]:c).map(h=>_o(h,Math.max(1,t-1)))}async function Yk(e,t){let n=process.platform==="darwin"?[["pbcopy"]]:process.platform==="win32"?[["clip.exe"]]:[["wl-copy"],["xclip","-selection","clipboard"],["xsel","--clipboard","--input"]];for(let[r,...s]of n){if(t.aborted)return!1;if(await new Promise(i=>{let a=Uk(r,s,{stdio:["pipe","ignore","ignore"],signal:t}),c=setTimeout(()=>{a.kill(),i(!1)},1e3),l=d=>{clearTimeout(c),i(d)};a.on("error",()=>l(!1)),a.on("close",d=>l(d===0)),a.stdin.on("error",()=>{}),a.stdin.end(e)}))return!0}return!1}async function rf(e){let t=process.stdin,n=process.stderr,r={...e,picker:e.context.workspaces.length>1,highlighted:Math.max(0,e.context.workspaces.findIndex(h=>h.id===e.context.workspace.id))},s=!process.env.NO_COLOR,o=nr(n),i=()=>o.render(Jk(r,n.columns||80,n.rows||24,s));if(!t.isTTY||!n.isTTY||(n.rows||24)<16||(n.columns||80)<30){r.done=!0,i(),n.write(`
|
|
1714
1733
|
${Rn}
|
|
1715
1734
|
`);return}let a=t.isRaw,c=t.readableFlowing===!0,l=new AbortController,d=!1,u;await new Promise(h=>{function p(){if(d)return;d=!0,l.abort(),t.off("keypress",C),t.off("end",p),n.off("resize",m),process.off("SIGINT",p),process.off("SIGTERM",g),process.off("exit",f),r.picker=!1,r.done=!0,r.message=void 0;let A=e.sessionCurrent();A?i():o.render(["CLI session changed in another process. Run canary whoami to check the active account."]),f(),A&&!r.context.selectionRequired&&n.write(`
|
|
1716
1735
|
${Rn}
|
|
1717
1736
|
|
|
1718
|
-
`),h()}function f(){t.setRawMode(a),c||t.pause(),n.write(`${ve}0m${ve}?25h`)}function g(){process.exitCode=143,p()}function m(){(n.rows||24)<16||(n.columns||80)<30?p():i()}function C(A,b){if(!(!b||d)){if(!e.sessionCurrent()){p();return}if(b.ctrl&&["c","d"].includes(b.name??"")){p();return}if(!(b.ctrl||b.meta)){if(r.picker){let S=r.context.workspaces.length;if(b.name==="escape"){if(r.context.selectionRequired){p();return}r.picker=!1}else if(/^[1-9]$/.test(b.sequence??"")&&Number(b.sequence)<=S)r.highlighted=Number(b.sequence)-1;else if(b.name==="up")r.highlighted=(r.highlighted+S-1)%S;else if(b.name==="down")r.highlighted=(r.highlighted+1)%S;else if(b.name==="return"){let x=r.context.workspaces[r.highlighted];try{e.selectWorkspace(x),r.context={...r.context,workspace:x,source:"selected in CLI",selectionRequired:!1},r.picker=!1,r.message="Workspace saved for future CLI commands."}catch{if(!e.sessionCurrent()){p();return}r.picker=!1,r.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(b.name??"")){p();return}else if(b.name==="w"&&vc(r.context))r.picker=!0,r.highlighted=Math.max(0,r.context.workspaces.findIndex(S=>S.id===r.context.workspace.id));else if(b.name==="c"&&!u){let S=new AbortController;u=S,l.signal.addEventListener("abort",()=>S.abort(),{once:!0}),Jk(Qh,S.signal).then(x=>{u===S&&(u=void 0),!d&&(r.message=x?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",i())})}i()}}}Hk(t),t.setRawMode(!0),t.resume(),t.on("keypress",C),t.once("end",p),n.on("resize",m),process.once("SIGINT",p),process.once("SIGTERM",g),process.once("exit",f),n.write(`${ve}?25l`),i()})}var zk=900*1e3,Xk=6e4;var rf=e=>e.toString("base64url");function Zk(e){let t=process.platform,[n,r]=t==="darwin"?["open",[e]]:t==="win32"?["explorer.exe",[e]]:["xdg-open",[e]];try{let s=Vk(n,r,{stdio:"ignore",detached:!0});s.on("error",()=>{}),s.unref()}catch{}}function Qk(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 ev(e){return new Promise((t,n)=>{let r,s,o=new Promise((l,d)=>{r=l,s=d}),i=Kk((l,d)=>{let u=new URL(l.url??"/","http://127.0.0.1"),h=(g,m,C)=>{d.writeHead(C,{"content-type":"text/html",connection:"close"}),d.end(Qk(g,m))};if(u.pathname!=="/callback"){d.writeHead(404,{connection:"close"}),d.end("not found");return}if(u.searchParams.get("state")!==e){h("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let p=u.searchParams.get("error");if(p){h("Authorization failed","You can close this tab and return to your terminal.",400),s(new Error(`authorization failed: ${p}`));return}let f=u.searchParams.get("code");if(!f){h("Authorization failed","No authorization code was returned. Please run canary login again.",400),s(new Error("callback returned no code"));return}h("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),r(f)}),a=setTimeout(()=>s(new Error("timed out waiting for browser authorization")),zk);a.unref?.();let c=()=>{clearTimeout(a),i.closeAllConnections?.(),i.close()};o.then(c,c),i.on("error",l=>{clearTimeout(a),n(l)}),i.listen(0,"127.0.0.1",()=>{t({port:i.address().port,code:o,close:c})})})}async function tv(e,t){let n=V(),r=n.apiUrl||ue(),s=(t.apiUrl||ue()).replace(/\/+$/,""),o=rf(nf(32)),i=Yk("sha256").update(o).digest("base64url"),a=rf(nf(16)),{port:c,code:l,close:d}=await ev(a),u=`http://127.0.0.1:${c}/callback`,h=(t.webUrl||Tt()).replace(/\/+$/,""),p=`${h}/cli/authorize?challenge=${encodeURIComponent(i)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(u)}`;for(let C of Yh(e,t.open,p))console.error(C);let f=Zh({json:e,animation:t.animation,open:t.open}),g=Date.now(),m=f?void 0:setInterval(()=>console.error(Vh(e,Math.round((Date.now()-g)/1e3))),Xk);m?.unref?.();try{t.open&&Zk(p);let C=await l;m&&clearInterval(m),f?.saving();let A=await B("/api/v1/cli/auth/token",{method:"POST",body:{code:C,codeVerifier:o},baseUrl:s});return f&&await f.celebrate(),f?.clear(),await of(A,n,r,s,e,{webUrl:h,agentSkills:t.agentSkills,workspace:t.workspace,interactive:!!f&&!!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(C){throw f?.fail(),C}finally{m&&clearInterval(m),f?.stop(),d()}}async function of(e,t,n,r,s,o){Ne(({team:g,...m})=>({...m,token:e.token,user:e.user,apiUrl:r,...o.webUrl?{webUrl:o.webUrl}:{},agentSkills:o.agentSkills}),{overwriteUnreadable:!0}),ho();let i=await qh(e,t,n,r);o.workspace!==void 0&&(i.workspace=No(i,o.workspace),i.source="selected in CLI",i.selectionRequired=!1),i.selectionRequired||Ne(g=>({...g,team:i.workspace}));let a=o.agentSkills?Gr():void 0,c=o.agentSkills?Ra():void 0,l=()=>{let g=V();return g.token===e.token&&g.apiUrl===r},d=g=>{Ne(m=>{if(m.token!==e.token||m.apiUrl!==r)throw new Error("CLI session changed");return{...m,team:g}}),i.selectionRequired=!1},u=i.repository?g=>$o({token:e.token,apiUrl:r,userId:e.user.id},i.repository,g):void 0;if(!i.selectionRequired&&u&&(i.repositoryState=(await u(i.workspace.id))?.state),o.interactive&&i.workspaces.length)await tf({email:e.user.email,context:i,skill:a,plugin:c,selectWorkspace:d,sessionCurrent:l});else if(o.promptWorkspace&&i.selectionRequired&&i.workspaces.length){console.error(`Signed in as ${ie(e.user.email)}.`);let g=await ef(i);g&&(d(g),i.workspace=g,i.source="selected in CLI",u&&(i.repositoryState=(await u(g.id))?.state))}if(!l())throw new Error("CLI session changed in another process. Run canary whoami.");let h=!process.exitCode,p=V().team;if(!p){let g=i.workspaces.length?"workspace_selection_required":"workspace_required",m=i.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${Tt()}, then run canary login.`;return s?console.log(JSON.stringify({ok:!1,authenticated:!0,error:g,user:e.user,workspaces:i.workspaces,fix:m})):(console.log(`Signed in as ${ie(e.user.email)}. Select a workspace to continue.`),i.workspaces.forEach((C,A)=>console.log(` ${A+1}. ${ie(C.name)} (${ie(C.id)})`)),console.log(m)),process.exitCode=1,h}let f=i.repository?{name:i.repository,state:i.repositoryState}:void 0;if(s)console.log(JSON.stringify({ok:!0,user:e.user,team:p,workspace:p,...f?{repository:f}:{}}));else if(!o.interactive){console.log(`Logged in as ${ie(e.user.email)} (${ie(p.name??p.id)}).`),f&&console.log(jo(f.name));for(let g of[a&&nv(a),Kh(c)])g&&console.log(g);console.log(Rn)}return h}async function sf(e,t,n){let r=V(),s=r.apiUrl||ue(),o=(n.apiUrl||ue()).replace(/\/+$/,""),i=await B("/api/v1/cli/auth/whoami",{token:e,baseUrl:o});return of({...i,token:e,tokenType:"Bearer",expiresAt:null},r,s,o,t,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function nv(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 af(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 r;if(t.token!==void 0){let s=t.token.trim();if(!s)throw new Error("--token was provided but is empty");r=await sf(s,n,{...t,agentSkills:t.agentSkills!==!1})}else{let s=(process.env.CANARY_TOKEN??"").trim();s?r=await sf(s,n,{...t,agentSkills:t.agentSkills!==!1}):(r=await tv(n,{webUrl:t.webUrl,apiUrl:t.apiUrl,workspace:t.workspace,open:t.open!==!1,animation:t.animation!==!1,agentSkills:t.agentSkills!==!1}),Yn())}r&&t.agentSkills!==!1&&t.hooks!==!1&&await cs({json:n})}catch(r){let s=r instanceof L?`${r.message}`:r instanceof Error?r.message:String(r);n?console.log(JSON.stringify({ok:!1,error:s})):console.error(`Login failed: ${s}`),process.exitCode=1}})}w();Q();ro();In();w();fe();Q();Fe();w();fe();Fe();var Tn=5e3;function xc(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let n=new AbortController;for(let r of[e,t])r.aborted?n.abort(r.reason):r.addEventListener("abort",()=>n.abort(r.reason),{once:!0});return n.signal}async function cf(e,t,n,r={}){let s=AbortSignal.timeout(r.timeoutMs??Tn);try{let o=await B(`/api/v1/cli/local-repositories/lookup?${new URLSearchParams({workspaceId:t,githubFullName:n}).toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:xc(s,r.signal)});return o&&typeof o.repositoryId=="string"?{repositoryId:o.repositoryId}:null}catch(o){return o instanceof L&&o.status===404&&o.code==="repository_not_connected"?{notConnected:!0}:null}}async function Sc(e,t={}){let{signal:n}=t,r=ne();if(!r)return{ok:!1,cause:"not_logged_in"};let s=V(),o=s.team?.id;if(!o)return{ok:!1,cause:"no_workspace"};let i=ue();try{let a=r===s.token?s.user?.id:void 0;if(a||(a=(await B("/api/v1/cli/auth/whoami",{token:r,baseUrl:i,signal:n}))?.user?.id),!a)return{ok:!1,cause:"not_logged_in"};let c={apiUrl:i,userId:a,workspaceId:o,directory:e},l=await Pd(c,d=>cf({token:r,apiUrl:i},o,d,t));return l?.repositoryId?{ok:!0,context:{token:r,apiUrl:i,repository:c,repositoryId:l.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(a){return{ok:!1,cause:a.code==="not_a_git_repository"?"no_binding":"context_error"}}}Ao();nt();Fe();w();Q();Fe();import{randomUUID as rv}from"node:crypto";import{mkdirSync as sv,readFileSync as lf,renameSync as ov,rmSync as iv,writeFileSync as av}from"node:fs";import{dirname as cv,join as lv}from"node:path";var uv="skips.json",dv=720*60*60*1e3,hv=1440*60*1e3,fv=(e,t)=>{let n=Date.parse(e.at);return Number.isFinite(n)&&t-n<dv&&n-t<hv};function uf(e,t=Date.now()){let n={version:1,skips:{}},r;try{r=JSON.parse(lf(Bt(e,uv),"utf8"))}catch{return n}let s=r?.skips;if(!r||typeof r!="object"||r.version!==1||!s||typeof s!="object"||Array.isArray(s))return n;for(let[o,i]of Object.entries(s))/^[a-f0-9]{40}$/.test(o)&&i&&typeof i=="object"&&typeof i.reason=="string"&&typeof i.at=="string"&&fv(i,t)&&(n.skips[o]={reason:i.reason,at:i.at,...typeof i.branch=="string"?{branch:i.branch}:{}});return n}var Po=()=>lv(K(),"hold","skips.json"),pv=600*1e3;function df(e){let t;try{t=JSON.parse(lf(Po(),"utf8"))}catch{return{}}let n=t?.skips;if(t?.version!==1||!n||typeof n!="object"||Array.isArray(n))return{};let r={};for(let[s,o]of Object.entries(n)){let i=Date.parse(o?.at??"");typeof o?.reason=="string"&&Number.isFinite(i)&&e-i>=0&&e-i<pv&&(r[s]={reason:o.reason,at:o.at})}return r}function hf(e){let t=Po(),n=`${t}.${rv()}.tmp`;sv(cv(t),{recursive:!0,mode:448});try{av(n,JSON.stringify({version:1,skips:e},null,2)+`
|
|
1719
|
-
`,{flag:"wx",mode:384}),
|
|
1720
|
-
`,{mode:n}),
|
|
1721
|
-
`).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
|
|
1737
|
+
`),h()}function f(){t.setRawMode(a),c||t.pause(),n.write(`${ve}0m${ve}?25h`)}function g(){process.exitCode=143,p()}function m(){(n.rows||24)<16||(n.columns||80)<30?p():i()}function C(A,b){if(!(!b||d)){if(!e.sessionCurrent()){p();return}if(b.ctrl&&["c","d"].includes(b.name??"")){p();return}if(!(b.ctrl||b.meta)){if(r.picker){let S=r.context.workspaces.length;if(b.name==="escape"){if(r.context.selectionRequired){p();return}r.picker=!1}else if(/^[1-9]$/.test(b.sequence??"")&&Number(b.sequence)<=S)r.highlighted=Number(b.sequence)-1;else if(b.name==="up")r.highlighted=(r.highlighted+S-1)%S;else if(b.name==="down")r.highlighted=(r.highlighted+1)%S;else if(b.name==="return"){let x=r.context.workspaces[r.highlighted];try{e.selectWorkspace(x),r.context={...r.context,workspace:x,source:"selected in CLI",selectionRequired:!1},r.picker=!1,r.message="Workspace saved for future CLI commands."}catch{if(!e.sessionCurrent()){p();return}r.picker=!1,r.message="Couldn't save the workspace. Your previous selection is unchanged."}}}else if(["return","escape","q"].includes(b.name??"")){p();return}else if(b.name==="w"&&xc(r.context))r.picker=!0,r.highlighted=Math.max(0,r.context.workspaces.findIndex(S=>S.id===r.context.workspace.id));else if(b.name==="c"&&!u){let S=new AbortController;u=S,l.signal.addEventListener("abort",()=>S.abort(),{once:!0}),Yk(tf,S.signal).then(x=>{u===S&&(u=void 0),!d&&(r.message=x?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",i())})}i()}}}Hk(t),t.setRawMode(!0),t.resume(),t.on("keypress",C),t.once("end",p),n.on("resize",m),process.once("SIGINT",p),process.once("SIGTERM",g),process.once("exit",f),n.write(`${ve}?25l`),i()})}var Xk=900*1e3,Zk=6e4;var of=e=>e.toString("base64url");function Qk(e){let t=process.platform,[n,r]=t==="darwin"?["open",[e]]:t==="win32"?["explorer.exe",[e]]:["xdg-open",[e]];try{let s=Kk(n,r,{stdio:"ignore",detached:!0});s.on("error",()=>{}),s.unref()}catch{}}function ev(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 tv(e){return new Promise((t,n)=>{let r,s,o=new Promise((l,d)=>{r=l,s=d}),i=zk((l,d)=>{let u=new URL(l.url??"/","http://127.0.0.1"),h=(g,m,C)=>{d.writeHead(C,{"content-type":"text/html",connection:"close"}),d.end(ev(g,m))};if(u.pathname!=="/callback"){d.writeHead(404,{connection:"close"}),d.end("not found");return}if(u.searchParams.get("state")!==e){h("Unrecognized request","This didn't match a pending sign-in. You can close this tab.",400);return}let p=u.searchParams.get("error");if(p){h("Authorization failed","You can close this tab and return to your terminal.",400),s(new Error(`authorization failed: ${p}`));return}let f=u.searchParams.get("code");if(!f){h("Authorization failed","No authorization code was returned. Please run canary login again.",400),s(new Error("callback returned no code"));return}h("Authorization received","Return to your terminal to finish signing in. You can close this tab.",200),r(f)}),a=setTimeout(()=>s(new Error("timed out waiting for browser authorization")),Xk);a.unref?.();let c=()=>{clearTimeout(a),i.closeAllConnections?.(),i.close()};o.then(c,c),i.on("error",l=>{clearTimeout(a),n(l)}),i.listen(0,"127.0.0.1",()=>{t({port:i.address().port,code:o,close:c})})})}async function nv(e,t){let n=V(),r=n.apiUrl||ue(),s=(t.apiUrl||ue()).replace(/\/+$/,""),o=of(sf(32)),i=Vk("sha256").update(o).digest("base64url"),a=of(sf(16)),{port:c,code:l,close:d}=await tv(a),u=`http://127.0.0.1:${c}/callback`,h=(t.webUrl||Tt()).replace(/\/+$/,""),p=`${h}/cli/authorize?challenge=${encodeURIComponent(i)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(u)}`;for(let C of Kh(e,t.open,p))console.error(C);let f=ef({json:e,animation:t.animation,open:t.open}),g=Date.now(),m=f?void 0:setInterval(()=>console.error(zh(e,Math.round((Date.now()-g)/1e3))),Zk);m?.unref?.();try{t.open&&Qk(p);let C=await l;m&&clearInterval(m),f?.saving();let A=await W("/api/v1/cli/auth/token",{method:"POST",body:{code:C,codeVerifier:o},baseUrl:s});return f&&await f.celebrate(),f?.clear(),await cf(A,n,r,s,e,{webUrl:h,agentSkills:t.agentSkills,workspace:t.workspace,interactive:!!f&&!!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(C){throw f?.fail(),C}finally{m&&clearInterval(m),f?.stop(),d()}}async function cf(e,t,n,r,s,o){Ne(({team:g,...m})=>({...m,token:e.token,user:e.user,apiUrl:r,...o.webUrl?{webUrl:o.webUrl}:{},agentSkills:o.agentSkills}),{overwriteUnreadable:!0}),ho();let i=await Jh(e,t,n,r);o.workspace!==void 0&&(i.workspace=No(i,o.workspace),i.source="selected in CLI",i.selectionRequired=!1),i.selectionRequired||Ne(g=>({...g,team:i.workspace}));let a=o.agentSkills?Jr():void 0,c=o.agentSkills?Ta():void 0,l=()=>{let g=V();return g.token===e.token&&g.apiUrl===r},d=g=>{Ne(m=>{if(m.token!==e.token||m.apiUrl!==r)throw new Error("CLI session changed");return{...m,team:g}}),i.selectionRequired=!1},u=i.repository?g=>$o({token:e.token,apiUrl:r,userId:e.user.id},i.repository,g):void 0;if(!i.selectionRequired&&u&&(i.repositoryState=(await u(i.workspace.id))?.state),o.interactive&&i.workspaces.length)await rf({email:e.user.email,context:i,skill:a,plugin:c,selectWorkspace:d,sessionCurrent:l});else if(o.promptWorkspace&&i.selectionRequired&&i.workspaces.length){console.error(`Signed in as ${ie(e.user.email)}.`);let g=await nf(i);g&&(d(g),i.workspace=g,i.source="selected in CLI",u&&(i.repositoryState=(await u(g.id))?.state))}if(!l())throw new Error("CLI session changed in another process. Run canary whoami.");let h=!process.exitCode,p=V().team;if(!p){let g=i.workspaces.length?"workspace_selection_required":"workspace_required",m=i.workspaces.length?"canary workspace use <id>":`Create or join a workspace at ${Tt()}, then run canary login.`;return s?console.log(JSON.stringify({ok:!1,authenticated:!0,error:g,user:e.user,workspaces:i.workspaces,fix:m})):(console.log(`Signed in as ${ie(e.user.email)}. Select a workspace to continue.`),i.workspaces.forEach((C,A)=>console.log(` ${A+1}. ${ie(C.name)} (${ie(C.id)})`)),console.log(m)),process.exitCode=1,h}let f=i.repository?{name:i.repository,state:i.repositoryState}:void 0;if(s)console.log(JSON.stringify({ok:!0,user:e.user,team:p,workspace:p,...f?{repository:f}:{}}));else if(!o.interactive){console.log(`Logged in as ${ie(e.user.email)} (${ie(p.name??p.id)}).`),f&&console.log(jo(f.name));for(let g of[a&&rv(a),Xh(c)])g&&console.log(g);console.log(Rn)}return h}async function af(e,t,n){let r=V(),s=r.apiUrl||ue(),o=(n.apiUrl||ue()).replace(/\/+$/,""),i=await W("/api/v1/cli/auth/whoami",{token:e,baseUrl:o});return cf({...i,token:e,tokenType:"Bearer",expiresAt:null},r,s,o,t,{agentSkills:n.agentSkills,workspace:n.workspace,interactive:!1})}function rv(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 lf(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 r;if(t.token!==void 0){let s=t.token.trim();if(!s)throw new Error("--token was provided but is empty");r=await af(s,n,{...t,agentSkills:t.agentSkills!==!1})}else{let s=(process.env.CANARY_TOKEN??"").trim();s?r=await af(s,n,{...t,agentSkills:t.agentSkills!==!1}):(r=await nv(n,{webUrl:t.webUrl,apiUrl:t.apiUrl,workspace:t.workspace,open:t.open!==!1,animation:t.animation!==!1,agentSkills:t.agentSkills!==!1}),Yn())}r&&t.agentSkills!==!1&&t.hooks!==!1&&await ls({json:n})}catch(r){let s=r instanceof L?`${r.message}`:r instanceof Error?r.message:String(r);n?console.log(JSON.stringify({ok:!1,error:s})):console.error(`Login failed: ${s}`),process.exitCode=1}})}w();ee();ro();In();w();fe();ee();Fe();w();fe();Fe();var Tn=5e3;function Sc(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let n=new AbortController;for(let r of[e,t])r.aborted?n.abort(r.reason):r.addEventListener("abort",()=>n.abort(r.reason),{once:!0});return n.signal}async function uf(e,t,n,r={}){let s=AbortSignal.timeout(r.timeoutMs??Tn);try{let o=await W(`/api/v1/cli/local-repositories/lookup?${new URLSearchParams({workspaceId:t,githubFullName:n}).toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:Sc(s,r.signal)});return o&&typeof o.repositoryId=="string"?{repositoryId:o.repositoryId}:null}catch(o){return o instanceof L&&o.status===404&&o.code==="repository_not_connected"?{notConnected:!0}:null}}async function Cc(e,t={}){let{signal:n}=t,r=Q();if(!r)return{ok:!1,cause:"not_logged_in"};let s=V(),o=s.team?.id;if(!o)return{ok:!1,cause:"no_workspace"};let i=ue();try{let a=r===s.token?s.user?.id:void 0;if(a||(a=(await W("/api/v1/cli/auth/whoami",{token:r,baseUrl:i,signal:n}))?.user?.id),!a)return{ok:!1,cause:"not_logged_in"};let c={apiUrl:i,userId:a,workspaceId:o,directory:e},l=await Ld(c,d=>uf({token:r,apiUrl:i},o,d,t));return l?.repositoryId?{ok:!0,context:{token:r,apiUrl:i,repository:c,repositoryId:l.repositoryId}}:{ok:!1,cause:"no_binding"}}catch(a){return{ok:!1,cause:a.code==="not_a_git_repository"?"no_binding":"context_error"}}}Ao();nt();Fe();w();ee();Fe();import{randomUUID as sv}from"node:crypto";import{mkdirSync as ov,readFileSync as df,renameSync as iv,rmSync as av,writeFileSync as cv}from"node:fs";import{dirname as lv,join as uv}from"node:path";var dv="skips.json",hv=720*60*60*1e3,fv=1440*60*1e3,pv=(e,t)=>{let n=Date.parse(e.at);return Number.isFinite(n)&&t-n<hv&&n-t<fv};function hf(e,t=Date.now()){let n={version:1,skips:{}},r;try{r=JSON.parse(df(Ut(e,dv),"utf8"))}catch{return n}let s=r?.skips;if(!r||typeof r!="object"||r.version!==1||!s||typeof s!="object"||Array.isArray(s))return n;for(let[o,i]of Object.entries(s))/^[a-f0-9]{40}$/.test(o)&&i&&typeof i=="object"&&typeof i.reason=="string"&&typeof i.at=="string"&&pv(i,t)&&(n.skips[o]={reason:i.reason,at:i.at,...typeof i.branch=="string"?{branch:i.branch}:{}});return n}var Po=()=>uv(K(),"hold","skips.json"),gv=600*1e3;function ff(e){let t;try{t=JSON.parse(df(Po(),"utf8"))}catch{return{}}let n=t?.skips;if(t?.version!==1||!n||typeof n!="object"||Array.isArray(n))return{};let r={};for(let[s,o]of Object.entries(n)){let i=Date.parse(o?.at??"");typeof o?.reason=="string"&&Number.isFinite(i)&&e-i>=0&&e-i<gv&&(r[s]={reason:o.reason,at:o.at})}return r}function pf(e){let t=Po(),n=`${t}.${sv()}.tmp`;ov(lv(t),{recursive:!0,mode:448});try{cv(n,JSON.stringify({version:1,skips:e},null,2)+`
|
|
1738
|
+
`,{flag:"wx",mode:384}),iv(n,t)}catch(r){throw av(n,{force:!0}),r}}function gf(e,t,n=Date.now()){return Mr(`${Po()}.lock`,"the push skips",()=>{let r=ff(n),s={reason:t,at:new Date(n).toISOString()};return pf({...r,[e]:s}),s})}function mf(e,t=Date.now()){try{return Mr(`${Po()}.lock`,"the push skips",()=>{let n=ff(t),r=n[e];return r?(delete n[e],pf(n),{reason:r.reason}):null})}catch{return null}}Jt();var mv=500,yf={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 wf(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 yv(e,t){try{if(!bd(e))return D(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 hn)return D(t,"config_busy",n.message,void 0,2);throw n}console.log(t?JSON.stringify({ok:!0,mode:e}):wf(e))}async function wv(e,t,n){let r=(t??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,mv);if(!r)return D(n,"reason_required","a skip needs the person's OK, in their words",'canary skip --reason "<their exact words>"',3);let s=yn(process.env,e);if(!s)return D(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 o;try{o=gf(s,r)}catch(a){if(a instanceof hn)return D(n,"config_busy",a.message,void 0,2);throw a}let i=Q();i&&await es("gate_skip:chat",{token:i,apiUrl:ue()}),console.log(n?JSON.stringify({ok:!0,chat:s,reason:o.reason,at:o.at}):`Skip recorded: this chat's next push goes out unchecked (${F(o.reason)}).`)}async function bv(e,t){fo(e);let n=await Cc(e);if(!n.ok){let[s,o]=yf[n.cause]??yf.context_error;return D(t,n.cause,s,o,3)}let r=Object.entries(hf(n.context.repository).skips).map(([s,o])=>({treeHash:s,...o})).sort((s,o)=>o.at.localeCompare(s.at));if(t)return console.log(JSON.stringify({ok:!0,skips:r}));if(!r.length)return console.log("No skips recorded for this repository.");for(let s of r)console.log(`${s.treeHash.slice(0,12)} ${s.at.slice(0,16).replace("T"," ")} ${s.branch?F(s.branch):"(detached)"} ${F(s.reason)}`)}function bf(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(r=>yv(n,r.json===!0));t.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let r=cs();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(wf(r.mode));for(let s of Oo(r))console.log(s)}}),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 r=n.json===!0;try{n.list?await bv(n.dir??process.cwd(),r):await wv(n.dir??process.cwd(),n.reason,r)}catch(s){D(r,"internal_error",s instanceof Error?s.message:String(s),void 0,2)}})}In();w();nt();var kv={[pe.install]:"(random, minted once into ~/.canary/config.json)",[pe.worktree]:"(hash of this checkout's path, salted by the install id; the path never leaves)",[pe.repo]:"(root commit of the history; absent on a shallow clone)"};function kf(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=Wt();if(t.json===!0)return void console.log(JSON.stringify(n));for(let[r,s]of Object.entries(n)){let o=r===pe.harness&&s==="unknown"?"(no running coding-agent session detected)":kv[r]??"";console.log(`${r.padEnd(18)} ${s}${o?` ${o}`:""}`)}})}w();fe();import{execFileSync as Xg,spawn as Zg}from"node:child_process";import{createHash as m1,randomBytes as y1}from"node:crypto";import{appendFileSync as w1,closeSync as b1,constants as ui,copyFileSync as k1,existsSync as Te,mkdirSync as Fn,openSync as v1,readdirSync as yi,readFileSync as Mt,realpathSync as cn,rmSync as Dn,statSync as Ar,utimesSync as x1,writeFileSync as $s,writeSync as S1}from"node:fs";import{homedir as wl}from"node:os";import{basename as bl,dirname as pt,join as P,relative as Qg,resolve as Rl,sep as wi}from"node:path";w();fe();ee();nt();import{execFile as Vv}from"node:child_process";import{copyFileSync as tp,existsSync as np,mkdirSync as rp,mkdtempSync as Kv,readdirSync as sp,readFileSync as zv,renameSync as Xv,rmSync as Dc,statSync as Zv,writeFileSync as Vo}from"node:fs";import{tmpdir as Qv}from"node:os";import{join as Ie,resolve as ep}from"node:path";import{promisify as ex}from"node:util";w();ee();import{createHash as Do,randomBytes as xv}from"node:crypto";import{execFileSync as Ec}from"node:child_process";import{existsSync as ge,mkdirSync as $e,readdirSync as ft,readFileSync as ar,realpathSync as Af,renameSync as Sv,rmSync as je,statfsSync as Cv,statSync as Av,utimesSync as Iv,writeFileSync as Kt}from"node:fs";import{createServer as Rv}from"node:net";import{basename as Rc,dirname as Tv,join as j,resolve as Ev}from"node:path";w();import{spawn as vv}from"node:child_process";var vf=()=>process.env.SANDBOX_RUNTIME==="1",Ac=()=>!!(process.env.https_proxy||process.env.HTTPS_PROXY||process.env.http_proxy||process.env.HTTP_PROXY);function Ic(){let[e,t]=process.versions.node.split(".").map(Number);return e>=24||e===22&&t>=21}var xf="Node 22.21 or later (or 24 and later)";function Sf(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 Cf(){if(process.argv[2]!=="jobs"||!Ac()||!Ic()||process.env.NODE_USE_ENV_PROXY==="1")return!1;let e=vv(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 Ov=12*6e4,$v=720*6e4,Nv=336*60*6e4,_v=3e3,jv=42e3,Tc=100,If=40,Lo=2,_=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="JobsError"}},H=()=>j(K(),"jobs"),Pv=2.2,Rf=26e8,Mv=1e9;function Oc(e,t,n=null){let r=Math.ceil(n!==null?e+n+Rf:t?e+Mv:e*Pv+Rf),s=$c();return s<r?{needBytes:r,freeBytes:s}:null}function $c(){$e(H(),{recursive:!0,mode:448});let{bavail:e,bsize:t}=Cv(H());return e*t}var Lv=e=>(Math.ceil(e/1e8)/10).toFixed(1),Fv=e=>(Math.floor(e/1e8)/10).toFixed(1),fs=e=>`This batch's copy and the app's dependencies need about ${Lv(e.needBytes)} GB of free disk, and ${Fv(e.freeBytes)} GB is free.`;function Ef(){let e=H();try{$e(e,{recursive:!0,mode:448});let t=j(e,`.write-check-${process.pid}`);Kt(t,""),je(t,{force:!0})}catch(t){let n=t.code;throw n!=="EPERM"&&n!=="EACCES"&&n!=="EROFS"?t:Wo(n)}}function Wo(e){let t=H();return new _("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. ${Sf(t)}`)}function cr(){let e=Number(process.env.CLAUDE_PID);if(!Number.isInteger(e)||e<=0)return null;let t=Rt(e);return t===null?null:{pid:e,startedAt:t}}function Zt(e){try{process.kill(e.pid,0)}catch(n){if(n.code==="ESRCH")return"gone"}if(Dv(e.pid))return"gone";let t=Rt(e.pid);return t===null?"unknown":Math.abs(t-e.startedAt)<=_v?"alive":"gone"}function Dv(e){try{return Ec("ps",["-o","stat=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim().startsWith("Z")}catch{return!1}}function sr(e){return!e||Zt(e)!=="gone"}var Of=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ot(e,t){if(!Of.test(e))throw new _("bad_id",`${JSON.stringify(e)} isn't a ${t} id.`,`Use the ${t} id Canary printed.`);return e}function Ae(){let e=process.env.CLAUDE_CODE_SESSION_ID?.trim();if(!e)throw new _("no_session","canary jobs runs only inside a Claude Code session.");return e}function Y(e){try{return JSON.parse(ar(e,"utf8"))}catch{return null}}function Pe(e,t,n=384){let r=`${e}.${process.pid}.tmp`;Kt(r,JSON.stringify(t,null,2)+`
|
|
1739
|
+
`,{mode:n}),Sv(r,e)}function $f(e){try{let t=new Date;Iv(e,t,t)}catch{}}var Fo=(e,t)=>{try{return Date.now()-Av(e).mtimeMs>=t}catch{return!0}},or=e=>j(H(),"sessions",`${/^[A-Za-z0-9_-]{1,128}$/.test(e)?e:Do("sha256").update(e).digest("hex").slice(0,32)}.json`);function it(e){return Y(or(e))??{sessionId:e,runs:{},cursors:{}}}function vt(e,t){$e(j(H(),"sessions"),{recursive:!0,mode:448});let n=t(it(e));return Pe(or(e),n),n}function Wv(){let e=j(H(),"sessions");return ge(e)?ft(e).filter(t=>t.endsWith(".json")).map(t=>Y(j(e,t))).filter(t=>t!==null):[]}function Nf(e){let t=`${or(e)}.watch`,n=`${process.pid} ${Date.now()}`;return $e(j(H(),"sessions"),{recursive:!0,mode:448}),Kt(t,n),()=>{try{return ar(t,"utf8")===n}catch{return!1}}}function _f(e){try{return Af(Ec("git",["-C",e,"rev-parse","--path-format=absolute","--git-common-dir"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim())}catch{try{return Af(e)}catch{return Ev(e)}}}function Bv(e){let t=n=>Ec("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(`
|
|
1740
|
+
`).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 Uv=(e,t)=>!!e&&!!t&&e!==t&&e.split(":")[0]===t.split(":")[0],Vt=()=>j(H(),"repos"),ir=e=>`${e.name.replace(/[^\w.-]/g,"_")}-${e.id.slice(0,8)}`;function jf(){return ge(Vt())?ft(Vt()).map(e=>Y(j(Vt(),e,"repo.json"))).filter(e=>e!==null):[]}function Mo(e){return $e(j(Vt(),ir(e)),{recursive:!0,mode:448}),Pe(j(Vt(),ir(e),"repo.json"),e),e}function qe(e){let t=_f(e);return jf().find(n=>n.path===t)??null}function En(e,t={}){let n=_f(e),r=jf(),s=r.find(a=>a.path===n);if(s&&!t.verify)return s;let o=Bv(e);if(s){if(!Uv(s.identity,o))return o&&s.identity!==o&&(!s.identity||o.startsWith("commit:"))?Mo({...s,identity:o}):s;Mo({...s,path:""})}let i=o?r.find(a=>a.identity===o&&a.path!==""&&a.path!==n&&!ge(a.path)):void 0;return Mo(i?{...i,path:n}:{id:xv(8).toString("hex"),path:n,identity:o,name:Rc(n)===".git"?Rc(Tv(n)):Rc(n)})}function Ze(e){let t=j(Vt(),ir(e));return{dir:t,canaryMd:j(t,"canary.md"),secrets:j(t,"secrets.env"),scripts:j(t,"scripts")}}var Pf=e=>j(Vt(),e,"scripts"),zt="## How the app runs here",Mf=`# Canary
|
|
1722
1741
|
|
|
1723
1742
|
Canary's verifiers read this file before every check and add what they learn after each run.
|
|
1724
1743
|
It stays on this machine, in Canary's own folder: outside the repository, shared by its worktrees, and never uploaded.
|
|
@@ -1738,43 +1757,43 @@ Name them here; keep the values in secrets.env beside this file.
|
|
|
1738
1757
|
${zt}
|
|
1739
1758
|
|
|
1740
1759
|
## What worked and what failed
|
|
1741
|
-
`;function Bo(e){let t=
|
|
1742
|
-
`,{flag:"wx",mode:384}),t}var lr="notes-before.json",
|
|
1743
|
-
`).map(s=>s.trim()));return
|
|
1744
|
-
`).map(s=>s.trim()).filter(s=>s&&!r.has(s))}function Qt(e){try{let t=
|
|
1745
|
-
`)[n]?.trim()||null}catch{return null}}var
|
|
1746
|
-
${r}`);function Jo(e){let t=j(
|
|
1747
|
-
`);for(let n=t.length-1;n>=0;n--)if(
|
|
1760
|
+
`;function Bo(e){let t=Ze(En(e,{verify:!0}));return $e(t.scripts,{recursive:!0,mode:448}),ge(t.canaryMd)||Kt(t.canaryMd,Mf,{flag:"wx"}),ge(t.secrets)||Kt(t.secrets,`# Test secrets Canary's verifiers may use, as NAME=value. Never uploaded.
|
|
1761
|
+
`,{flag:"wx",mode:384}),t}var lr="notes-before.json",Lf=e=>e.includes(zt)?e.slice(0,e.indexOf(zt)):e;function Ff(e){let t=qe(e),n=Mf;try{t&&(n=ar(Ze(t).canaryMd,"utf8"))}catch{}return{at:new Date().toISOString(),notes:Lf(n)}}function Df(e,t){let n;try{n=ar(t,"utf8")}catch{return[]}let r=new Set(e.notes.split(`
|
|
1762
|
+
`).map(s=>s.trim()));return Lf(n).split(`
|
|
1763
|
+
`).map(s=>s.trim()).filter(s=>s&&!r.has(s))}function Qt(e){try{let t=qe(e),n=t&&/^\s*Verifiers at a time:\s*(\d+)\s*$/im.exec(ar(Ze(t).canaryMd,"utf8")),r=n?Number(n[1]):Lo;return r>=1&&r<=8?r:Lo}catch{return Lo}}var ce=e=>j(H(),"runs",ot(e,"run"));function Uo(e){ge(ce(e))&&Kt(j(ce(e),"heartbeat"),"")}var le=e=>j(H(),"batches",ot(e,"batch"));function de(e){return j(H(),"workspaces",e.repoFolder,String(e.slot))}function Wf(e){$e(j(H(),"workspaces",e.repoFolder),{recursive:!0,mode:448}),Kt(j(H(),"workspaces",e.repoFolder,`${e.slot}.used`),"")}function qv(e){let t=j(H(),"workspaces");for(let n of ge(t)?ft(t):[]){let r=j(t,n),s=Y(j(Vt(),n,"repo.json")),o=s!==null&&(s.path===""||!ge(s.path));for(let i of ft(r).filter(a=>/^\d+$/.test(a))){let a=j(r,i),c=ge(j(r,`${i}.used`))?j(r,`${i}.used`):a;e.has(a)||!(o||Fo(c,Nv))||(je(a,{recursive:!0,force:!0}),je(j(r,`${i}.used`),{force:!0}))}ft(r).some(i=>/^\d+$/.test(i))||je(r,{recursive:!0,force:!0})}}var ur=(e,t,n)=>n?j(le(e),"packs",ot(t,"job"),`proof-${n}`):j(le(e),"packs",ot(t,"job")),dr=e=>j(le(e),"scratch"),Xt=e=>j(le(e),"state.json");function Bf(e){$e(j(H(),"batches"),{recursive:!0,mode:448}),Uf(e)&&je(le(e),{recursive:!0,force:!0});try{$e(le(e),{mode:448})}catch(t){if(t.code==="EEXIST"){let n=Y(Xt(e))?.left;throw n?new _("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 _("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 en(e){let t=Y(Xt(e));if(!t)throw new _("not_taken_here","This batch wasn't taken on this machine.",`Take it first: canary jobs take ${e}`);return $f(Xt(e)),t}function ps(e){Pe(Xt(e.batchId),e)}function X(){let e=j(H(),"batches");return ge(e)?ft(e).filter(t=>Of.test(t)).map(t=>Y(Xt(t))).filter(t=>t!==null):[]}var gs=e=>X().some(t=>t.setAside===!0&&t.checkout===e);function hr(e){ot(e,"job");let t=X().find(n=>n.jobs.some(r=>r.jobId===e));if(!t)throw new _("not_taken_here","No batch taken on this machine holds this job.","Use the job id take printed.");return $f(Xt(t.batchId)),t}var Nc=e=>Do("sha256").update(e).digest("hex").slice(0,16);function _c(e,t,n){try{$e(e,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r;if(!n(Y(j(e,"owner.json"))))return!1;je(e,{recursive:!0,force:!0});try{$e(e,{mode:448})}catch{return!1}}return Pe(j(e,"owner.json"),t),!0}var qo=e=>!e?.batchId||Uf(e.batchId),Hv=2*6e4;function Uf(e){return ge(le(e))?!ge(Xt(e))&&Fo(le(e),Hv):!0}function qf(e,t){let n=j(H(),"slots");$e(n,{recursive:!0,mode:448});for(let r=0;r<t;r++)if(_c(j(n,String(r)),{batchId:e},s=>s?.batchId===e||qo(s)))return r;return null}var Hf=e=>Y(j(H(),"slots",String(e),"owner.json"))?.batchId??null;function ms(e){let t=j(H(),"slots");for(let n=0;n<e;n++)if(!ge(j(t,String(n)))||qo(Y(j(t,String(n),"owner.json"))))return!0;return!1}var Gf=e=>j(H(),"waiting",`${ot(e,"batch")}.json`);function ys(e,t,n){$e(j(H(),"waiting"),{recursive:!0,mode:448}),Pe(Gf(e),{batchId:e,sessionId:t,checkout:n})}var tn=e=>je(Gf(e),{force:!0});function ws(e){let t=j(H(),"waiting");return ge(t)?ft(t).map(n=>Y(j(t,n))).filter(n=>n!==null&&n.sessionId===e):[]}function Ho(e){for(let t of["slots","ports","locks"]){let n=j(H(),t);if(ge(n))for(let r of ft(n))Y(j(n,r,"owner.json"))?.batchId===e&&je(j(n,r),{recursive:!0,force:!0})}for(let t of Gv)for(let n of Pc(t,e))je(j(H(),t,n),{force:!0});je(Yo(e),{force:!0})}var Gv=["verifiers","approval-waits"],Go=e=>/^[A-Za-z0-9_-]{1,96}$/.test(e)?e:Do("sha256").update(e).digest("hex").slice(0,32);function Jf(e,t,n){try{return ar(j(H(),e,t),"utf8").split(`
|
|
1764
|
+
`)[n]?.trim()||null}catch{return null}}var jc=(e,t)=>Jf(e,t,0);function Pc(e,t){let n=j(H(),e);return ge(n)?ft(n).filter(r=>jc(e,r)===t):[]}function Yf(e,t,n){$e(j(H(),e),{recursive:!0,mode:448}),Kt(j(H(),e,t),n,{mode:384})}var Vf=(e,t)=>Yf("verifiers",Go(e),t),at=e=>jc("verifiers",Go(e)),Kf=e=>Pc("verifiers",e).length>0,zf=(e,t,n,r="")=>Yf("approval-waits",`${Go(e)}.${t}`,`${n}
|
|
1765
|
+
${r}`);function Jo(e){let t=j(H(),"approval-waits"),n=`${Go(e)}.`;return ge(t)?ft(t).filter(r=>r.startsWith(n)).flatMap(r=>{let s=jc("approval-waits",r);return s?[{name:r,call:r.slice(n.length),batchId:s}]:[]}):[]}function bs(e){for(let t of e)je(j(H(),"approval-waits",t),{force:!0})}var Yo=e=>j(H(),"approval-owed",ot(e,"batch"));function Mc(e,t){$e(j(H(),"approval-owed"),{recursive:!0,mode:448}),Pe(Yo(e),t)}var Lc=e=>Y(Yo(e));function ks(e,t){(!t||Lc(e)?.call===t)&&je(Yo(e),{force:!0})}var Nt=e=>Pc("approval-waits",e),vs=e=>Jf("approval-waits",e,1),Jv=e=>j(H(),"locks",Do("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,24));function Xf(e,t,n){return $e(j(H(),"locks"),{recursive:!0,mode:448}),_c(Jv(e),{batchId:t,jobId:n,target:e},r=>qo(r)||r?.batchId===t)}function Fc(e,t){let n=j(H(),"locks");if(ge(n))for(let r of ft(n)){let s=Y(j(n,r,"owner.json"));s?.batchId===e&&s.jobId===t&&je(j(n,r),{recursive:!0,force:!0})}}async function Zf(e,t){let n=j(H(),"ports");$e(n,{recursive:!0,mode:448});for(let r=0;r<If;r++){let s=jv+(t+r)%If*Tc;if(!_c(j(n,String(s)),{batchId:e},i=>i?.batchId===e||qo(i)))continue;let o=!0;for(let i=s;i<s+Tc&&o;i++)o=await Yv(i);if(o)return[s,s+Tc-1];je(j(n,String(s)),{recursive:!0,force:!0})}throw new _("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 Yv(e){return await Tf(e,"127.0.0.1")&&await Tf(e,"::1")}function Tf(e,t){return new Promise((n,r)=>{let s=Rv();s.once("error",o=>{if(o.code==="EADDRNOTAVAIL"&&t==="::1")return n(!0);if(o.code!=="EPERM"&&o.code!=="EACCES")return n(!1);r(new _("local_ports_blocked",`Canary can't use ports on localhost here (${o.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."))}),s.listen(e,t,()=>s.close(()=>n(!0)))})}async function Qf(e){let t=X();for(let s of t)sr(s.owner)||sr(it(s.sessionId).owner)||!Fo(Xt(s.batchId),Ov)||await e(s).catch(()=>{});let n=X();try{qv(new Set(n.map(de)))}catch{}let r=new Set(n.map(s=>s.runId));for(let s of Wv())if(!sr(s.owner)){for(let o of ws(s.sessionId))tn(o.batchId);try{let o=!1;for(let i of Object.keys(s.runs)){let a=ce(i),c=ge(j(a,"heartbeat"))?j(a,"heartbeat"):a;r.has(i)||ge(a)&&!Fo(c,$v)||(je(a,{recursive:!0,force:!0}),delete s.runs[i],o=!0)}if(Object.keys(s.runs).length===0)for(let i of[or(s.sessionId),`${or(s.sessionId)}.watch`])je(i,{force:!0});else o&&Pe(or(s.sessionId),s)}catch{}}}zr();Fe();Gt();Eo();Jt();var tx=ex(Vv),nx=1e5,rx=8*6e4,sx=3e4,ox=1440*6e4;function op(e,t,n){let r=e[0]==="--json",s=e.length>1&&e[e.length-1]==="--json",o=e.slice(r?1:0,s?-1:void 0),i=r||s;if(o.length===1&&o[0]==="-")return{json:i,words:null};let a=new Set(["--json","--verifier"]);if(e.includes("-")&&e.includes("--verifier")&&e.every(l=>l==="-"||a.has(l))&&e.filter(l=>l==="-").length===1)return{json:e.includes("--json"),words:null,verifier:!0};let c=o[0];return c===void 0||n.has(c)||t.has(c)?null:{json:i,words:o.join(" ")}}var ix=/^[ \t]*-{3,}[ \t]*from the user['’]s agent[ \t]*-{3,}[ \t\r]*$/i;function ax(e){let t=e.split(`
|
|
1766
|
+
`);for(let n=t.length-1;n>=0;n--)if(ix.test(t[n]))return{words:t.slice(0,n).join(`
|
|
1748
1767
|
`),agentContext:t.slice(n+1).join(`
|
|
1749
|
-
`).trim()||null};return{words:e,agentContext:null}}function
|
|
1750
|
-
`)}}var On=e=>Ie(K(),"requests",e);function
|
|
1768
|
+
`).trim()||null};return{words:e,agentContext:null}}function cx(e,t){return t?ax(e):{words:e,agentContext:null}}function lx(e,t,n){let r=new Map,s=t.split("\0");for(let a=0;a<s.length;a++){let c=/^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(s[a]);if(!c)continue;let l=c[3]||s[a+=2];l&&r.set(l,{added:c[1]==="-"?null:Number(c[1]),removed:c[2]==="-"?null:Number(c[2])})}let o=[],i=e.split("\0");for(let a=0;a<i.length;a++){let c=i[a];if(!c)continue;if(c[0]==="R"||c[0]==="C"){let u=i[a+=2];u&&o.push({path:u,status:c[0]==="R"?"renamed":"added",...r.get(u)??{added:null,removed:null}});continue}let l=i[++a];if(!l)continue;let d=c[0]==="A"?"added":c[0]==="D"?"deleted":"modified";o.push({path:l,status:d,...r.get(l)??{added:null,removed:null}})}return o.push(...ip(n)),o}function ip(e){let t=[],n=e.split("\0");for(let r=0;r<n.length;r++){let s=n[r];if(s.length<4)continue;let o=s.slice(0,2);o.includes("R")||o.includes("C")?r++:o==="??"&&t.push({path:s.slice(3),status:"untracked",added:null,removed:null})}return t}function ux(e,t){return[...e.split("\0").filter(Boolean).map(r=>({path:r,status:"added",added:null,removed:null})),...ip(t)]}async function nn(e,t,n={}){try{return(await tx("git",["-c","core.fsmonitor=false",...t],{cwd:e,env:{...no(),...n},timeout:sx,maxBuffer:64*1024*1024})).stdout}catch{return null}}async function dx(e){let t=(await nn(e,["rev-parse","--git-path","index"]))?.trim();if(!t||!np(ep(e,t)))return{env:{},dispose:()=>{}};let n=Kv(Ie(Qv(),"canary-index-"));return tp(ep(e,t),Ie(n,"index")),{env:{GIT_INDEX_FILE:Ie(n,"index")},dispose:()=>Dc(n,{recursive:!0,force:!0})}}async function hx(e,t){let n=await Xd(e).catch(()=>null),r=await dx(e),[s,o,i,a,c]=await Promise.all([nn(e,["rev-parse","--abbrev-ref","HEAD"]),nn(e,["rev-parse","HEAD"]),nn(e,["status","--porcelain=v1","-z","--untracked-files=normal"]),n?nn(e,["diff","--name-status","-z","--find-renames",n],r.env):nn(e,["ls-files","-z"]),n?nn(e,["diff","--numstat","-z","--find-renames",n],r.env):Promise.resolve("")]).finally(r.dispose);if(i===null||a===null||c===null)throw new re("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=s?.trim();return{repo:{name:t,branch:l&&l!=="HEAD"?l:null,head:o?.trim()||null,uncommitted:i.length>0},changes:{files:n?lx(a,c,i):ux(a,i)}}}var fx=500;async function px(e,t){return t?(await nn(e,["log",`--max-count=${fx}`,"--format=%B%x00",`${t}..HEAD`])??"").split("\0").map(r=>r.trim()).filter(Boolean):[]}function gx(e){try{let t=Ie(K(),"requests");rp(t,{recursive:!0,mode:448}),Vo(Ie(t,`${e}.asked`),"",{mode:384})}catch(t){process.stderr.write(`Canary couldn't note this request on this machine (${t instanceof Error?t.message:String(t)}); \`canary show\` needs its whole id.
|
|
1769
|
+
`)}}var On=e=>Ie(K(),"requests",e);function mx(e,t,n,r){let s=On(e);rp(s,{recursive:!0,mode:448});let o=Ie(K(),"requests");for(let i of sp(o,{withFileTypes:!0}))if(!(!i.isDirectory()||i.name===e))try{Date.now()-Zv(Ie(o,i.name)).mtimeMs>ox&&Dc(Ie(o,i.name),{recursive:!0,force:!0})}catch{}try{Xv(t.bundlePath,Ie(s,"source.bundle"))}catch(i){if(i.code!=="EXDEV")throw i;tp(t.bundlePath,Ie(s,"source.bundle"))}Vo(Ie(s,"source.json"),JSON.stringify(t.manifest,null,2)+`
|
|
1751
1770
|
`,{mode:384}),Vo(Ie(s,"request.json"),JSON.stringify({checkout:n,chat:r})+`
|
|
1752
|
-
`,{mode:384}),Vo(Ie(s,lr),JSON.stringify(
|
|
1753
|
-
`,{mode:384})}function
|
|
1754
|
-
`:""}Canary \xB7 more to come: canary wait ${l.requestId}`)),process.exitCode=l.exitCode}catch(c){if(s)return;s=!0,
|
|
1755
|
-
`||a){t.push(n),n="",a&&o++;continue}if(e.startsWith("2>&1",o)&&/\s/.test(e[o-1]??"")){o+=3;continue}if(/[&|<>`$()\\#]/.test(i))return!1;n+=i}if(r)return!1;let s=[...t,n].map(o=>o.trim()).filter(Boolean);return s.length>0&&s.every(o=>/^canary\s+jobs\s/.test(`${o} `))}var
|
|
1771
|
+
`,{mode:384}),Vo(Ie(s,lr),JSON.stringify(Ff(n))+`
|
|
1772
|
+
`,{mode:384})}function Wc(e){let t=Ie(K(),"requests");for(let n of np(t)?sp(t,{withFileTypes:!0}):[]){if(!n.isDirectory())continue;let r=Ie(t,n.name);try{JSON.parse(zv(Ie(r,"request.json"),"utf8")).chat===e&&Dc(Ie(r,"source.bundle"),{force:!0})}catch{}}}async function yx(){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 ap(e,t){let{json:n}=t;Ke({cwd:e,agent:n,mode:"request"});let r=Q();if(!r)return D(n,"not_logged_in","Not logged in","run `canary login` first",3);(await Promise.resolve().then(()=>(to(),id))).installAgentSkill(),(await Promise.resolve().then(()=>(Ea(),rd))).installAgentPlugin();let s=!1,o,i={requestId:null,creating:null,capturing:null,codeSent:!1,token:r,extend:c=>{clearTimeout(o),o=a(c)}},a=c=>setTimeout(()=>{s||(s=!0,xx(n,i))},c);o=a(nx);try{let c=await bx(e,r,t,i);gx(c.answer.requestId);let l=Sx(c.answer);if(c.codeMissing&&(l.exitCode=3),s)return;s=!0,n?console.log(JSON.stringify(l)):(l.say&&console.log(l.say),l.ended||console.log(`${l.say?`
|
|
1773
|
+
`:""}Canary \xB7 more to come: canary wait ${l.requestId}`)),process.exitCode=l.exitCode}catch(c){if(s)return;s=!0,vx(n,c)}finally{clearTimeout(o)}}function wx(e,t){let n=yn();return{...n?{"x-canary-session":n}:{},...e?{"x-canary-verifier":"1","x-canary-verifiers":String(Qt(t))}:{}}}async function bx(e,t,n,r){let{words:s,agentContext:o}=n.words===null?cx(await yx(),n.json):{words:n.words,agentContext:null},i=new AbortController,a=An(e,{signal:i.signal});a.catch(()=>{}),r.capturing=a;try{let c=await xn(e,t),l=await vn({...c,token:t}),d={workspaceId:c.workspaceId,repositoryId:l.repositoryId,words:s,agentContext:o,...await hx(e,l.name)};r.creating=W("/api/v1/cli/requests",{method:"POST",token:t,body:d,headers:wx(n.verifier===!0,e)}).then(os);let u=await r.creating;if(!u.needsCode)return{answer:u,codeMissing:!1};r.requestId=u.requestId,r.extend(rx);let h=n.verifier===!0?yn():null,p=await kx(e,u.requestId,a,{context:c,repositoryId:l.repositoryId,token:t,keepFor:h});return r.codeSent=!0,{answer:{...p.answer,say:ss([u.say,p.answer.say]),do:[...u.do,...p.answer.do]},codeMissing:p.codeMissing}}finally{i.abort(),a.then(c=>c.dispose(),()=>{})}}async function kx(e,t,n,r){let s=l=>W(`/api/v1/cli/requests/${t}/source`,{method:"POST",token:r.token,body:l}).then(os).catch(d=>{throw d instanceof L&&d.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"):d}),o;try{o=await n}catch(l){let d=l instanceof We?l.code:"capture_failed",u=l instanceof We&&l.fix?`${l.message} To fix it: ${l.fix}.`:l instanceof Error?l.message:String(l);return{answer:await s({unavailable:{code:d,message:u}}),codeMissing:!0}}let i=`request:${t}`,a;try{a=await tr(o,r.context,r.repositoryId,r.token,{requestKey:i,fresh:!0})}catch(l){throw await s({unavailable:{code:"upload_failed",message:"The upload of your code didn't finish."}}).catch(()=>{}),l}r.keepFor&&mx(t,o,e,r.keepFor);let c=await s({source:a,commitMessages:await px(e,o.manifest.provenance.baseSha),...o.submodules.length?{submodules:[...o.submodules]}:{}});return ns(o.manifest,r.context,r.repositoryId,{requestKey:i,uploadId:a.uploadId}),{answer:c,codeMissing:!1}}function vx(e,t){if(t instanceof re)return D(e,t.code,t.message,void 0,3);if(t instanceof L)return t.status===413&&t.code==="commit_messages_too_large"?D(e,t.code,t.message,t.fix,3):t.status===413?D(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?D(e,"not_logged_in","Your Canary login is no longer valid.","run `canary login`",3):t.code==="source_upload_unavailable"?D(e,t.code,"Canary couldn't store your code just now.","run the same command again in a minute",2):D(e,t.code??"api_error",t.message,t.fix,be(t)||t.status>=500?2:3);let n=as(t);if(n)return D(e,"home_not_writable",n.message,n.fix,2);D(e,"internal_error",t instanceof Error?t.message:String(t),void 0,2)}async function xx(e,t){D(e,"timed_out","Canary didn't answer in time.","run the same command again",2);let n=[],r=s=>W(`/api/v1/cli/requests/${s}/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(r(t.requestId)):!t.requestId&&t.creating&&n.push(t.creating.then(s=>s.needsCode?r(s.requestId):void 0,()=>{})),t.capturing&&n.push(t.capturing.then(s=>s.dispose(),()=>{})),await Promise.race([Promise.all(n),new Promise(s=>setTimeout(s,6e3))]),process.stderr.write("",()=>process.stdout.write("",()=>process.exit(2)))}function Sx(e){let t=e.ending==="failed"?2:0;return{ok:!0,requestId:e.requestId,say:$t(e.say),do:e.do,ended:e.ending!==null,exitCode:t}}ee();Gt();w();var Bc={session:"x-canary-session",batchKey:"x-canary-batch-key"},$n=/^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}(\/[A-Za-z0-9_][A-Za-z0-9._-]{0,99}){0,7}$/;w();fe();ee();nt();import{randomUUID as Cx}from"node:crypto";mn();function Ax(){let e=V().installId;return{[pe.cli]:wt,[pe.command]:"jobs",[pe.harness]:"claude-code",...e&&/^[0-9a-f-]{36}$/.test(e)?{[pe.install]:e}:{}}}var Uc=45e3,Ix=6e4;async function lp(e,t){let n=Q();if(!n)throw new _("not_logged_in","Not logged in to Canary.","Run canary login.");let r=ue().replace(/\/+$/,""),s={...Ax(),authorization:`Bearer ${n}`,[Bc.session]:t.session};t.batchKey&&(s[Bc.batchKey]=t.batchKey),t.json!==void 0&&(s["content-type"]="application/json"),t.bytes&&(s["content-type"]="application/octet-stream");let o=new AbortController,i=setTimeout(()=>o.abort(new Error("timed out")),t.timeoutMs??Ix),a=o.signal,c;try{c=await fetch(`${r}/api/v1${e}`,{method:t.method??(t.json!==void 0||t.bytes?"POST":"GET"),headers:s,body:t.json!==void 0?JSON.stringify(t.json):t.bytes,signal:a})}catch{throw cp(r)}finally{clearTimeout(i)}if(c.ok)return c;let l=await c.json().catch(()=>null);throw typeof l?.error!="string"?cp(r):c.status>=500?new L(c.status,rn):c.status===401?new _("not_logged_in","Canary no longer accepts this CLI login.","Ask the user to run canary login, then run the command again."):new L(c.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 rn="Canary hit an internal error; retry shortly.";function cp(e){let t=new URL(e).host,n=Ac()?Ic()?`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 ${xf}.`:"Run it again in a minute.";return new L(0,"Couldn't reach Canary.",n)}async function oe(e,t){let n=await lp(e,t);return n.status===204?null:await n.json()}async function up(e,t){return Buffer.from(await(await lp(e,t)).arrayBuffer())}var _t=e=>be(e)||e instanceof L&&e.status>=500,Rx=new Set(["batch_released","batch_ended","nothing_left","not_found"]),Ko=e=>e instanceof L&&!!e.code&&Rx.has(e.code);async function He(e,t=0){let n=Date.now()+t;for(let r=1;;r++)try{return await e()}catch(s){if(!_t(s)||r>=3&&Date.now()>=n)throw s;await new Promise(o=>setTimeout(o,Math.min(r*2e3,1e4)))}}function xs(e,t,n,r){let s=n instanceof Error?n.stack??n.message:String(n),o={reportId:Cx(),...t.batchId?{batchId:t.batchId}:{},...t.jobId?{jobId:t.jobId}:{},cause:s.slice(0,8e3)};return He(()=>oe("/cli/jobs/internal-error",{session:e,batchKey:t.batchKey,json:o,timeoutMs:r}))}w();ee();import{execFile as Hx,execFileSync as Rs}from"node:child_process";import{readdirSync as Kp,readFileSync as Gx,readlinkSync as zp,realpathSync as Xp,rmSync as Yp}from"node:fs";import{basename as Jx,join as Vp,sep as Zp}from"node:path";import{promisify as Yx}from"node:util";w();import{appendFileSync as Lx,mkdirSync as _p,readFileSync as ei,rmSync as Ep,writeFileSync as Fx}from"node:fs";import{createHash as jp}from"node:crypto";import{basename as Op,dirname as Pp,join as ti}from"node:path";w();ee();import{execFileSync as Tx}from"node:child_process";import{mkdirSync as Ex,rmSync as Ox}from"node:fs";import{basename as $x,join as fp}from"node:path";var pp="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?",qc={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."},gp={label:"Keep asking",description:"Claude Code asks you about each command, following your own settings."},Hc={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."},mp={label:"Don't use them",description:"The checks set up what they can themselves and ask you for any key they need."};function yp(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 Xo=e=>fp(K(),"approvals",`${e}.json`);function wp(e,t){let n=En(e),r=Y(Xo(n.id))??{repo:n.path};t(r),Ex(fp(K(),"approvals"),{recursive:!0,mode:448}),Pe(Xo(n.id),r)}function bp(e){let t=qe(e);return t&&Y(Xo(t.id))}function Nn(e){let t=bp(e);return t?.commands?t:null}function kp(e,t){wp(e,n=>Object.assign(n,{commands:t.trim()===qc.label?"run":"ask",answer:t,at:new Date().toISOString()}))}var Zo=e=>bp(e)?.envFiles??null;function vp(e,t,n){wp(e,r=>{r.envFiles={use:n.trim()===Hc.label,files:t,answer:n,at:new Date().toISOString()}})}function xp(e){let t=qe(e);t&&Ox(Xo(t.id),{force:!0})}var Nx=/\.(example|sample|template|dist|defaults?)$/i;function _x(e){let t=[];try{t=Tx("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($x(n))&&!Nx.test(n)).sort()}function Sp(e){let t=_x(e),n=new Set(Zo(e)?.files??[]);return t.every(r=>n.has(r))?[]:t}function fr(e){e=e.replace(/\s*\|\s*(?:head|tail)(?:\s+-n\s*\d+|\s+-\d+)?\s*$/,"");let t=[],n="",r=null;for(let o=0;o<e.length;o++){let i=e[o];if(r){if(i===r)r=null;else if(r==='"'&&/[$`\\]/.test(i))return!1;continue}if(i==="'"||i==='"'){r=i;continue}let a=(i==="&"||i==="|")&&e[o+1]===i;if(i===";"||i===`
|
|
1774
|
+
`||a){t.push(n),n="",a&&o++;continue}if(e.startsWith("2>&1",o)&&/\s/.test(e[o-1]??"")){o+=3;continue}if(/[&|<>`$()\\#]/.test(i))return!1;n+=i}if(r)return!1;let s=[...t,n].map(o=>o.trim()).filter(Boolean);return s.length>0&&s.every(o=>/^canary\s+jobs\s/.test(`${o} `))}var jx=new Set(["cat","head","tail","ls","wc","stat","grep"]),Px=new Set(["head","tail","wc","grep","uniq"]);function Cp(e){let t=[],n=null,r=null;for(let s of e)if(r)if(s===r)r=null;else{if(r==='"'&&/[$`\\]/.test(s))return null;n+=s}else if(s==="'"||s==='"')r=s,n??="";else if(/\s/.test(s))n!==null&&t.push(n),n=null;else{if(/[;&|<>`$()\\#*?[\]{}~]/.test(s)&&!(s==="~"&&n===null))return null;n=(n??"")+s}return r?null:(n!==null&&t.push(n),t)}function Ap(e,t){let n=e.replace(/\s2>\s?(?:\/dev\/null|&1)(?=\s|$)/g," ").split("|").map(Cp);if(n.some(a=>!a||a.length===0))return!1;let r=a=>a.slice(1).filter(c=>!c.startsWith("-")&&!/^\d+$/.test(c)),[s,...o]=n,i=r(s).slice(s[0]==="grep"?1:0);return jx.has(s[0])&&i.length>0&&i.every(t)&&o.every(a=>Px.has(a[0])&&r(a).length<=(a[0]==="grep"?1:0))}var Mx=new Set(["echo","printf","sleep","true",":"]);function Ip(e){let t=e.split(/;|&&|\n/).map(n=>n.trim()).filter(Boolean).map(Cp);return t.length>0&&t.every(n=>n!==null&&n.length>0&&Mx.has(n[0]))}var dp=(e,t)=>e.replace(/\s+/g," ").trim()===t.replace(/\s+/g," ").trim(),hp=(e,...t)=>t.some(n=>n.label===e.trim());function Rp(e,t){let n={commands:null,envFiles:null},r=!Nn(t),s=Sp(t);for(let o of[e.tool_response,e.tool_input]){let i=o?.answers;if(!(!i||typeof i!="object"))for(let[a,c]of Object.entries(i))typeof c=="string"&&(r&&dp(a,pp)&&hp(c,qc,gp)?n.commands??=c:s.length&&dp(a,yp(s))&&hp(c,Hc,mp)&&(n.envFiles??={files:s,answer:c}))}return n}var zo=e=>`${JSON.stringify(e.label)} (${e.description})`;function Gc(e){let t=[];Nn(e)||t.push(`header "Approvals": ${JSON.stringify(pp)} Options, in this order: ${zo(qc)} and ${zo(gp)}`);let n=Sp(e);return n.length&&t.push(`header "Env files": ${JSON.stringify(yp(n))} Options, in this order: ${zo(Hc)} and ${zo(mp)}`),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 Tp(e){let t=[],n=Nn(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; 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 r=Zo(e);return r&&t.push(r.use?`The checks may use this project's env files (the user's choice on ${r.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: ${r.files.join(", ")}.`:`The user said on ${r.at.slice(0,10)} that the checks may not use this project's env files.`),t}var $p=500,Dx=120,Mp=256*1024,Wx=3e4,Bx=3e5,Ss=e=>ti(H(),"records",`${ot(e,"batch")}.jsonl`),Vc=e=>ti(H(),"records",`${ot(e,"batch")}.out`),Lp=(e,t)=>ti(Vc(e),/^[A-Za-z0-9_-]{1,96}$/.test(t)?t:jp("sha256").update(t).digest("hex").slice(0,32)),Jc=e=>e.length>$p?`${e.slice(0,$p-1)}\u2026`:e;function Qo(e,t){if(e.length<=t)return e;let n=Math.floor(t/4);return`${e.slice(0,n)}
|
|
1756
1775
|
[... ${e.length-t} characters of this output not shown ...]
|
|
1757
|
-
${e.slice(e.length-(t-n))}`}function
|
|
1758
|
-
`,{mode:384})}var
|
|
1776
|
+
${e.slice(e.length-(t-n))}`}function Cs(e,t){_p(Pp(Ss(e)),{recursive:!0,mode:448}),Lx(Ss(e),JSON.stringify(t)+`
|
|
1777
|
+
`,{mode:384})}var As=()=>new Date().toISOString(),Kc=e=>e.split(`
|
|
1759
1778
|
`).map(t=>t.trim()).find(t=>t&&!/^(source|\.|cd|set|export)\b/.test(t))??e.split(`
|
|
1760
|
-
`)[0],
|
|
1761
|
-
`))try{let c=JSON.parse(a);if(c.e==="asked")r.push(c);else if(c.e==="ended")for(let l of[c.call,c.same])l&&s.set(l,c.ended)}catch{}let o=r.slice(-t),i=r.filter(a=>a.bg).at(-1);return i&&!o.includes(i)&&o.unshift(i),o.map(a=>({at:a.at,step:
|
|
1762
|
-
`)[0]??"")}),
|
|
1763
|
-
`).filter(Boolean).flatMap(t=>{try{return[JSON.parse(t)]}catch{return[]}})}catch{return[]}}var
|
|
1764
|
-
`).find(n=>n.startsWith("n"))?.slice(1)??null}catch{return null}}}function
|
|
1765
|
-
`))r.startsWith("p")?n=Number(r.slice(1)):r.startsWith("n")&&n&&e.set(n,r.slice(1));return e}function
|
|
1766
|
-
`).filter(Boolean))];c.length&&await
|
|
1767
|
-
`)[0]:String(c)}`)}return n}async function jn(e,t={}){let n=[],r=[];for(let a of e.processes)await
|
|
1768
|
-
`)[0]:String(c)}; it may hold files a container created as another user`)}return n.length?(
|
|
1769
|
-
`).map(c=>{let l=/^(\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=)(.*)$/.exec(c);return!l||!l[3].match(
|
|
1770
|
-
`);
|
|
1771
|
-
`),
|
|
1772
|
-
`);for(let s of
|
|
1773
|
-
/${
|
|
1774
|
-
`)}async function
|
|
1779
|
+
`)[0],Yc=e=>e.say||(e.kind==="file"?`wrote ${Op(Pp(e.what))}/${Op(e.what)}`:Kc(e.what));function Fp(e,t){let n;try{n=ei(Ss(e),"utf8")}catch{return[]}let r=[],s=new Map;for(let a of n.trimEnd().split(`
|
|
1780
|
+
`))try{let c=JSON.parse(a);if(c.e==="asked")r.push(c);else if(c.e==="ended")for(let l of[c.call,c.same])l&&s.set(l,c.ended)}catch{}let o=r.slice(-t),i=r.filter(a=>a.bg).at(-1);return i&&!o.includes(i)&&o.unshift(i),o.map(a=>({at:a.at,step:Yc(a),command:a.kind==="command"?Kc(a.what):null,ended:a.bg?"background":s.get(a.call)??s.get(a.same)??"running"}))}var Ux=500,ni=3e4;function ri(e,t){let n=r=>r.slice(0,Ux);return X().filter(r=>t.includes(r.batchId)&&r.sessionId===e&&r.claimed&&(!r.ended||r.setAside===!0)&&!gr(r.batchId)).map(r=>{let s=r.keptScripts??[],{fixing:o,done:i,now:a,commands:c}=qx(r.batchId,{copy:de(r),scratch:le(r.batchId),kept:s}),l=o?"fixing":s.length>0?"kept":"new";return{batchId:r.batchId,setup:l,ready:r.readyAt??null,done:i&&n(i),now:a&&n(a),commands:c.map(n),...r.setAside?{aside:!0}:{}}})}function qx(e,t){let n=_n(e),r=new Map(n.flatMap(h=>h.e==="ended"?[h.call,h.same].filter(p=>p!==null).map(p=>[p,h.ended]):[])),s=h=>r.get(h.call)??r.get(h.same),o=n.filter(h=>h.e==="asked"),i=o.some(h=>h.kind==="file"?t.kept.some(p=>h.what===ti(t.copy,p)):s(h)==="failed"&&t.kept.some(p=>h.what.includes(p))),a=n.flatMap(h=>h.e==="output"?[h.path]:[]),c=o.filter(h=>!(h.kind==="command"&&(fr(h.what)||Ip(h.what)))&&!a.some(p=>h.what.includes(p))),l=c.at(-1),d=l!==void 0&&(l.bg===!0||s(l)===void 0),u=c.slice(0,d?-1:c.length).reverse().find(h=>h.bg===!0||s(h)==="ran");return{fixing:i,done:u?Yc(u):null,now:d?Yc(l):null,commands:c.filter(h=>h.kind==="command").slice(-2).map(h=>[t.copy,t.scratch].reduce((p,f)=>p.split(`${f}/`).join("").split(f).join("."),Kc(h.what)))}}var Dp=e=>_n(e).flatMap(t=>t.e==="asked"&&t.kind==="command"?[t.what]:[]),si=(e,t,n,r,s="",o=!1)=>Cs(e,{at:As(),e:"asked",...t,kind:n,what:n==="command"?Qo(r,Mp):Jc(r),...s?{say:Jc(s)}:{},...o?{bg:!0}:{}}),pr=(e,t,n,r="")=>Cs(e,{at:As(),e:"ended",call:t.call??null,same:t.same??null,ended:n,detail:Jc(r.split(`
|
|
1781
|
+
`)[0]??"")}),zc=(e,t,n,r)=>Cs(e,{at:As(),e:t,jobId:n,proof:r}),Wp=(e,t,n)=>Cs(e,{at:As(),e:"output",call:t,path:n}),Xc=e=>jp("sha256").update(e).digest("hex");function Bp(e,t,n){try{let r=ei(n);Cs(e,{at:As(),e:"wrote",sha:Xc(r)}),Zc(e,t,r.toString("utf8"))}catch{}}function Zc(e,t,n){n&&(_p(Vc(e),{recursive:!0,mode:448}),Fx(Lp(e,t),Qo(n,Mp),{mode:384}))}function Up(e){Ep(Ss(e),{force:!0}),Ep(Vc(e),{recursive:!0,force:!0})}function qp(e){let t=new Set;for(let n of _n(e))n.e==="asked"?t.add(n.call):n.e==="ended"&&n.call&&t.delete(n.call);return t}var gr=e=>_n(e).some(t=>t.e==="start"),Hp=e=>_n(e).find(t=>t.e==="start")?.at??null;function _n(e){try{return ei(Ss(e),"utf8").split(`
|
|
1782
|
+
`).filter(Boolean).flatMap(t=>{try{return[JSON.parse(t)]}catch{return[]}})}catch{return[]}}var Np=e=>{try{return ei(e,"utf8")}catch{return""}};function Gp(e,t,n){let r=_n(e),s=r.flatMap((u,h)=>u.e==="start"||u.e==="sent"?[{line:u,index:h}]:[]),o=s.filter(({line:u})=>u.e==="start"&&u.jobId===t&&u.proof===n).at(-1),i=o??s.at(-1),a=[];for(let u of r.slice(i?i.index+1:0))if(u.e==="asked")a.push({call:u.call,same:u.same,settled:!1,elsewhere:null,entry:{id:"",at:u.at,kind:u.kind,what:u.what,ended:"not_run",detail:"",output:""}});else if(u.e==="ended"){let h=a.find(p=>!p.settled&&(u.call?p.call===u.call:p.same===u.same));if(!h)continue;Object.assign(h.entry,{ended:u.ended,detail:u.detail}),h.settled=u.ended!=="not_run"}else if(u.e==="output"){let h=a.find(p=>p.call===u.call);h&&(h.elsewhere=u.path)}let c=a.slice(-Dx),l=Math.max(2e3,Math.min(Wx,Math.floor(Bx/Math.max(1,c.length))));c.forEach((u,h)=>{u.entry.id=`${n?`p${n}`:""}c${h+1}`,u.entry.what=Qo(u.entry.what,l),u.entry.ended!=="sent_back"&&(u.entry.output=Qo(Np(Lp(e,u.call))||(u.elsewhere?Np(u.elsewhere):""),l))});let d=s.find(({line:u})=>u.e==="start"&&u.jobId===t);return{calls:c.map(u=>u.entry),earlierCalls:a.length-c.length,minutes:i?Math.round((Date.now()-Date.parse(i.line.at))/6e3)/10:0,startedAt:o?Date.parse(o.line.at):null,jobStartedAt:d?Date.parse(d.line.at):null}}function Jp(e){let t=new Map,n=new Map,r=new Set;for(let s of _n(e))s.e==="asked"&&s.kind==="file"?t.set(s.call,s.what):s.e==="ended"&&s.ended==="ran"&&s.call&&t.has(s.call)?n.set(t.get(s.call),Date.parse(s.at)):s.e==="wrote"&&r.add(s.sha);return{paths:n,contents:r}}var Vx=Yx(Hx),mr=e=>`canary.batch=${e}`,yr=e=>`canary-${e}`;function Qp(e,t,n){try{let s=JSON.parse(Rs("docker",["inspect","--type",t,"--format",t==="container"||t==="image"?"{{json .Config.Labels}}":"{{json .Labels}}",n],{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","pipe"]}));return s?.["canary.batch"]===e||s?.["com.docker.compose.project"]===yr(e)}catch(r){return/no such/i.test(String(r.stderr??""))}}function Is(e,t){try{return Rs("ps",["-o",`${e}=`,"-p",String(t)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Kx(e){try{return zp(`/proc/${e}/cwd`)}catch{try{return Rs("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).split(`
|
|
1783
|
+
`).find(n=>n.startsWith("n"))?.slice(1)??null}catch{return null}}}function el(e,t){if(e<=1||e===process.pid||e===Number(process.env.CLAUDE_PID))return!1;let n=[de(t),le(t.batchId)].flatMap(r=>{try{return[Xp(r)]}catch{return[]}});for(let r=e,s=0;r>1&&s<64;s++){let o=Kx(r);if(o!==null&&n.some(i=>o===i||o.startsWith(i+Zp)))return!0;r=Number(Is("ppid",r)??0)}return!1}function zx(e){return Number(Is("pgid",e))===e}async function Xx(e,t){if(e.pid<=1)return!1;let n=Zt(e);return n!=="alive"?n==="gone":el(e.pid,t)?eg(e):!1}async function eg(e){let t=zx(e.pid)?-e.pid:e.pid,n=r=>{try{process.kill(t,r)}catch{}};n("SIGTERM");for(let r=0;r<50&&Zt(e)==="alive";r++)await new Promise(s=>setTimeout(s,100));return Zt(e)==="alive"&&n("SIGKILL"),await new Promise(r=>setTimeout(r,200)),Zt(e)==="gone"}function Zx(){let e=new Map;try{for(let r of Kp("/proc").filter(s=>/^\d+$/.test(s)))try{e.set(Number(r),zp(`/proc/${r}/cwd`))}catch{}if(e.size)return e}catch{}let t="";try{t=Rs("lsof",["-a","-d","cwd","-u",String(process.getuid?.()??""),"-Fpn"],{encoding:"utf8",timeout:15e3,maxBuffer:16*1024*1024,stdio:["ignore","pipe","ignore"]})}catch(r){t=String(r.stdout??"")}let n=0;for(let r of t.split(`
|
|
1784
|
+
`))r.startsWith("p")?n=Number(r.slice(1)):r.startsWith("n")&&n&&e.set(n,r.slice(1));return e}function Qx(e,t){let n;try{n=Gx(`/proc/${e}/environ`,"utf8").replace(/\0/g," ")}catch{try{n=Rs("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 eS(e){let t=new Set;for(let n=e,r=0;n>1&&r<64;r++)t.add(n),n=Number(Is("ppid",n)??0);return t}async function tS(e){let n=[le(e.batchId),...Hf(e.slot)===e.batchId?[de(e)]:[]].flatMap(i=>{try{return[Xp(i)]}catch{return[]}}),r=eS(process.pid),s=[],o=[];for(let i=0;i<3&&n.length;i++){s=[],o=[];let a=0;for(let[c,l]of Zx()){if(c<=1||r.has(c)||!n.some(f=>l===f||l.startsWith(f+Zp)))continue;let d=Rt(c);if(d===null)continue;let u=Jx(Is("comm",c)??"a process"),h=Qx(c,e.sessionId),p=Is("tty",c)??"?";h==="other"||h==="unknown"&&!p.startsWith("?")?o.push(`process ${c} (${u}) runs from this batch's folders, but its session didn't start it, so it was left running`):await eg({pid:c,startedAt:d})?a++:s.push(`process ${c} (${u}): it didn't stop`)}if(a===0)break}return{left:s,others:o}}async function Qc(e,t){let{stdout:n}=await Vx("docker",e,{timeout:t});return n.trim()}async function nS(e,t){let n=[],r=[`label=${mr(e)}`,`label=com.docker.compose.project=${yr(e)}`];try{await Qc(["version","--format","{{.Server.Version}}"],t)}catch(o){return o.code==="ENOENT"?n:[`Docker didn't answer, so containers labelled ${mr(e)} couldn't be checked`]}let s=[[["ps","-aq"],["rm","-f","-v"]],[["volume","ls","-q"],["volume","rm","-f"]],[["network","ls","-q"],["network","rm"]],[["image","ls","-q"],["image","rm","-f"]]];for(let[o,i]of s)for(let a of r)try{let c=[...new Set((await Qc([...o,"--filter",a],t)).split(`
|
|
1785
|
+
`).filter(Boolean))];c.length&&await Qc([...i,...c],t)}catch(c){n.push(`Docker ${o[0]==="ps"?"containers":o[0]+"s"} labelled ${a.slice(6)}: ${c instanceof Error?c.message.split(`
|
|
1786
|
+
`)[0]:String(c)}`)}return n}async function jn(e,t={}){let n=[],r=[];for(let a of e.processes)await Xx(a,e)||(r.push(a),n.push(`process ${a.pid} (${a.what}): it couldn't be confirmed as the one recorded, or didn't stop`));let s=await tS(e);n.push(...s.left);let o=e.left===void 0||e.dockerLeft===!0?await nS(e.batchId,t.dockerTimeoutMs??6e4):[];n.push(...o),Ho(e.batchId);let i=le(e.batchId);for(let a of rS(i).filter(c=>c!=="state.json"))try{Yp(Vp(i,a),{recursive:!0,force:!0})}catch(c){n.push(`${Vp(i,a)}: ${c instanceof Error?c.message.split(`
|
|
1787
|
+
`)[0]:String(c)}; it may hold files a container created as another user`)}return n.length?(ps({...e,processes:r,left:n,dockerLeft:o.length>0}),[...n,...s.others]):(Yp(i,{recursive:!0,force:!0}),Up(e.batchId),s.others)}function rS(e){try{return Kp(e)}catch{return[]}}async function tg(e){let t=[];for(let n of X().filter(r=>r.left)){let r=e?await jn(n,{dockerTimeoutMs:5e3}).catch(()=>n.left):n.left;t.push(...r.map(s=>`batch ${n.batchId}: ${s}`))}return t}w();import{execFile as sS}from"node:child_process";import{createHash as oS}from"node:crypto";import{appendFileSync as ig,copyFileSync as iS,createReadStream as aS,existsSync as nl,lstatSync as ag,mkdirSync as rl,mkdtempSync as cS,readFileSync as lS,rmSync as tl,statSync as ng,writeFileSync as cg}from"node:fs";import{tmpdir as uS}from"node:os";import{basename as dS,dirname as lg,isAbsolute as ug,join as Be,relative as hS}from"node:path";import{promisify as fS}from"node:util";var sl=fS(sS),rg=1024*1024,sg=1024*1024,pS=".canary-cache",Ts="refs/canary/head",dg=["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 hg(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 me(e,t,n){let{stdout:r}=await sl("git",[...dg.flatMap(s=>["-c",s]),"-C",e,...t],{env:hg(n),maxBuffer:67108864});return r}async function gS(e){let t=oS("sha256"),n=0;for await(let r of aS(e))t.update(r),n+=r.length;return{hash:t.digest("hex"),bytes:n}}async function mS(e,t){let n=async o=>{try{return(await sl("git",["-C",e,...o],{env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}})).stdout.trim()}catch{return""}},r=await n(["rev-parse","--path-format=absolute","--git-path","info/exclude"]);r&&nl(r)&&iS(r,Be(t,".git","info","exclude"));let s=await n(["config","--path","--get","core.excludesFile"]);s&&await me(t,["config","--local","core.excludesFile",s])}async function yS(e,t,n,r,s){await gg(t,n,r),await sl("git",["init","--quiet","--template=",s],{env:hg()}),await mg(e,t,n,s),await me(s,["checkout","--quiet","-B","canary-copy",n.headSha]),await yg(s,r)}async function fg(e,t,n,r,s){if(await gg(t,n,r),nl(Be(s,".git")))try{await mg(e,t,n,s),await me(s,["checkout","--quiet","--force","-B","canary-copy",n.headSha]),await me(s,["clean","--quiet","--force","-d"]);let o=(await me(s,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"])).split("\0");for(let i of o.filter(a=>a&&!a.endsWith("/")&&dS(a).startsWith(".env")))tl(Be(s,i),{force:!0});return await yg(s,r),!0}catch{}return tl(s,{recursive:!0,force:!0}),rl(lg(s),{recursive:!0,mode:448}),await yS(e,t,n,r,s),!1}var ol="canary-unset.invalid",og=/(?<![\w.-])(?:(?:[\w-]+\.)*localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\]|host\.docker\.internal)(?![\w.-])|(?<![\w:.])::1(?![\w:.])/gi;function pg(e,t,n){let r=[];for(let s of n)if(!(ug(s)||s.split("/").includes("..")))try{let o=Be(e,s);if(!ng(o).isFile())continue;if(nl(Be(t,s))){r.push({file:s,repointed:[]});continue}let i=[],a=lS(o,"utf8").split(`
|
|
1788
|
+
`).map(c=>{let l=/^(\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=)(.*)$/.exec(c);return!l||!l[3].match(og)?c:(i.push(l[2]),l[1]+l[3].replace(og,ol))}).join(`
|
|
1789
|
+
`);rl(lg(Be(t,s)),{recursive:!0}),ig(Be(t,".git","info","exclude"),`/${s}
|
|
1790
|
+
`),cg(Be(t,s),a,{mode:ng(o).mode&511}),r.push({file:s,repointed:i})}catch{}return r}async function gg(e,t,n){if(t.treeHash!==n)throw new Error("the kept snapshot isn't the code Canary planned these checks on");let{hash:r,bytes:s}=await gS(e);if(r!==t.sha256||s!==t.bytes)throw new Error("the kept snapshot doesn't match its receipt")}async function mg(e,t,n,r){await me(r,["bundle","unbundle",t]),await me(r,["update-ref","refs/canary/base",n.baseSha]),await me(r,["update-ref",Ts,n.headSha]),rl(Be(r,".git","info"),{recursive:!0}),cg(Be(r,".git","info","attributes"),`* -text -eol -ident -filter -working-tree-encoding
|
|
1791
|
+
`);for(let s of dg){let o=s.indexOf("=");await me(r,["config","--local",s.slice(0,o),s.slice(o+1)])}await mS(e,r),ig(Be(r,".git","info","exclude"),`
|
|
1792
|
+
/${pS}/
|
|
1793
|
+
`)}async function yg(e,t){let n=(await me(e,["rev-parse","HEAD^{tree}"])).trim(),r=await me(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(n!==t||r.length>0)throw new Error("the copy doesn't match the snapshot after checkout")}async function wg(e,t){let n=[];for(let r of new Set(t)){let s=hS(e,r);if(!(!s||s.startsWith("..")||ug(s)))try{await me(e,["cat-file","-e",`${Ts}:${s}`]),await me(e,["diff","--quiet",Ts,"--",s]),n.push(s)}catch{}}return n}async function bg(e,t){try{let n=(await me(e,["ls-tree","-r","-l","--full-tree","-z",t])).split("\0").flatMap(s=>{let o=/^\S+ blob \S+ +(\d+)\t(.+)$/s.exec(s);return o?[{bytes:Number(o[1]),path:o[2]}]:[]}),r=s=>{try{return ag(Be(e,s)).size}catch{return 0}};return{bytes:n.reduce((s,o)=>s+o.bytes,0),onDisk:n.reduce((s,o)=>s+Math.min(r(o.path),o.bytes),0)}}catch{return null}}async function kg(e){return(await me(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 vg(e){let t=cS(Be(uS(),"canary-diff-"));try{let n={GIT_INDEX_FILE:Be(t,"index")};await me(e,["read-tree",Ts],n),await me(e,["add","--update","--","."],n);let r=(await me(e,["ls-files","--others","--exclude-standard","-z"],n)).split("\0").filter(Boolean),s=[],o=r.filter(l=>{let d=ag(Be(e,l));return d.isFile()&&d.size>sg&&s.push(`[new file ${l}, ${d.size} bytes, not included]`),!(d.isFile()&&d.size>sg)});for(let l=0;l<o.length;l+=200)await me(e,["add","--",...o.slice(l,l+200)],n);let i=l=>me(e,["diff","--cached","--no-color","--no-ext-diff","--no-textconv","-U0",`--diff-filter=${l}`,Ts],n),a=await i("a")+await i("A");return Buffer.byteLength(a)>rg&&(a=`${Buffer.from(a).subarray(0,rg).toString("utf8")}
|
|
1775
1794
|
[diff cut at 1 MB]
|
|
1776
1795
|
`),[a,...s].filter(Boolean).join(`
|
|
1777
|
-
`)||null}finally{el(t,{recursive:!0,force:!0})}}w();import{createHash as $S}from"node:crypto";import{existsSync as NS,lstatSync as _S,readFileSync as il,realpathSync as cl,statSync as jS}from"node:fs";import{extname as Ag,join as _t,sep as PS}from"node:path";w();import{execFileSync as yS}from"node:child_process";import{readFileSync as kg}from"node:fs";import{basename as wS,join as bS}from"node:path";var kS=/(^|[_.-])(KEY|SECRET|TOKEN|PASS|PASSWORD|PASSWD|PWD|CREDENTIALS?|SALT|DSN)($|[_.-])/i,vS=8,Sg=/^[a-z]+$/;function vg(e){let t=[];for(let n of e.split(/\r?\n/)){let r=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/.exec(n);if(!r)continue;let s=r[2].trim(),o=/^(["'])(.*?)\1\s*(?:#.*)?$/.exec(s);t.push([r[1],o?o[2]:s.replace(/\s+#.*$/,"")])}return t}function xS(e){return/^[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:([^@\s]+)@/i.exec(e)?.[1]??null}function ol(e){let t=new Map,n=(s,o)=>{o.length>=vS&&!t.has(o)&&t.set(o,s)};try{let s=He(e);if(s)for(let[o,i]of vg(kg(Xe(s).secrets,"utf8")))n(o,i)}catch{}let r=[];try{r=yS("git",["-C",e,"ls-files","--others","--directory","-z"],{encoding:"utf8",maxBuffer:64*1024*1024}).split("\0")}catch{}for(let s of r.filter(o=>o&&!o.endsWith("/")&&wS(o).startsWith(".env"))){let o;try{o=kg(bS(e,s),"utf8")}catch{continue}for(let[i,a]of vg(o)){let c=xS(a);for(let l of[kS.test(i)?a:null,c])l&&!Sg.test(l)&&n(i,l)}}return[...t].map(([s,o])=>({name:o,value:s}))}var SS=[/\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],CS=/\b(?:cnry_|gh[pousr]_|github_pat_|glpat-|npm_|whsec_|xox[abprs]-|sk-(?:ant-)?|[sr]k_(?:live|test)_)[\w+/=-]{16,}/g,AS=/(["']?)\b([A-Za-z_][\w.-]*)\1(\s*(?::|=(?!=))\s*["']?)([^\s"',;&}<>]{8,})/g,IS=/(secret|token|passw(or)?d|credentials?|(api|private|access|secret|signing|encryption)[_.-]?key)$/i,xg=e=>/^[A-Za-z_]\w*(?:\??\.[A-Za-z_]\w*)*$/.test(e)&&/(secret|token|key|pass(w(or)?d)?|pwd?|credentials?)$/i.test(e),RS=/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|token)\s+)?)([\w.~+/=-]{8,})/gi,TS=/(\b(?:set-)?cookie["']?\s*[:=]\s*["']?)([^\r\n"']+)/gi,ES=/(\b[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:)([^@\s/]{8,})(?=@)/gi,OS=/([?&](?:code|state|ticket|nonce|token|access_token|id_token|code_challenge|code_verifier|challenge|signature)=)([\w.~+/-]{16,}={0,2})/gi,wr="values that look like tokens or keys";function Cg(e){let t=[...e].sort((r,s)=>s.value.length-r.value.length),n=new Map;return r=>{let s=new Set;for(let{name:i,value:a}of t)r.includes(a)&&(r=r.split(a).join(`<${i}>`),s.add(i));let o=i=>i.startsWith("<")||Sg.test(i)?i:(n.has(i)||n.set(i,n.size+1),s.add(wr),`<hidden-${n.get(i)}>`);for(let i of SS)r=r.replace(i,o);r=r.replace(CS,i=>/\d/.test(i)?o(i):i),r=r.replace(RS,(i,a,c)=>a+(xg(c)?c:o(c))),r=r.replace(TS,(i,a,c)=>a+c.replace(/=([^;\s]{16,})/g,(l,d)=>`=${o(d)}`)),r=r.replace(ES,(i,a,c)=>a+o(c)),r=r.replace(OS,(i,a,c)=>a+o(c)),r=r.replace(AS,(i,a,c,l,d)=>IS.test(c)&&!/[$(){}[\]]/.test(d)&&(/["']$/.test(l)||!xg(d))?i.slice(0,i.length-d.length)+o(d):i);for(let[i,a]of[...n].sort(([c],[l])=>l.length-c.length))r.includes(i)&&(r=r.split(i).join(`<hidden-${a}>`),s.add(wr));return{text:r,hidden:[...s]}}}var Ig=32*1024*1024,MS=256*1024*1024,Ts=e=>(t,n,r)=>{(typeof t!="string"||t.trim().length<e)&&r.push(`${n} must be ${e?"non-empty ":""}text`)},LS=(e,t,n)=>{(!Number.isInteger(e)||e<0)&&n.push(`${t} must be a whole number`)},sn=(...e)=>(t,n,r)=>{e.includes(t)||r.push(`${n} must be one of ${e.join(", ")}`)},ll=e=>(t,n,r)=>{t!==null&&e(t,n,r)},Ze=(e,t=0)=>(n,r,s)=>{if(!Array.isArray(n))return void s.push(`${r} must be a list`);n.length<t&&s.push(`${r} needs at least ${t} item`);for(let o=0;o<n.length;o++)e(n[o],`${r}[${o}]`,s)},at=e=>(t,n,r)=>{if(!t||typeof t!="object"||Array.isArray(t))return void r.push(`${n||"the file"} must be an object`);for(let[s,o]of Object.entries(e))s in t?o(t[s],n?`${n}.${s}`:s,r):r.push(`${n?`${n}.`:""}${s} is missing`)},ee=Ts(1),FS=at({steps:Ze(ee,1),files:Ze(ee),observe:ee}),DS=at({id:ee,kind:sn("command","request","ui_action","test","other"),action:ee,output:Ts(0),files:Ze(ee)}),WS=at({path:ee,mediaType:ee,bytes:LS,caption:Ts(0),frames:Ze(ee)}),BS=at({name:ee,kind:ee,class:sn("local","staging","production"),access:sn("read","write"),whyAllowed:ee}),US=at({part:ee,by:ee,version:ee,cannotShow:ee}),HS=at({asked:ee,answer:sn("granted","declined","unavailable"),source:sn("asked_this_run","canary_md")}),qS=at({by:sn("normal_use","put_in_place"),how:ee}),Eg={steps:Ze(DS),files:Ze(WS),targets:Ze(BS),standIns:Ze(US),permissions:Ze(HS),diff:ll(Ts(0)),reproduction:ll(FS)},GS=at({jobId:ee,claim:at({verdict:sn("broken","held","not_reproduced","cannot_run"),summary:ee,stepIds:Ze(ee)}),ranOn:at({where:sn("canary_computer","user_machine"),by:ee,environment:ee,commit:ee,target:Ts(0),services:Ze(ee)}),...Eg,couldNotRun:ll(at({tried:Ze(ee),proved:Ze(ee),missing:ee,whoCouldNotProvide:ee}))}),JS=at({jobId:ee,answer:ee,...Eg});function YS(e,t){let n=[];if((t==="pack"?GS:JS)(e,"",n),t==="pack"&&n.length===0){let r=e;r.claim.verdict==="cannot_run"!=(r.couldNotRun!==null)&&n.push("couldNotRun is set exactly when the claim is cannot_run"),r.claim.startingState!=null&&qS(r.claim.startingState,"claim.startingState",n)}return n}var Rg={".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"},Tg=e=>e.subarray(0,8e3).includes(0),VS=new Set(["path","id","jobId","commit","mediaType","verdict","kind","class","access","source","where"]);function Og(e,t,n,r,s){let o=t==="pack"?"pack.json":"delta.json",i;try{i=JSON.parse(il(_t(e,o),"utf8"))}catch(y){throw new _("no_pack",`Can't read ${_t(e,o)}: ${y instanceof Error?y.message:String(y)}`,"Write it first; canary jobs schema shows its format.")}if(!i||typeof i!="object"||Array.isArray(i))throw new _("invalid_pack",`${o} must hold one JSON object.`);i.jobId=n.jobId,i.diff=n.diff,i.observed=null,t==="pack"&&i.ranOn&&typeof i.ranOn=="object"&&Object.assign(i.ranOn,{where:"user_machine",commit:n.commit,tree:n.tree,uncommitted:n.uncommitted,warmCopy:n.warmCopy});for(let y of Array.isArray(i.files)?i.files:[])y&&typeof y=="object"&&typeof y.path=="string"&&(y.bytes=$n.test(y.path)&&al(e,y.path)||0),y&&typeof y=="object"&&(y.frames??=[]);for(let y of Array.isArray(i.steps)?i.steps:[])y&&typeof y=="object"&&(y.files??=[],y.output??="");let a=YS(i,t);if(a.length)throw new _("invalid_pack",`${o} doesn't fit the evidence format: ${a.slice(0,8).join("; ")}`,"Fix it and submit again; canary jobs schema shows the format.");let c=i,l=new Set;for(let y of c.files)[y.path,...y.frames].forEach(k=>l.add(k));for(let y of[...c.steps.flatMap(k=>k.files),...c.reproduction?.files??[],...n.scripts])l.has(y)||(l.add(y),$n.test(y)&&c.files.push({path:y,mediaType:Rg[Ag(y).toLowerCase()]??"application/octet-stream",bytes:al(e,y)??0,caption:"",frames:[]}));if("claim"in c){let y=new Set(c.steps.map(k=>k.id));for(let k of c.claim.stepIds)y.has(k)||a.push(`the claim cites step ${k}, which isn't in the pack`)}"claim"in c&&c.claim.verdict!=="cannot_run"&&!n.stopped&&!c.claim.startingState&&a.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 d=new Set(c.files.map(y=>y.path));for(let y of c.files)for(let k of y.frames)d.has(k)||a.push(`frame ${k} of ${y.path} needs its own entry in files`);for(let y of l)!$n.test(y)||y===o?a.push(`${y} isn't a usable evidence path (plain folder and file names, no leading dot)`):al(e,y)===null&&a.push(`${y} isn't a file inside ${e} (links that lead out of it don't count)`);if(a.length)throw new _("invalid_pack",`The evidence doesn't hold together: ${a.slice(0,8).join("; ")}`);let u=[...l].sort().map(y=>{let k=il(_t(e,y)),N=jS(_t(e,y)).mtimeMs,G=n.scripts.includes(y)?_t(n.scriptsFrom,y.slice(y.indexOf("/")+1)):null,ae=n.byHand.paths.get(cl(G&&NS(G)?G:_t(e,y)))!==void 0||n.byHand.contents.has(zc(k))?"hand":n.startedAt&&N<n.startedAt-2e3?"before":"run";return{path:y,by:ae,text:!Tg(k)}});c.observed={...n.observed,files:u};let h=n.observed.calls.some(y=>y.kind==="command"&&y.output.trim()!=="")||u.some(y=>y.by==="run"&&!y.text);if("claim"in c&&c.claim.verdict!=="cannot_run"&&!n.stopped&&!h)throw new _("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 p=new Map(c.files.map(y=>[y.path,y.mediaType])),f=[],g=Cg(s),m=(y,k)=>{let N=g(k);for(let G of N.hidden)f.push({name:G,path:y});return N.text},C=[...l].sort().map(y=>{let k=il(_t(e,y));return{path:y,data:k,text:k.length>Ig||Tg(k)?null:k.toString("utf8")}}),A=new Set(c.steps.map(y=>y.id)),b=y=>JSON.parse(JSON.stringify(c),(k,N)=>typeof N!="string"||VS.has(k)||l.has(N)||A.has(N)?N:y(N));for(let y of C)y.text!==null&&g(y.text);b(y=>g(y).text);let S=new Map;for(let{path:y,data:k,text:N}of C){let G=N===null?N:m(y,N);S.set(y,G===null||G===N?k:Buffer.from(G))}let x=b(y=>m(o,y));for(let y of x.files)y.bytes=S.get(y.path)?.length??y.bytes;let v=new Map([[o,Buffer.from(JSON.stringify(x,null,2))],...S]),I=[...v].map(([y,k])=>({path:y,mediaType:y===o?"application/json":p.get(y)??Rg[Ag(y).toLowerCase()]??"application/octet-stream",bytes:k.length,sha256:$S("sha256").update(k).digest("hex")})),$=I.filter(y=>y.bytes>Ig).map(y=>y.path);if($.length)throw new _("too_large",`Over 32 MB: ${$.join(", ")}.`,"Leave out what the scenario doesn't need, or trim long recordings.");if(I.reduce((y,k)=>y+k.bytes,0)>MS)throw new _("too_large","The evidence is over 256 MB in total.","Leave out what the scenario doesn't need, or trim long recordings.");return{pack:x,upload:{kind:t,proofRequestId:r,files:I},bytes:v,hidden:f}}function al(e,t){try{let n=cl(e);if(!cl(_t(e,t)).startsWith(n+PS))return null;let s=_S(_t(e,t));return s.isFile()?s.size:null}catch{return null}}var $g=`Evidence for one job: packs/<job>/pack.json in the batch folder, with any file it names beside it
|
|
1796
|
+
`)||null}finally{tl(t,{recursive:!0,force:!0})}}w();import{createHash as NS}from"node:crypto";import{existsSync as _S,lstatSync as jS,readFileSync as al,realpathSync as ll,statSync as PS}from"node:fs";import{extname as Rg,join as jt,sep as MS}from"node:path";w();import{execFileSync as wS}from"node:child_process";import{readFileSync as xg}from"node:fs";import{basename as bS,join as kS}from"node:path";var vS=/(^|[_.-])(KEY|SECRET|TOKEN|PASS|PASSWORD|PASSWD|PWD|CREDENTIALS?|SALT|DSN)($|[_.-])/i,xS=8,Ag=/^[a-z]+$/;function Sg(e){let t=[];for(let n of e.split(/\r?\n/)){let r=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/.exec(n);if(!r)continue;let s=r[2].trim(),o=/^(["'])(.*?)\1\s*(?:#.*)?$/.exec(s);t.push([r[1],o?o[2]:s.replace(/\s+#.*$/,"")])}return t}function SS(e){return/^[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:([^@\s]+)@/i.exec(e)?.[1]??null}function il(e){let t=new Map,n=(s,o)=>{o.length>=xS&&!t.has(o)&&t.set(o,s)};try{let s=qe(e);if(s)for(let[o,i]of Sg(xg(Ze(s).secrets,"utf8")))n(o,i)}catch{}let r=[];try{r=wS("git",["-C",e,"ls-files","--others","--directory","-z"],{encoding:"utf8",maxBuffer:64*1024*1024}).split("\0")}catch{}for(let s of r.filter(o=>o&&!o.endsWith("/")&&bS(o).startsWith(".env"))){let o;try{o=xg(kS(e,s),"utf8")}catch{continue}for(let[i,a]of Sg(o)){let c=SS(a);for(let l of[vS.test(i)?a:null,c])l&&!Ag.test(l)&&n(i,l)}}return[...t].map(([s,o])=>({name:o,value:s}))}var CS=[/\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],AS=/\b(?:cnry_|gh[pousr]_|github_pat_|glpat-|npm_|whsec_|xox[abprs]-|sk-(?:ant-)?|[sr]k_(?:live|test)_)[\w+/=-]{16,}/g,IS=/(["']?)\b([A-Za-z_][\w.-]*)\1(\s*(?::|=(?!=))\s*["']?)([^\s"',;&}<>]{8,})/g,RS=/(secret|token|passw(or)?d|credentials?|(api|private|access|secret|signing|encryption)[_.-]?key)$/i,Cg=e=>/^[A-Za-z_]\w*(?:\??\.[A-Za-z_]\w*)*$/.test(e)&&/(secret|token|key|pass(w(or)?d)?|pwd?|credentials?)$/i.test(e),TS=/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|token)\s+)?)([\w.~+/=-]{8,})/gi,ES=/(\b(?:set-)?cookie["']?\s*[:=]\s*["']?)([^\r\n"']+)/gi,OS=/(\b[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:)([^@\s/]{8,})(?=@)/gi,$S=/([?&](?:code|state|ticket|nonce|token|access_token|id_token|code_challenge|code_verifier|challenge|signature)=)([\w.~+/-]{16,}={0,2})/gi,wr="values that look like tokens or keys";function Ig(e){let t=[...e].sort((r,s)=>s.value.length-r.value.length),n=new Map;return r=>{let s=new Set;for(let{name:i,value:a}of t)r.includes(a)&&(r=r.split(a).join(`<${i}>`),s.add(i));let o=i=>i.startsWith("<")||Ag.test(i)?i:(n.has(i)||n.set(i,n.size+1),s.add(wr),`<hidden-${n.get(i)}>`);for(let i of CS)r=r.replace(i,o);r=r.replace(AS,i=>/\d/.test(i)?o(i):i),r=r.replace(TS,(i,a,c)=>a+(Cg(c)?c:o(c))),r=r.replace(ES,(i,a,c)=>a+c.replace(/=([^;\s]{16,})/g,(l,d)=>`=${o(d)}`)),r=r.replace(OS,(i,a,c)=>a+o(c)),r=r.replace($S,(i,a,c)=>a+o(c)),r=r.replace(IS,(i,a,c,l,d)=>RS.test(c)&&!/[$(){}[\]]/.test(d)&&(/["']$/.test(l)||!Cg(d))?i.slice(0,i.length-d.length)+o(d):i);for(let[i,a]of[...n].sort(([c],[l])=>l.length-c.length))r.includes(i)&&(r=r.split(i).join(`<hidden-${a}>`),s.add(wr));return{text:r,hidden:[...s]}}}var Tg=32*1024*1024,LS=256*1024*1024,Es=e=>(t,n,r)=>{(typeof t!="string"||t.trim().length<e)&&r.push(`${n} must be ${e?"non-empty ":""}text`)},FS=(e,t,n)=>{(!Number.isInteger(e)||e<0)&&n.push(`${t} must be a whole number`)},sn=(...e)=>(t,n,r)=>{e.includes(t)||r.push(`${n} must be one of ${e.join(", ")}`)},ul=e=>(t,n,r)=>{t!==null&&e(t,n,r)},Qe=(e,t=0)=>(n,r,s)=>{if(!Array.isArray(n))return void s.push(`${r} must be a list`);n.length<t&&s.push(`${r} needs at least ${t} item`);for(let o=0;o<n.length;o++)e(n[o],`${r}[${o}]`,s)},ct=e=>(t,n,r)=>{if(!t||typeof t!="object"||Array.isArray(t))return void r.push(`${n||"the file"} must be an object`);for(let[s,o]of Object.entries(e))s in t?o(t[s],n?`${n}.${s}`:s,r):r.push(`${n?`${n}.`:""}${s} is missing`)},te=Es(1),DS=ct({steps:Qe(te,1),files:Qe(te),observe:te}),WS=ct({id:te,kind:sn("command","request","ui_action","test","other"),action:te,output:Es(0),files:Qe(te)}),BS=ct({path:te,mediaType:te,bytes:FS,caption:Es(0),frames:Qe(te)}),US=ct({name:te,kind:te,class:sn("local","staging","production"),access:sn("read","write"),whyAllowed:te}),qS=ct({part:te,by:te,version:te,cannotShow:te}),HS=ct({asked:te,answer:sn("granted","declined","unavailable"),source:sn("asked_this_run","canary_md")}),GS=ct({by:sn("normal_use","put_in_place"),how:te}),$g={steps:Qe(WS),files:Qe(BS),targets:Qe(US),standIns:Qe(qS),permissions:Qe(HS),diff:ul(Es(0)),reproduction:ul(DS)},JS=ct({jobId:te,claim:ct({verdict:sn("broken","held","not_reproduced","cannot_run"),summary:te,stepIds:Qe(te)}),ranOn:ct({where:sn("canary_computer","user_machine"),by:te,environment:te,commit:te,target:Es(0),services:Qe(te)}),...$g,couldNotRun:ul(ct({tried:Qe(te),proved:Qe(te),missing:te,whoCouldNotProvide:te}))}),YS=ct({jobId:te,answer:te,...$g});function VS(e,t){let n=[];if((t==="pack"?JS:YS)(e,"",n),t==="pack"&&n.length===0){let r=e;r.claim.verdict==="cannot_run"!=(r.couldNotRun!==null)&&n.push("couldNotRun is set exactly when the claim is cannot_run"),r.claim.startingState!=null&&GS(r.claim.startingState,"claim.startingState",n)}return n}var Eg={".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"},Og=e=>e.subarray(0,8e3).includes(0),KS=new Set(["path","id","jobId","commit","mediaType","verdict","kind","class","access","source","where"]);function Ng(e,t,n,r,s){let o=t==="pack"?"pack.json":"delta.json",i;try{i=JSON.parse(al(jt(e,o),"utf8"))}catch(y){throw new _("no_pack",`Can't read ${jt(e,o)}: ${y instanceof Error?y.message:String(y)}`,"Write it first; canary jobs schema shows its format.")}if(!i||typeof i!="object"||Array.isArray(i))throw new _("invalid_pack",`${o} must hold one JSON object.`);i.jobId=n.jobId,i.diff=n.diff,i.observed=null,t==="pack"&&i.ranOn&&typeof i.ranOn=="object"&&Object.assign(i.ranOn,{where:"user_machine",commit:n.commit,tree:n.tree,uncommitted:n.uncommitted,warmCopy:n.warmCopy});for(let y of Array.isArray(i.files)?i.files:[])y&&typeof y=="object"&&typeof y.path=="string"&&(y.bytes=$n.test(y.path)&&cl(e,y.path)||0),y&&typeof y=="object"&&(y.frames??=[]);for(let y of Array.isArray(i.steps)?i.steps:[])y&&typeof y=="object"&&(y.files??=[],y.output??="");let a=VS(i,t);if(a.length)throw new _("invalid_pack",`${o} doesn't fit the evidence format: ${a.slice(0,8).join("; ")}`,"Fix it and submit again; canary jobs schema shows the format.");let c=i,l=new Set;for(let y of c.files)[y.path,...y.frames].forEach(k=>l.add(k));for(let y of[...c.steps.flatMap(k=>k.files),...c.reproduction?.files??[],...n.scripts])l.has(y)||(l.add(y),$n.test(y)&&c.files.push({path:y,mediaType:Eg[Rg(y).toLowerCase()]??"application/octet-stream",bytes:cl(e,y)??0,caption:"",frames:[]}));if("claim"in c){let y=new Set(c.steps.map(k=>k.id));for(let k of c.claim.stepIds)y.has(k)||a.push(`the claim cites step ${k}, which isn't in the pack`)}"claim"in c&&c.claim.verdict!=="cannot_run"&&!n.stopped&&!c.claim.startingState&&a.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 d=new Set(c.files.map(y=>y.path));for(let y of c.files)for(let k of y.frames)d.has(k)||a.push(`frame ${k} of ${y.path} needs its own entry in files`);for(let y of l)!$n.test(y)||y===o?a.push(`${y} isn't a usable evidence path (plain folder and file names, no leading dot)`):cl(e,y)===null&&a.push(`${y} isn't a file inside ${e} (links that lead out of it don't count)`);if(a.length)throw new _("invalid_pack",`The evidence doesn't hold together: ${a.slice(0,8).join("; ")}`);let u=[...l].sort().map(y=>{let k=al(jt(e,y)),N=PS(jt(e,y)).mtimeMs,G=n.scripts.includes(y)?jt(n.scriptsFrom,y.slice(y.indexOf("/")+1)):null,ae=n.byHand.paths.get(ll(G&&_S(G)?G:jt(e,y)))!==void 0||n.byHand.contents.has(Xc(k))?"hand":n.startedAt&&N<n.startedAt-2e3?"before":"run";return{path:y,by:ae,text:!Og(k)}});c.observed={...n.observed,files:u};let h=n.observed.calls.some(y=>y.kind==="command"&&y.output.trim()!=="")||u.some(y=>y.by==="run"&&!y.text);if("claim"in c&&c.claim.verdict!=="cannot_run"&&!n.stopped&&!h)throw new _("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 p=new Map(c.files.map(y=>[y.path,y.mediaType])),f=[],g=Ig(s),m=(y,k)=>{let N=g(k);for(let G of N.hidden)f.push({name:G,path:y});return N.text},C=[...l].sort().map(y=>{let k=al(jt(e,y));return{path:y,data:k,text:k.length>Tg||Og(k)?null:k.toString("utf8")}}),A=new Set(c.steps.map(y=>y.id)),b=y=>JSON.parse(JSON.stringify(c),(k,N)=>typeof N!="string"||KS.has(k)||l.has(N)||A.has(N)?N:y(N));for(let y of C)y.text!==null&&g(y.text);b(y=>g(y).text);let S=new Map;for(let{path:y,data:k,text:N}of C){let G=N===null?N:m(y,N);S.set(y,G===null||G===N?k:Buffer.from(G))}let x=b(y=>m(o,y));for(let y of x.files)y.bytes=S.get(y.path)?.length??y.bytes;let v=new Map([[o,Buffer.from(JSON.stringify(x,null,2))],...S]),I=[...v].map(([y,k])=>({path:y,mediaType:y===o?"application/json":p.get(y)??Eg[Rg(y).toLowerCase()]??"application/octet-stream",bytes:k.length,sha256:NS("sha256").update(k).digest("hex")})),$=I.filter(y=>y.bytes>Tg).map(y=>y.path);if($.length)throw new _("too_large",`Over 32 MB: ${$.join(", ")}.`,"Leave out what the scenario doesn't need, or trim long recordings.");if(I.reduce((y,k)=>y+k.bytes,0)>LS)throw new _("too_large","The evidence is over 256 MB in total.","Leave out what the scenario doesn't need, or trim long recordings.");return{pack:x,upload:{kind:t,proofRequestId:r,files:I},bytes:v,hidden:f}}function cl(e,t){try{let n=ll(e);if(!ll(jt(e,t)).startsWith(n+MS))return null;let s=jS(jt(e,t));return s.isFile()?s.size:null}catch{return null}}var _g=`Evidence for one job: packs/<job>/pack.json in the batch folder, with any file it names beside it
|
|
1778
1797
|
(paths relative to that folder, plain names, no leading dot).
|
|
1779
1798
|
|
|
1780
1799
|
What came back is not yours to write. Canary captures what every command you run prints, and notes
|
|
@@ -1817,47 +1836,47 @@ reproduction may be null when nothing broke.
|
|
|
1817
1836
|
An answer to request <n>: packs/<job>/proof-<n>/delta.json, with only new steps and files; a file
|
|
1818
1837
|
needs a path not already sent with the job. Its reproduction, when not null, replaces the job's:
|
|
1819
1838
|
{ "answer": "what was done, or why it couldn't be", "steps": [], "files": [], "targets": [], "standIns": [],
|
|
1820
|
-
"permissions": [], "reproduction": null }`;w();import{homedir as
|
|
1821
|
-
`,n)+1||e.length+1)-1),s=[],o=t,i=[],a=null,c=null,l="word",d=f=>f.startsWith("~/")?
|
|
1822
|
-
`||g===";"||g==="|"||g==="&"?p():g==="("||g===")"?(p(),g===")"&&o!==t&&(o=null)):/\s/.test(g)?h():a=(a??"")+g}return p(),s}w();import{basename as br,dirname as
|
|
1823
|
-
`),n=[];for(let r=0;r<t.length;r++){n.push(t[r]);let s=/<<-?\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(t[r]),o=s?t.findIndex((a,c)=>c>r&&a.trim()===s[2]):-1;if(!s||o<0)continue;let i=t[r].slice(0,s.index).split(/[|;&]+/).pop().trim().split(/\s+/).find(a=>!ci.test(a)&&!
|
|
1824
|
-
`)}function
|
|
1839
|
+
"permissions": [], "reproduction": null }`;w();import{homedir as zS}from"node:os";import{basename as oi,isAbsolute as XS,join as ZS,resolve as QS}from"node:path";var jg=e=>!/[$`*?]/.test(e);function Pg(e,t){let n=e.indexOf("<<"),r=n===-1?e:e.slice(0,(e.indexOf(`
|
|
1840
|
+
`,n)+1||e.length+1)-1),s=[],o=t,i=[],a=null,c=null,l="word",d=f=>f.startsWith("~/")?ZS(zS(),f.slice(2)):XS(f)?f:o===null?null:QS(o,f),u=f=>{let g=jg(f)?d(f):null;g&&s.push(g)},h=()=>{a!==null&&(l==="target"?u(a):l==="word"&&i.push(a),a=null,l="word")},p=()=>{h();let[f,...g]=i[0]==="sudo"||i[0]==="command"?i.slice(1):i,m=g.filter(b=>!b.startsWith("-")),C=oi(f??"");C==="cd"?o=m[0]&&jg(m[0])?d(m[0]):null:(C==="cp"||C==="mv")&&m.length>1?u(m.at(-1)):(C==="tee"||C==="touch"||C==="mkdir")&&m.forEach(u);let A=i.findIndex(b=>oi(b)==="curl"||oi(b)==="wget");if(A!==-1){let b=oi(i[A])==="wget",S=b?"--output-document":"--output",x=b?/^-[a-zA-Z]*O$/:/^-[a-zA-Z]*o$/,v=i.slice(A+1);v.forEach((I,$)=>{I.startsWith(`${S}=`)?u(I.slice(S.length+1)):(I===S||x.test(I))&&v[$+1]&&v[$+1]!=="-"&&u(v[$+1])})}i=[]};for(let f=0;f<r.length;f++){let g=r[f];if(c)g===c?c=null:a=(a??"")+g;else if(g==="'"||g==='"')c=g,a??="";else if(g==="\\")a=(a??"")+(r[++f]??"");else if(g===">"||g==="<"){for(a!==null&&/^\d+$/.test(a)?a=null:h();r[f+1]===g||r[f+1]==="-";)f++;if(r[f+1]==="&"||r[f+1]==="("){for(;f+1<r.length&&!/[\s;|)]/.test(r[f+1]);)f++;continue}l=g===">"?"target":"skip"}else g===`
|
|
1841
|
+
`||g===";"||g==="|"||g==="&"?p():g==="("||g===")"?(p(),g===")"&&o!==t&&(o=null)):/\s/.test(g)?h():a=(a??"")+g}return p(),s}w();import{basename as br,dirname as e1,isAbsolute as dl,join as t1,resolve as ii,sep as hl}from"node:path";var Pt=e=>({reason:e,shared:!1}),fl=e=>({reason:e,shared:!0}),Dg=new Set(["sudo","env","command","exec","time","nohup","nice","xargs"]),Wg=new Set(["bash","sh","zsh","source","."]),Mg=new Set(["rm","rmdir","unlink","shred","trash"]),n1=new Set(["node","python","python3","ruby","perl","deno","bun"]),r1=/\b(rmSync|rmdirSync|unlinkSync|rmtree|removedirs|FileUtils\.rm\w*|File\.delete)\b|\b(fs|fsp|os|shutil)\.(rm|rmdir|unlink|remove)\b|\bunlink\s*\(/,s1=new Set(["psql","mysql","mariadb","mongosh","mongo","redis-cli","cockroach","clickhouse-client","sqlcmd"]),o1=new Set(["dropdb","dropuser"]),i1=/\b(drop\s+(table|database|schema|index|collection)|truncate(\s+table)?\s+\w+|delete\s+from|flushall|flushdb|dropdatabase|deletemany)\b|\.drop\(/i,a1={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/},c1=new Set(["-H","--host","--context","--config","-c","-l","--log-level"]),l1=new Set(["-p","--project-name","-f","--file","--profile","--env-file","--project-directory"]),Lg=new Set(["volume","network","container","image","system","builder"]),ai="",on="",u1=new Set(["export","local","readonly","declare","typeset"]),Fg=new Set(["{","}","then","do","else","elif","if","while","until","!","fi","done"]),ci=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;function pl(e,t){let n=0,r=null;for(let s=t+2;s<e.length;s++){let o=e[s];if(o==="$"&&e[s+1]==="("&&r!=="'"){s=pl(e,s)-1;continue}if(r){o===r&&(r=null);continue}if(o==="'"||o==='"')r=o;else if(o==="(")n++;else if(o===")"&&n--===0)return s+1}return e.length}function d1(e){let t=e.split(`
|
|
1842
|
+
`),n=[];for(let r=0;r<t.length;r++){n.push(t[r]);let s=/<<-?\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(t[r]),o=s?t.findIndex((a,c)=>c>r&&a.trim()===s[2]):-1;if(!s||o<0)continue;let i=t[r].slice(0,s.index).split(/[|;&]+/).pop().trim().split(/\s+/).find(a=>!ci.test(a)&&!Dg.has(br(a)));Wg.has(br(i??""))||(r=o)}return n.join(`
|
|
1843
|
+
`)}function h1(e){let t=[],n=[],r=null,s=null,o=()=>{r!==null&&n.push(r),r=null},i=()=>{o(),n.length&&t.push(n),n=[]},a=e.replace(/\\\n/g," ");for(let c=0;c<a.length;c++){let l=a[c];if(l==="$"&&a[c+1]==="("&&s!=="'"){let d=pl(a,c);r=(r??"")+a.slice(c,d),c=d-1;continue}if(s){l===s?s=null:r+=s==="'"&&l==="$"?ai:l;continue}if(l==="'"||l==='"'){s=l,r??="";continue}if(l==="("||l===")"){i(),t.push([l]);continue}if(l==="#"&&r===null){for(;c<a.length&&a[c]!==`
|
|
1825
1844
|
`;)c++;i();continue}if(l===`
|
|
1826
|
-
`||l===";"||l==="|"||l==="&"){i();continue}if(l===" "||l===" "){o();continue}r=(r??"")+l}return i(),t}var
|
|
1827
|
-
`,{flag:"wx"}),{...o,path:i}}throw new _("question_ids","Couldn't number a new question; run the command again.")}function
|
|
1845
|
+
`||l===";"||l==="|"||l==="&"){i();continue}if(l===" "||l===" "){o();continue}r=(r??"")+l}return i(),t}var f1=(e,t)=>e.replace(/\$\{BASH_SOURCE(?:\[0\])?\}|\$BASH_SOURCE(?:\[0\])?|\$\{0\}|\$0(?![0-9])/g,t);function li(e,t,n=0,r=null,s=new Map){let o=f=>t.roots.some(g=>f===g||f.startsWith(g.endsWith(hl)?g:g+hl)),i=t.cwd,a=new Map([["HOME",t.home],...s]),c=f=>{let g=f.replace(/\$\$/g,"PID");for(let m=g.lastIndexOf("$(");m>=0;m=g.lastIndexOf("$(")){let C=pl(g,m);g=g.slice(0,m)+(d(g.slice(m+2,C-1).trim())??on)+g.slice(C)}return g.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(m,C,A,b)=>{let S=(C??b)==="PWD"?i:a.get(C??b);return typeof S=="string"?S:A===void 0?on:c(A)}).replace(/\$\{[^}]*\}|`[^`]*`|[$`]/g,on)},l=f=>{let g=c(f);return g.includes(on)?null:g.split(ai).join("$")},d=f=>{let g=/^(?:cd\s+(?:--\s+)?(.+?)\s*(?:&&|;)\s*pwd(?:\s+-P)?|dirname\s+(?:--\s+)?(.+)|pwd(?:\s+-P)?)$/s.exec(f);if(!g)return null;let m=g[1]??g[2];if(m===void 0)return i;let C=l(m.replace(/^(["'])(.*)\1$/s,"$2"));if(C===null||i===null&&!dl(C))return null;let A=dl(C)?ii(C):ii(i,C);return g[2]===void 0?A:e1(A)},u=new Set,h=i1.test(e),p=[];for(let f of h1(d1(r?f1(e,r):e))){if(f[0]==="("){p.push(i);continue}if(f[0]===")"){i=p.pop()??i;continue}let g=f.slice(f.findIndex(T=>!Fg.has(T)));if(f.every(T=>Fg.has(T)))continue;if(g[0]==="for"&&g[2]==="in"&&g[1]){let T=g.slice(3).map(l);a.set(g[1],T.length>0&&T.every(M=>M!==null&&/^[\w@%+=:,-][\w.@%+=:,-]*$/.test(M))?T[0]:on);continue}let m=u1.has(g[0])?g.slice(1).filter(T=>!T.startsWith("-")):g,C=m.findIndex(T=>!ci.test(T)),A=new Map;for(let T of C<0?m:m.slice(0,C)){let[,M,E]=ci.exec(T),U=/^\$\(\s*mktemp\b/.test(E)?t1(t.roots[0]??t.cwd,".tmp"):c(E);C<0?a.set(M,U):U.includes(on)||A.set(M,U)}if(C<0)continue;let b=m.slice(C).map(T=>{let M=c(T),E=M.includes(on);return{text:E?T:M.split(ai).join("$"),opaque:E,known:E?M.slice(0,M.indexOf(on)):""}}),S=T=>{if(T.opaque)return null;let M=T.text.split(/[*?[{]/)[0],E=M==="~"||M.startsWith("~/")?t.home+M.slice(1):M;return dl(E)?ii(E):i===null?null:ii(i,E)},x=T=>{let M=T.opaque&&T.known&&!/(^|\/)\.\.(\/|$)/.test(T.text)?T.known.slice(0,T.known.lastIndexOf("/")+1)||".":null,E=S(M?{text:M,opaque:!1,known:""}:T);return E===null||!(o(E)||[...u].some(U=>E===U||E.startsWith(U+hl)))},v=b.filter((T,M)=>{let E=/^\d*>>?(.*)$/.exec(T.text),U=/^\d*>>?$/.test(b[M-1]?.text??""),J=E?.[1]?{...T,text:E[1]}:U?T:null,ne=J&&S(J);return ne&&ne!=="/dev/null"&&u.add(ne),!E&&!U&&!/^\d*<</.test(T.text)&&!/^\d*</.test(T.text)});if(v.length===0)continue;let I=v,$=!1;for(;I.length>1&&(Dg.has(br(I[0].text))||ci.test(I[0].text)||I!==v&&I[0].text.startsWith("-"));)$||=br(I[0].text)==="xargs",I=I.slice(1);let y=br(I[0].text),k=I.slice(1),N=k.filter(T=>!T.text.startsWith("-")),G=(...T)=>k.some(M=>T.includes(M.text)),Le=I.map(T=>T.text).join(" ");if(y==="cd"){i=N[0]?S(N[0]):null;continue}if(["touch","mkdir","tee","mkfifo"].includes(y)){for(let T of N){let M=S(T);M&&u.add(M)}continue}let Ce=()=>new Map(a);if(y==="trap"||y==="eval"){let T=m.slice(C+(v.length-I.length)+1).find(E=>!E.startsWith("-")),M=T===void 0?null:li(T.split(ai).join("$"),{...t,cwd:i??t.cwd},n+1,r,Ce());if(M)return M;continue}if(Wg.has(y)){let T=k.findIndex(J=>/^-[a-z]*c[a-z]*$/.test(J.text)),M=T<0&&N[0]?S(N[0]):null,E=T>=0?k[T+1]?.text??null:M&&o(M)&&n<2?t.read(M):null,U=E===null?null:li(E,{...t,cwd:i??t.cwd},n+1,T>=0?r:M,T>=0?Ce():A);if(U)return U;continue}if(Mg.has(y)){if($)return Pt("it removes whatever files it is handed");let T=N.find(x);if(T)return Pt(`it removes ${T.text}, which isn't in the checks' own folders`);continue}if(y==="mv"){if($)return Pt("it moves away whatever files it is handed");let T=G("-t","--target-directory"),M=(T?N:N.slice(0,-1)).find(x);if(M)return Pt(`it moves ${M.text} away, which isn't in the checks' own folders`);let E=T?null:N.at(-1)&&S(N.at(-1));E&&u.add(E);continue}if(y==="find"){let T=k.some((U,J)=>U.text==="-delete"||["-exec","-execdir","-ok"].includes(U.text)&&Mg.has(br(k[J+1]?.text??""))),M=k.findIndex(U=>U.text.startsWith("-")||U.text==="("||U.text==="!"),E=M<0?k:k.slice(0,M);if(T&&(E.length===0||E.some(x)))return Pt("it deletes files it finds outside the checks' own folders");continue}if(n1.has(y)){let T=k.findIndex(M=>["-e","-c","--eval","-p"].includes(M.text));if(T>=0&&r1.test(k[T+1]?.text??""))return Pt("it removes files from code given on the command line");continue}if(y==="git"){let T=k.findIndex(J=>J.text==="-C"),M=T>=0&&k[T+1]?S(k[T+1]):i,E=k.filter((J,ne)=>!J.text.startsWith("-")&&!(T>=0&&ne===T+1)).map(J=>J.text);if(E[0]==="push"&&(G("--delete","-d")||E.slice(1).some(J=>J.startsWith(":"))))return fl("it deletes a branch or tag on a remote");if((E[0]==="clean"||E[0]==="restore"||E[0]==="rm"||E[0]==="reset"&&G("--hard")||E[0]==="checkout"&&(G("--","-f","--force")||E.includes("."))||E[0]==="stash"&&["drop","clear"].includes(E[1]??"")||["branch","tag"].includes(E[0]??"")&&G("-D","-d","--delete")||E[0]==="worktree"&&E[1]==="remove")&&(M===null||!o(M)))return Pt("it discards or deletes git work outside the checks' own copy");continue}if(y==="docker"||y==="podman"||y==="docker-compose"){let T=k.findIndex((we,Bn)=>!we.text.startsWith("-")&&!c1.has(k[Bn-1]?.text??"")),M=y==="docker-compose"||k[T]?.text==="compose",E=M?l1:new Set(["--filter"]),U=T<0?[]:k.slice(y==="docker-compose"?0:M?T+1:T),J=U.filter((we,Bn)=>!we.text.startsWith("-")&&!E.has(U[Bn-1]?.text??"")),ne=J.map(we=>we.text),Ye=M?["down","rm"].includes(ne[0]??""):["rm","rmi","prune"].includes(ne[0]??"")||Lg.has(ne[0]??"")&&["rm","remove","prune"].includes(ne[1]??""),St=k.findIndex(we=>we.text==="-p"||we.text==="--project-name"),et=St>=0?k[St+1]?.text:k.find(we=>we.text.startsWith("--project-name="))?.text.slice(15),z=M&&(et===t.composeProject||et===void 0&&i!==null&&o(i)),gt=k.some(we=>we.text===`label=${t.label}`||we.text===`--filter=label=${t.label}`),Ct=Lg.has(ne[0]??""),At=M||(Ct?ne[1]:ne[0])==="prune"?null:ne[0]==="rmi"||ne[0]==="image"?"image":ne[0]==="network"||ne[0]==="volume"?ne[0]:"container",_r=J.slice(Ct?2:1),Ws=y==="docker"&&At!==null&&_r.length>0&&_r.every(we=>!we.opaque&&t.dockerOwn?.(At,we.text)===!0);if(Ye&&!z&&!gt&&!Ws)return Pt("it removes Docker containers, images or volumes that may not be the checks' own");continue}let ae=o1.has(y)||y==="mysqladmin"&&N.some(T=>T.text==="drop");if(s1.has(y)||y==="sqlite3"||ae){let T=y==="sqlite3"?N.length>0&&!x(N[0]):p1(Le,t.ports)&&!/(?:\s-h|--host)[= ]+(?!localhost\b|127\.0\.0\.1\b)\S/.test(Le);if((h||ae)&&!T)return y==="sqlite3"?Pt("it drops or deletes data in a database file that isn't the checks' own"):fl("it drops or deletes data in a database the checks didn't start");continue}if(a1[y]?.test(k.map(T=>T.text).join(" ")))return fl(`it deletes something with ${y}`)}return null}function p1(e,[t,n]){let r=[...e.matchAll(/(?:(?:localhost|127\.0\.0\.1):|\s(?:-p|-P|--port)[= ]?)(\d{2,5})\b/g)].map(s=>Number(s[1]));return r.length>0&&r.every(s=>s>=t&&s<=n)}w();function Bg(e){let t=e.replace(/'[^']*'/g,"''"),n=t.split(/&&|\|\||[;|\n]/).map(r=>r.trimStart());return n.some(r=>/^[A-Za-z_][A-Za-z0-9_]*=/.test(r))?"it starts by setting a shell variable":/\$[A-Za-z_{(]|`/.test(t)?"it uses a shell variable or command substitution":n.some(r=>/^cd(\s|$)/.test(r))?"it changes directory":null}var Ug=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.`;w();import{existsSync as g1,mkdirSync as qg,readdirSync as Hg,writeFileSync as gl}from"node:fs";import{join as kr}from"node:path";var ml=e=>kr(ce(e),"questions");function lt(e){let t=[];for(let{runId:n}of e){let r=ml(n);if(g1(r))for(let s of Hg(r).filter(o=>/^Q\d+\.json$/.test(o))){let o=Y(kr(r,s));o&&t.push({...o,path:kr(r,s)})}}return t.sort((n,r)=>Number(n.id.slice(1))-Number(r.id.slice(1)))}function Gg(e,t){let n=kr(Ze(En(e)).dir,"question-ids");qg(n,{recursive:!0}),qg(ml(t.runId),{recursive:!0});for(let r=0;r<100;r++){let s=Math.max(0,...Hg(n).map(a=>Number(/^Q(\d+)$/.exec(a)?.[1]??0)))+1+r;try{gl(kr(n,`Q${s}`),t.runId,{flag:"wx"})}catch(a){if(a.code==="EEXIST")continue;throw a}let o={...t,id:`Q${s}`,askedAt:new Date().toISOString(),status:"open",answer:null,answeredAt:null},i=kr(ml(t.runId),`${o.id}.json`);return gl(i,JSON.stringify(o,null,2)+`
|
|
1846
|
+
`,{flag:"wx"}),{...o,path:i}}throw new _("question_ids","Couldn't number a new question; run the command again.")}function Jg(e,t){let n=lt(e).find(r=>r.id.toLowerCase()===t.toLowerCase());if(!n)throw new _("no_such_question",`No question ${t} among this session's checks.`,"Use the id the listener printed.");return n}function Yg(e,t,n,r=[]){let{path:s,...o}=e,i=new Date().toISOString(),a=[...new Set([...o.userWords??[],...r])],c=o.status==="answered"?{...o,more:[...o.more??[],{text:t,at:i}],userSpoke:o.userSpoke||n,userWords:a}:{...o,status:"answered",answer:t,answeredAt:i,userSpoke:n,userWords:a};return Pe(s,c,420),c}function yl(e){let t=Y(e),r=(t?.status==="answered"?[t.answer??"",...(t.more??[]).map(s=>s.text)]:[]).flatMap((s,o)=>{try{return gl(`${e}.given-${o}`,"",{flag:"wx"}),[{text:s,index:o}]}catch{return[]}});return{first:r.some(s=>s.index===0),texts:r.map(s=>s.text)}}function Pn(e,t,n){for(let r of lt(e).filter(s=>s.batchId===t&&(n==="all"||s.jobId===n)&&s.status==="open")){let{path:s,...o}=r;Pe(s,{...o,status:"expired"},420)}}function Vg(e){return Y(e)}var Ge=6e4,C1=9.5*Ge,A1=9*Ge,I1=5*Ge,vr=5e3,Ln=2*Ge,em=5*Ge,Ns=5e3,R1=1500,T1=e=>6e4+Math.ceil(e/131),xr=e=>e.slice(0,8),Tl=e=>`verifier-${xr(e)}`,an=e=>new Promise(t=>setTimeout(t,e)),R=e=>void process.stdout.write(`${e}
|
|
1828
1847
|
`),di=460;function Mn(e){for(let t of e.split(`
|
|
1829
|
-
`)){let n=t;for(;n.length>di;){let r=n.lastIndexOf(" ",di),s=r>di/2?r:di;R(`${n.slice(0,s)} \u2026`),n=`\u2026 ${n.slice(s).trimStart()}`}R(n)}}var hi=e=>e.map(t=>t.trim().replace(/[.!?]+$/,n=>n.includes("?")?"?":"")).join(" | ").replace(/([^?])$/,"$1.");function Rr(e=process.cwd()){try{return
|
|
1848
|
+
`)){let n=t;for(;n.length>di;){let r=n.lastIndexOf(" ",di),s=r>di/2?r:di;R(`${n.slice(0,s)} \u2026`),n=`\u2026 ${n.slice(s).trimStart()}`}R(n)}}var hi=e=>e.map(t=>t.trim().replace(/[.!?]+$/,n=>n.includes("?")?"?":"")).join(" | ").replace(/([^?])$/,"$1.");function Rr(e=process.cwd()){try{return Xg("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||e}catch{return e}}var bi=e=>oe("/cli/jobs",{session:e}),Je=e=>Object.entries(it(e).runs).map(([t,{checkout:n}])=>({runId:t,checkout:n}));function tm(e){try{if(!Te(P(ce(e),"source.bundle")))return[];let t=P(ce(e),"results");return yi(t).filter(n=>n.endsWith(".json")).flatMap(n=>{let r=Y(P(t,n));return r?.verdict==="blocked"?[`${JSON.stringify(r.scenario.title)} [${r.jobId}]`]:[]})}catch{return[]}}var _s=e=>tm(e).length>0;async function E1(){let e=process.env.CLAUDE_CODE_SESSION_ID?.trim();if(!e)return;let t=Je(e).filter(({runId:r})=>Te(P(ce(r),"source.bundle")));if(t.length===0)return;let n=new Set((await oe("/cli/jobs",{session:e,timeoutMs:5e3})).runs.map(r=>r.runId));for(let{runId:r}of t)!n.has(r)&&!_s(r)&&Dn(P(ce(r),"source.bundle"),{force:!0})}function ye(e,t={}){return async(...n)=>{try{if(t.sweep!==!1){Ef(),t.urgent||await Qf(async r=>void await jn(r,{dockerTimeoutMs:5e3}));for(let r of await tg(!t.urgent&&!t.local))console.error(`Canary left in place from ${r}`);t.local||await E1().catch(()=>{})}await e(...n)}catch(r){if(r instanceof _||r instanceof L)console.error(`${Ko(r)?"Stop":"Error"}: ${r.message}`),r.fix&&console.error(`Next: ${r.fix}`);else{console.error(`Error: ${rn}`);let s=process.env.CLAUDE_CODE_SESSION_ID?.trim();s&&await xs(s,{},r,5e3).catch(()=>{})}process.exitCode=1}}}function xt(e,t){let n=en(e);return t(n),ps(n),n}var O1=["environment_missing","information_unavailable","approval_declined","target_unreachable","tool_install_failed","auto_mode_blocked"],$1={broken:"failed",held:"passed",not_reproduced:"unclear",inconclusive:"unclear",blocked:"couldn't run"},El=e=>e&&$1[e]||"no verdict",nm=e=>e.blockedReason?.kind==="stopped_by_user"?"stopped by the user":e.blockedReason?.kind==="to_prove"?"not tried yet":El(e.verdict),Os=(e,t)=>t.verdict==="blocked"?nm(Y(P(ce(e),"results",`${t.jobId}.json`))??{verdict:t.verdict,blockedReason:null}):El(t.verdict);function Ol(e){let t=qe(e);return(t&&Y(P(Ze(t).scripts,pi)))??{}}function kl(e){let t=Je(Ae()).find(r=>r.runId===e)?.checkout,n=Object.entries(t?Ol(t):{}).map(([r,s])=>`${r} (${s.what})`);return n.length?` Another try starts setup from what earlier tries kept: ${n.join("; ")}.`:""}function rm(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 sm(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}${N1(t,e.whereToLook)}`]:[]]}function N1(e,t){let n=/^(.+?):(\d+)(?:-(\d+))?$/.exec(t.trim()),r=Y(P(ce(e),"source.json")),s=Je(Ae()).find(a=>a.runId===e)?.checkout,o=s?qe(s):null;if(!n||!r?.baseTreeHash||!r.treeHash||r.baseTreeHash===r.treeHash||!o)return"";let i=P(H(),"workspaces",ir(o));for(let a of Te(i)?yi(i).filter(c=>/^\d+$/.test(c)):[]){let c;try{c=Xg("git",["-C",P(i,a),"diff","--no-color","-U0",r.baseTreeHash,r.treeHash,"--",n[1]],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{continue}let l=[...c.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gm)].map(h=>[Number(h[1]),Number(h[1])+Math.max(h[2]===void 0?1:Number(h[2]),1)-1]);if(l.length===0)return" (a file this change didn't touch)";let[d,u]=[Number(n[2]),Number(n[3]??n[2])];return l.some(([h,p])=>d<=p+3&&u>=h-3)?"":` (a line this change didn't touch; it changed this file at ${l.map(([h,p])=>h===p?`line ${h}`:`lines ${h}-${p}`).join(", ")})`}return""}function $l(e,t){let n=e.scenario.claim,r=nm(e),s=e.verdict==="held"&&e.scenario.claim!==null?" It didn't happen.":"",o=[`# ${r[0].toUpperCase()}${r.slice(1)}: ${e.scenario.title}${s}`,"",rm(e),...sm(e,t),...e.note?["",e.note]:[]];return n&&(o.push("",e.verdict==="broken"?"## How to see it yourself":"## The scenario",`- Start from: ${n.startingState}`),n.entryPoint&&o.push(`- Go in through: ${n.entryPoint}`),o.push(`- Then: ${n.trigger}`,`- What goes wrong: ${n.wrongOutcome}`),n.correctBehaviour&&o.push(`- What should happen: ${n.correctBehaviour}`)),e.reproduction&&(o.push("","## The check's own steps",...e.reproduction.steps.map((i,a)=>`${a+1}. ${i}`),`Look for: ${e.reproduction.observe}`),e.reproduction.files.length&&o.push(`Canary keeps these scripts with the rest of the evidence: ${e.reproduction.files.join(", ")}.`)),e.ranOn&&o.push("","## Ran on",`${e.ranOn.environment.replace(/[^.!?]$/,"$&.")} Commit ${e.ranOn.commit}${e.ranOn.uncommitted?" with uncommitted changes":""}${e.ranOn.tree?`, snapshot ${e.ranOn.tree}`:""}.`),`${o.join(`
|
|
1830
1849
|
`)}
|
|
1831
|
-
`}function
|
|
1832
|
-
`);case"result":{let r=P(ce(e.runId),"results",`${e.record.jobId}.json`);Fn(pt(r),{recursive:!0})
|
|
1833
|
-
`);let s=r.replace(/\.json$/,".md");if(
|
|
1834
|
-
`)}case"report":{let r=new Map;for(let l of e.finished)r.set(
|
|
1850
|
+
`}function vl(e,t,n){let r=e.jobId?`the check ${JSON.stringify(n.get(e.jobId)??e.jobId)}`:`setting up batch ${e.batchId}`,s=Math.round((Date.now()-Date.parse(e.askedAt))/Ge);return`${t?`Reminder (asked ${s} 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 ${r}: ${JSON.stringify(e.text)}`}var _1=4*Ge;async function j1(){let e=Ae(),t=cr(),n=Nf(e),r=Rr();vt(e,y=>({...y,owner:t??y.owner??null}));let s=y=>it(e).runs[y]?.checkout??r,o=new Map,i=new Map,a={runs:[]},c=0,l=null,d=!1,u=async y=>{try{let k=await y();return d&&R("Canary: reachable again."),l=null,d=!1,k}catch(k){if(!_t(k))throw k;return l??=Date.now(),!d&&Date.now()-l>em&&(d=!0,R("Canary: can't reach Canary right now; still trying.")),null}},h=async()=>{let y=await u(()=>bi(e));if(!y)return!1;a=y,c=Date.now();for(let k of y.runs){i.set(k.runId,k.code.treeHash);for(let N of[...k.batches.flatMap(G=>G.jobs),...k.computer??[]])o.set(N.jobId,N.title)}return vt(e,k=>{for(let N of y.runs)k.runs[N.runId]??={checkout:r};return k}),!0};for(;!await h();)await an(vr);xl(a.runs.map(y=>s(y.runId)));let p=new Set,f=new Map,g=new Map,m=new Map,C=!1,A=async y=>{if(!C){C=!0;try{for(let[k,N]of[...g]){let G=m.get(k)??Ln;if(!y&&Date.now()-N<G)continue;g.delete(k);let Le=X().find(T=>T.batchId===k&&T.sessionId===e&&!T.left);if(!Le)continue;let Ce=await jn(Le),ae=m.has(k)?"finished its setup":"cleaned up";Mn(`Canary: the verifier for batch ${k} hadn't ${ae} ${Math.round(G/Ge)} 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.${Ce.length?` Left in place: ${Ce.join("; ")}`:" Nothing in this for the user."}`)}}finally{C=!1}}},b=y=>om(y,a),S=!1,x=async()=>{if(!S){S=!0;try{for(let y of X().filter(k=>k.sessionId===e&&k.claimed&&!k.ended)){let k=Lc(y.batchId);k&&await LC(y,k)}}finally{S=!1}}},v=0,I=async()=>{let y=new Map;for(let k of X().filter(N=>N.sessionId===e))y.set(k.runId,[...y.get(k.runId)??[],k.batchId]);for(let[k,N]of y){let G=ri(e,N);G.length>0&&await oe(`/cli/jobs/runs/${k}/setups`,{session:e,method:"POST",json:{setups:G}}).catch(()=>{})}};for(let y of lt(Je(e)).filter(b))f.set(y.path,Date.now()),Mn(vl(y,!0,o));let $=setInterval(()=>{if(n()){for(let y of lt(Je(e)).filter(b)){let k=f.get(y.path);k!==void 0&&Date.now()-k<_1||(f.set(y.path,Date.now()),Mn(vl(y,k!==void 0,o)))}A(!1),x(),Date.now()-v>=ni&&(v=Date.now(),I());for(let y of ws(e)){let k=a.runs.flatMap(N=>N.batches).find(N=>N.batchId===y.batchId);if(!k||k.state!=="queued"){tn(y.batchId);continue}!ms(Qt(y.checkout))||gs(y.checkout)||(tn(y.batchId),Mn(`Canary: a verifier on this machine has finished, so batch ${y.batchId} can start: start its verifier now.`))}for(let y of a.runs.flatMap(k=>k.batches))for(let k of Nt(y.batchId)){let N=vs(k);!N||p.has(k)||(p.add(k),Mn(`Canary: a check is waiting for the user to approve a command, because ${N}. Tell them so in a line now: the approval prompt itself doesn't say why they are asked.`))}}},2e3);try{for(;;){if(!n())return R("Canary: this listener was replaced by a newer one.");if(t&&!sr(t))return R("Canary: the Claude Code session ended; this listener stops.");let y=it(e).cursors,k=Object.entries(y).map(([E,U])=>`${E}:${U}`).join(","),N=Date.now(),G=await u(()=>oe(`/cli/jobs/events${k?`?cursors=${k}`:""}`,{session:e,timeoutMs:Uc}));if(!G){await an(vr);continue}if(!n())return R("Canary: this listener was replaced by a newer one.");let Le=0,Ce=0,ae=G.events.filter(E=>E.type==="jobs");ae.length&&(await h(),xl(ae.map(E=>s(E.runId))),[...new Set(ae.map(E=>s(E.runId)))].some(E=>Gc(E))&&Mn(P1));for(let E of G.events){if(E.type==="wait_over"&&E.batchId&&Pn(Je(e),E.batchId,E.jobId),E.type==="batch_ended"&&E.batchId){let J=E.batchId;g.set(J,Date.now());let ne=X().find(Ye=>Ye.batchId===J&&Ye.sessionId===e);E.reason==="set_aside"&&m.set(J,(ne?.setupMinutes??30)*Ge),ne&&js([J],(m.get(J)??Ln)+3e4)}let U=M1(E,o);U&&Mn(U),E.type==="result"&&Le++,E.type==="report"&&E.final&&(Ce++,_s(E.runId)||Dn(P(ce(E.runId),"source.bundle"),{force:!0}))}vt(e,E=>{for(let[U,J]of Object.entries(G.cursors))E.cursors[U]=Math.max(E.cursors[U]??0,J);return E});for(let{runId:E}of Je(e))Uo(E);Le>0&&await L1(G.events,i,s);let T=G.events.length===0,M=T&&Date.now()-N<vr;if(M&&await an(vr),(Ce>0||M||T&&Date.now()-c>2*Ge)&&await h(),a.runs.length===0&&(T||Ce>0)){let E=()=>[...g].filter(([U])=>X().some(J=>J.batchId===U&&J.sessionId===e&&!J.left));for(;E().some(([,U])=>Date.now()-U<Ln);)await an(vr);if(await A(!0),!n())return R("Canary: this listener was replaced by a newer one.");if(await h(),a.runs.length>0)continue;return R(Ce>0?"Canary: every check for this session has finished.":"Canary: no open checks for this session.")}}}finally{clearInterval($)}}var P1="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 om(e,t){return e.status==="open"&&t.runs.some(n=>n.runId===e.runId&&n.batches.some(r=>r.batchId===e.batchId&&r.state!=="ended"))}function M1(e,t){let n=r=>r?JSON.stringify(t.get(r)??r):"";switch(e.type){case"jobs":return e.batches.map(r=>{let s=[`Canary: ${r.afterError?"checks going once more":r.retried?"checks tried again":"new checks"} in run ${xr(e.runId)}, batch ${r.batchId} (${r.environment}): ${r.jobs.map(o=>JSON.stringify(o.title)).join("; ")}.`];return r.afterError?s.push("Canary hit an internal error with them and tries them once more: start a verifier for this batch as for any other."):r.retried&&s.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."),r.movedFrom&&s.push(`They moved here from batch ${r.movedFrom}, whose time ran out before its verifier could start them: start a verifier for this batch as for any other.`),r.questions.length&&s.push(`Questions to settle first: ${hi(r.questions)}`),r.permissions.length&&s.push(`Access to ask for: ${hi(r.permissions)}`),s.join(" ")}).join(`
|
|
1851
|
+
`);case"result":{let r=P(ce(e.runId),"results",`${e.record.jobId}.json`);Fn(pt(r),{recursive:!0}),$s(r,JSON.stringify(e.record,null,2)+`
|
|
1852
|
+
`);let s=r.replace(/\.json$/,".md");if($s(s,$l(e.record,e.runId)),e.record.blockedReason?.kind==="stopped_by_user")return null;let o=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: ${El(e.record.verdict)}${o}. Check: ${JSON.stringify(e.record.scenario.title)}. Full record: ${s}`,rm(e.record),...sm(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${O1.includes(e.record.blockedReason?.kind??"")?", once what it lacked is in place":""}: canary jobs retry ${e.runId} ${e.record.jobId}.${kl(e.runId)}`]:[]].join(`
|
|
1853
|
+
`)}case"report":{let r=new Map;for(let l of e.finished)r.set(Os(e.runId,l),(r.get(Os(e.runId,l))??0)+1);let s=[...r].map(([l,d])=>`${l} ${d}`).join(", ")||"none yet";if(!e.final)return null;if(e.finished.length===0)return`Canary final report for run ${xr(e.runId)}: no part of this run called for a check.`;let o=e.finished.map(l=>`${JSON.stringify(l.title)}: ${Os(e.runId,l)}`).join("; "),i=new Map;for(let l of e.finished.filter(d=>d.verdict==="broken")){let d=Y(P(ce(e.runId),"results",`${l.jobId}.json`))?.whereToLook?.replace(/:\d[\d-]*$/,"");d&&i.set(d,(i.get(d)??0)+1)}let a=i.size?`
|
|
1835
1854
|
Where the confirmed problems point: ${[...i].map(([l,d])=>`${l} (${d})`).join(", ")}.`:"",c=e.finished.some(l=>l.verdict==="blocked")?`
|
|
1836
|
-
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.${
|
|
1855
|
+
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.${kl(e.runId)}`:"";return`Canary final report for run ${xr(e.runId)}: all ${e.finished.length} checks have ended: ${s}. Each check's full record is in ${P(ce(e.runId),"results")}.
|
|
1837
1856
|
They were: ${o}.${a}${c}`}case"batch_ended":return null;case"wait_over":{let r=e.jobId?`the check ${n(e.jobId)}`:`the batch ${e.batchId}'s checks not yet run`;if(e.approval){let s=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 ${r} timed out; it can be re-checked. Stop that verifier and run canary jobs finish ${e.batchId} --give-back. ${s}`}return`Canary: no answer in time, so ${r} 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:
|
|
1838
|
-
${e.say}`}}async function M1(e,t,n){let r=[...new Set(e.filter(s=>s.type==="result").map(s=>s.runId))];try{for(let s of r)if(t.has(s)&&t.get(s)!==(await Zr(n(s),{likeClone:!0})).treeHash)return R("Canary: your files have changed since these checks were requested; their results are for the code as it was then.")}catch{}}var Yg=new Set;function vl(e){for(let t of new Set(e))if(Te(t))try{let n=Bo(t);if(Yg.has(n.dir))continue;Yg.add(n.dir),R(`Canary: this repository's notes for Canary are in ${n.canaryMd}, and its test secrets in ${n.secrets}.`)}catch(n){n instanceof _&&R(`Canary: ${n.message} ${n.fix??""}`.trim())}}async function L1(){let e=Ae(),t=await bi(e),n=new Map(Je(e).map(c=>[c.runId,c.checkout]));vl(t.runs.flatMap(c=>n.get(c.runId)??[]));let r=new Map(X().map(c=>[$c(c.key),Rl(c.batchId)])),s=c=>c===null?"nobody":r.get(c)?`${r.get(c)} on this machine`:"another verifier",o=ct(Je(e)).filter(c=>rm(c,t));for(let{runId:c}of Je(e).filter(({runId:l})=>!t.runs.some(d=>d.runId===l))){let l=Qg(c);l.length&&R(`Run ${c} 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 ${c}, naming checks after it to try only those.${bl(c)}`)}if(t.runs.length===0){Je(e).some(({runId:c})=>Ns(c))||R("No open Canary checks for this session.");return}for(let c of t.runs){R(`Run ${c.runId} (${c.kind}, ${c.coverage.run} of ${c.coverage.considered} finished)`);for(let l of c.batches){let d=$t(l.batchId),u=d.map(ks).find(g=>g),h=d.length?`; its verifier is waiting on an approval prompt${u?`, which the user is asked about because ${u}`:""}`:"";R(` Batch ${l.batchId} (${l.environment}): ${l.state}, held by ${s(l.holder)}${h}`);let p=l.state==="ended"?void 0:X().find(g=>g.batchId===l.batchId),f=p?(()=>{try{return Ar(le(l.batchId)).birthtimeMs}catch{return null}})():null;if(p&&f!==null){let g=$=>Math.max(0,Math.round((Date.now()-$)/Ge)),m=Mp(l.batchId,3),C=Up(l.batchId),A=l.jobs.every($=>$.state==="queued")?`setting up for ${g(f)} min; `:"",b=C?`set up in ${Math.max(0,Math.round((Date.parse(C)-f)/Ge))} min; `:"",S=l.jobs.find($=>$.state==="queued"),x=l.jobs.some($=>["running","waiting","stopping","proof"].includes($.state)),v=!A&&!x&&S?`between checks, the next in order being ${JSON.stringify(S.title)}; `:"",I=m.map($=>`${$.step} (${$.ended==="background"?"started in the background":$.ended==="running"?"still running":$.ended==="ran"?"ran":$.ended==="failed"?"failed":$.ended==="blocked"?"blocked by Claude Code's auto mode":"didn't run"}, ${g(Date.parse($.at))} min ago)`);R(` ${A}${b}${v}${I.length?`its verifier's latest steps, oldest first: ${I.join("; ")}`:"no step recorded yet"}`)}l.state==="queued"&&l.questions.length&&R(` Questions to settle first: ${hi(l.questions)}`),l.state==="queued"&&l.permissions.length&&R(` Access to ask for: ${hi(l.permissions)}`);for(let g of l.jobs)R(` ${g.jobId} ${g.state}${g.verdict?` (${Es(c.runId,g)})`:""} ${g.title}`)}if(c.computer?.length){R(" On Canary's computer:");let l=u=>Math.max(0,Math.round((Date.now()-Date.parse(u))/Ge)),d=u=>u.map(h=>`${h.step} (${l(h.at)} min ago)`).join("; ");for(let u of c.computerSandboxes??[])u.readyAt?R(` Sandbox ${u.sandbox}: set up in ${Math.max(0,Math.round((Date.parse(u.readyAt)-Date.parse(u.since))/Ge))} min`):R(` Sandbox ${u.sandbox}: setting up for ${l(u.since)} min; ${u.steps.length?`its latest steps, oldest first: ${d(u.steps)}`:"no step reported yet"}`);for(let u of c.computer)R(` ${u.jobId} ${u.state}${u.verdict?` (${Es(c.runId,u)})`:""} ${u.title}${u.sandbox?` (sandbox ${u.sandbox})`:""}`),(u.state==="running"||u.state==="proof")&&u.steps?.length&&R(` its latest steps, oldest first: ${d(u.steps)}`)}}let i=new Map(t.runs.flatMap(c=>[...c.batches.flatMap(l=>l.jobs),...c.computer??[]].map(l=>[l.jobId,l.title])));for(let c of o)R(kl(c,!0,i));let a;for(let c of new Set(t.runs.flatMap(l=>n.get(l.runId)??[]))){for(let d of Ip(c))R(d);let l=a?null:qc(c);l&&(R(l),a=c)}vt(e,c=>({...c,asking:a}))}var xl=e=>e instanceof _||e instanceof L&&!!e.code&&!Nt(e),Sr=45e3,Sl=e=>String(e?.code??""),Cl=e=>["ENOSPC","EDQUOT"].includes(Sl(e))||/No space left on device|Disk quota exceeded/.test(String(e?.message));function sm(e){if(["EACCES","EPERM","EROFS"].includes(Sl(e)))return Sl(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 F1(e){let t=Ae(),r=(await qe(()=>bi(t))).runs.find(i=>i.batches.some(a=>a.batchId===e)),s=r?.batches.find(i=>i.batchId===e);if(!r||!s)throw new _("not_found","No such batch among this session's open checks.","Use a batch id the listener or canary jobs list printed.");if(s.state==="ended")throw new _("batch_ended","This batch has ended.");let o={batchId:e,session:t,receipt:null,resuming:!1,folder:!1,state:null,copied:!1,claimSent:!1};try{await D1(r,o)}catch(i){await W1(o,i)}}async function D1(e,t){let{batchId:n,session:r}=t,s=e.batches.find(x=>x.batchId===n),o=ot(r).runs[e.runId]?.checkout??Rr(),i=Te(P(le(n),"state.json"))?en(n):null;i&&!i.claimed&&i.sessionId===r&&(!i.taker||Zt(i.taker)==="gone")&&Object.assign(t,{resuming:!0,folder:!0,state:i});let a=Bo(o),c=ir(En(o)),l=t.receipt=Y(P(ce(e.runId),"source.json")),d=P(ce(e.runId),"source.bundle");if(!l||!Te(d))throw new Error("the run's snapshot isn't on this machine");let u=x=>Ec(l.bytes,Te(P(de({repoFolder:c,slot:x}),".git"))),h,p={pid:process.pid,startedAt:Rt(process.pid)??Date.now()};if(t.resuming){let x=u(i.slot);x&&await Al(n,r,x,!0),h=t.state=xt(n,v=>{v.taker=p,v.owner=cr()??v.owner})}else{if(ps(o))throw ms(n,r,o),new _("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.");Df(n),t.folder=!0;let x=Qt(o),v=Bf(n,x);if(v===null)throw ms(n,r,o),new _("machine_busy",`${x} 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=u(v);I&&await Al(n,r,I,!1),h={batchId:n,runId:e.runId,sessionId:r,checkout:o,repoFolder:c,key:m1(24).toString("base64url"),owner:cr(),slot:v,ports:await zf(n,v),code:e.code,jobs:s.jobs.map($=>({jobId:$.jobId,title:$.title})),claimed:!1,taker:p,stopped:{},finalSent:[],proofs:{},cursor:0,processes:[]},fs(h),t.state=h}let f=de(h),g=await dg(o,d,l,e.code.treeHash,f);t.copied=!0,Ff(h),tn(n);let m=Zo(o),C=m&&{use:m.use,at:m.at,placed:m.use?hg(o,f,m.files):[]};Fn(dr(n),{recursive:!0});let A=G1(h,a,f);t.claimSent=!0;let b=await qe(()=>oe(`/cli/jobs/batches/${n}/claim`,{session:r,batchKey:h.key,json:{treeHash:e.code.treeHash}}));h=t.state=xt(n,x=>{x.claimed=!0,x.cursor=b.cursor,x.code=b.code,x.warm=g,x.keptScripts=A.scripts.map(v=>`${xe}/${v.name}`),x.jobMinutes=b.limits.jobMinutes,x.setupMinutes=b.limits.batchSetupMinutes,x.targets=Object.fromEntries(b.jobs.flatMap(({job:v})=>v.scenario.target?.address?[[v.id,v.scenario.target.address]]:[]))}),ws($t(n));let S=new Set(b.jobs.map(({job:x})=>x.id));for(let x of X().filter(v=>v.batchId!==n&&v.jobs.some(I=>S.has(I.jobId))))xt(x.batchId,v=>{v.jobs=v.jobs.filter(I=>!S.has(I.jobId))});vt(r,x=>(x.runs[e.runId]??={checkout:o},x)),z1(b,h,a,await wg(f),g,C,A,Y(P(ce(e.runId),lr)))}async function W1(e,t){let{batchId:n,session:r}=e,s=e.state?.claimed===!0,o=e.resuming||e.claimSent,i=(u=!1)=>{!e.folder||s&&!u||(Dn(le(n),{recursive:!0,force:!0}),qo(n))};if(xl(t))throw(!o||e.claimSent)&&i(),t;if(e.claimSent&&Cl(t))throw new _("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 a=e.state&&!e.copied&&!e.claimSent?de(e.state):null,c=a&&e.receipt?await yg(a,e.receipt.headSha):null;if(e.receipt&&!e.claimSent&&(Cl(t)||c!==null&&c.bytes-c.onDisk>Oc())){a&&Dn(a,{recursive:!0,force:!0}),e.resuming||i();let u=Ec(e.receipt.bytes,!!e.state&&e.copied,c?.bytes??null);throw u&&await Al(n,r,u,e.resuming),new _("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=sm(t);if(l&&!e.claimSent){if(!e.resuming)try{i()}catch{}throw Wo(l)}if(t instanceof L&&Nt(t)&&t.status<500)throw o?new _("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`):(i(),t);let d;try{d=await vs(r,{batchId:n,batchKey:e.state?.key},t)}catch(u){throw xl(u)?(s||i(),u):s?new _("internal_error",rn,`Hand the batch back once Canary can be reached: canary jobs finish ${n} --give-back`):o?new _("internal_error",rn,`Run canary jobs take ${n} again: it picks the same take back up. Or hand it back: canary jobs finish ${n} --give-back`):(i(),new _("internal_error",rn,`Run canary jobs take ${n} again.`))}throw i(!0),new _("internal_error",d.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 Al(e,t,n,r){if(r)throw new _("not_enough_disk",hs(n),`Tell the user how much space the checks need, then hand the batch back: canary jobs finish ${e} --give-back`);if(X().some(i=>i.sessionId===t&&!i.left))throw new _("not_enough_disk",`${hs(n)} This session's other Canary checks are using some of it.`,"Start this batch's verifier again once they finish.");let s=n;throw await qe(()=>oe(`/cli/jobs/batches/${e}/decline`,{session:t,json:s}).then(()=>!0)).catch(()=>!1)?new _("machine_limit",`${hs(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 _("not_enough_disk",hs(n),"Tell the user how much space the checks need. Take the batch again once they have freed some.")}var xe="canary-scripts",B1=new RegExp(`${xe}/([\\w.-]+(?:/[\\w.-]+)*\\.(?:sh|bash|rb|py|mjs|cjs|js|ts))\\b`,"g");function om(e){let t=[...e.matchAll(/^\s*(?:export\s+)?(\w+)=.*\bdocker\b/gm)].map(r=>`|"?\\$\\{?${r[1]}\\}?"?`).join(""),n=new RegExp(`(?:\\bdocker${t})\\s+(?:container\\s+)?(?:run|create)\\b`);return e.replace(/\\\n/g," ").split(`
|
|
1839
|
-
`).find(r=>n.test(r)&&!/--label\b|CANARY_DOCKER_LABEL/.test(r))}function
|
|
1840
|
-
`)),
|
|
1841
|
-
`);let o=Y(P(t.scripts,pi))??{},i=[];for(let[a,c]of Object.entries(o))!
|
|
1857
|
+
${e.say}`}}async function L1(e,t,n){let r=[...new Set(e.filter(s=>s.type==="result").map(s=>s.runId))];try{for(let s of r)if(t.has(s)&&t.get(s)!==(await Qr(n(s),{likeClone:!0})).treeHash)return R("Canary: your files have changed since these checks were requested; their results are for the code as it was then.")}catch{}}var Kg=new Set;function xl(e){for(let t of new Set(e))if(Te(t))try{let n=Bo(t);if(Kg.has(n.dir))continue;Kg.add(n.dir),R(`Canary: this repository's notes for Canary are in ${n.canaryMd}, and its test secrets in ${n.secrets}.`)}catch(n){n instanceof _&&R(`Canary: ${n.message} ${n.fix??""}`.trim())}}async function F1(){let e=Ae(),t=await bi(e),n=new Map(Je(e).map(c=>[c.runId,c.checkout]));xl(t.runs.flatMap(c=>n.get(c.runId)??[]));let r=new Map(X().map(c=>[Nc(c.key),Tl(c.batchId)])),s=c=>c===null?"nobody":r.get(c)?`${r.get(c)} on this machine`:"another verifier",o=lt(Je(e)).filter(c=>om(c,t));for(let{runId:c}of Je(e).filter(({runId:l})=>!t.runs.some(d=>d.runId===l))){let l=tm(c);l.length&&R(`Run ${c} 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 ${c}, naming checks after it to try only those.${kl(c)}`)}if(t.runs.length===0){Je(e).some(({runId:c})=>_s(c))||R("No open Canary checks for this session.");return}for(let c of t.runs){R(`Run ${c.runId} (${c.kind}, ${c.coverage.run} of ${c.coverage.considered} finished)`);for(let l of c.batches){let d=Nt(l.batchId),u=d.map(vs).find(g=>g),h=d.length?`; its verifier is waiting on an approval prompt${u?`, which the user is asked about because ${u}`:""}`:"";R(` Batch ${l.batchId} (${l.environment}): ${l.state}, held by ${s(l.holder)}${h}`);let p=l.state==="ended"?void 0:X().find(g=>g.batchId===l.batchId),f=p?(()=>{try{return Ar(le(l.batchId)).birthtimeMs}catch{return null}})():null;if(p&&f!==null){let g=$=>Math.max(0,Math.round((Date.now()-$)/Ge)),m=Fp(l.batchId,3),C=Hp(l.batchId),A=l.jobs.every($=>$.state==="queued")?`setting up for ${g(f)} min; `:"",b=C?`set up in ${Math.max(0,Math.round((Date.parse(C)-f)/Ge))} min; `:"",S=l.jobs.find($=>$.state==="queued"),x=l.jobs.some($=>["running","waiting","stopping","proof"].includes($.state)),v=!A&&!x&&S?`between checks, the next in order being ${JSON.stringify(S.title)}; `:"",I=m.map($=>`${$.step} (${$.ended==="background"?"started in the background":$.ended==="running"?"still running":$.ended==="ran"?"ran":$.ended==="failed"?"failed":$.ended==="blocked"?"blocked by Claude Code's auto mode":"didn't run"}, ${g(Date.parse($.at))} min ago)`);R(` ${A}${b}${v}${I.length?`its verifier's latest steps, oldest first: ${I.join("; ")}`:"no step recorded yet"}`)}l.state==="queued"&&l.questions.length&&R(` Questions to settle first: ${hi(l.questions)}`),l.state==="queued"&&l.permissions.length&&R(` Access to ask for: ${hi(l.permissions)}`);for(let g of l.jobs)R(` ${g.jobId} ${g.state}${g.verdict?` (${Os(c.runId,g)})`:""} ${g.title}`)}if(c.computer?.length){R(" On Canary's computer:");let l=u=>Math.max(0,Math.round((Date.now()-Date.parse(u))/Ge)),d=u=>u.map(h=>`${h.step} (${l(h.at)} min ago)`).join("; ");for(let u of c.computerSandboxes??[])u.readyAt?R(` Sandbox ${u.sandbox}: set up in ${Math.max(0,Math.round((Date.parse(u.readyAt)-Date.parse(u.since))/Ge))} min`):R(` Sandbox ${u.sandbox}: setting up for ${l(u.since)} min; ${u.steps.length?`its latest steps, oldest first: ${d(u.steps)}`:"no step reported yet"}`);for(let u of c.computer)R(` ${u.jobId} ${u.state}${u.verdict?` (${Os(c.runId,u)})`:""} ${u.title}${u.sandbox?` (sandbox ${u.sandbox})`:""}`),(u.state==="running"||u.state==="proof")&&u.steps?.length&&R(` its latest steps, oldest first: ${d(u.steps)}`)}}let i=new Map(t.runs.flatMap(c=>[...c.batches.flatMap(l=>l.jobs),...c.computer??[]].map(l=>[l.jobId,l.title])));for(let c of o)R(vl(c,!0,i));let a;for(let c of new Set(t.runs.flatMap(l=>n.get(l.runId)??[]))){for(let d of Tp(c))R(d);let l=a?null:Gc(c);l&&(R(l),a=c)}vt(e,c=>({...c,asking:a}))}var Sl=e=>e instanceof _||e instanceof L&&!!e.code&&!_t(e),Sr=45e3,Cl=e=>String(e?.code??""),Al=e=>["ENOSPC","EDQUOT"].includes(Cl(e))||/No space left on device|Disk quota exceeded/.test(String(e?.message));function im(e){if(["EACCES","EPERM","EROFS"].includes(Cl(e)))return Cl(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 D1(e){let t=Ae(),r=(await He(()=>bi(t))).runs.find(i=>i.batches.some(a=>a.batchId===e)),s=r?.batches.find(i=>i.batchId===e);if(!r||!s)throw new _("not_found","No such batch among this session's open checks.","Use a batch id the listener or canary jobs list printed.");if(s.state==="ended")throw new _("batch_ended","This batch has ended.");let o={batchId:e,session:t,receipt:null,resuming:!1,folder:!1,state:null,copied:!1,claimSent:!1};try{await W1(r,o)}catch(i){await B1(o,i)}}async function W1(e,t){let{batchId:n,session:r}=t,s=e.batches.find(x=>x.batchId===n),o=it(r).runs[e.runId]?.checkout??Rr(),i=Te(P(le(n),"state.json"))?en(n):null;i&&!i.claimed&&i.sessionId===r&&(!i.taker||Zt(i.taker)==="gone")&&Object.assign(t,{resuming:!0,folder:!0,state:i});let a=Bo(o),c=ir(En(o)),l=t.receipt=Y(P(ce(e.runId),"source.json")),d=P(ce(e.runId),"source.bundle");if(!l||!Te(d))throw new Error("the run's snapshot isn't on this machine");let u=x=>Oc(l.bytes,Te(P(de({repoFolder:c,slot:x}),".git"))),h,p={pid:process.pid,startedAt:Rt(process.pid)??Date.now()};if(t.resuming){let x=u(i.slot);x&&await Il(n,r,x,!0),h=t.state=xt(n,v=>{v.taker=p,v.owner=cr()??v.owner})}else{if(gs(o))throw ys(n,r,o),new _("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.");Bf(n),t.folder=!0;let x=Qt(o),v=qf(n,x);if(v===null)throw ys(n,r,o),new _("machine_busy",`${x} 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=u(v);I&&await Il(n,r,I,!1),h={batchId:n,runId:e.runId,sessionId:r,checkout:o,repoFolder:c,key:y1(24).toString("base64url"),owner:cr(),slot:v,ports:await Zf(n,v),code:e.code,jobs:s.jobs.map($=>({jobId:$.jobId,title:$.title})),claimed:!1,taker:p,stopped:{},finalSent:[],proofs:{},cursor:0,processes:[]},ps(h),t.state=h}let f=de(h),g=await fg(o,d,l,e.code.treeHash,f);t.copied=!0,Wf(h),tn(n);let m=Zo(o),C=m&&{use:m.use,at:m.at,placed:m.use?pg(o,f,m.files):[]};Fn(dr(n),{recursive:!0});let A=J1(h,a,f);t.claimSent=!0;let b=await He(()=>oe(`/cli/jobs/batches/${n}/claim`,{session:r,batchKey:h.key,json:{treeHash:e.code.treeHash}}));h=t.state=xt(n,x=>{x.claimed=!0,x.cursor=b.cursor,x.code=b.code,x.warm=g,x.keptScripts=A.scripts.map(v=>`${xe}/${v.name}`),x.jobMinutes=b.limits.jobMinutes,x.setupMinutes=b.limits.batchSetupMinutes,x.targets=Object.fromEntries(b.jobs.flatMap(({job:v})=>v.scenario.target?.address?[[v.id,v.scenario.target.address]]:[]))}),bs(Nt(n));let S=new Set(b.jobs.map(({job:x})=>x.id));for(let x of X().filter(v=>v.batchId!==n&&v.jobs.some(I=>S.has(I.jobId))))xt(x.batchId,v=>{v.jobs=v.jobs.filter(I=>!S.has(I.jobId))});vt(r,x=>(x.runs[e.runId]??={checkout:o},x)),X1(b,h,a,await kg(f),g,C,A,Y(P(ce(e.runId),lr)))}async function B1(e,t){let{batchId:n,session:r}=e,s=e.state?.claimed===!0,o=e.resuming||e.claimSent,i=(u=!1)=>{!e.folder||s&&!u||(Dn(le(n),{recursive:!0,force:!0}),Ho(n))};if(Sl(t))throw(!o||e.claimSent)&&i(),t;if(e.claimSent&&Al(t))throw new _("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 a=e.state&&!e.copied&&!e.claimSent?de(e.state):null,c=a&&e.receipt?await bg(a,e.receipt.headSha):null;if(e.receipt&&!e.claimSent&&(Al(t)||c!==null&&c.bytes-c.onDisk>$c())){a&&Dn(a,{recursive:!0,force:!0}),e.resuming||i();let u=Oc(e.receipt.bytes,!!e.state&&e.copied,c?.bytes??null);throw u&&await Il(n,r,u,e.resuming),new _("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=im(t);if(l&&!e.claimSent){if(!e.resuming)try{i()}catch{}throw Wo(l)}if(t instanceof L&&_t(t)&&t.status<500)throw o?new _("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`):(i(),t);let d;try{d=await xs(r,{batchId:n,batchKey:e.state?.key},t)}catch(u){throw Sl(u)?(s||i(),u):s?new _("internal_error",rn,`Hand the batch back once Canary can be reached: canary jobs finish ${n} --give-back`):o?new _("internal_error",rn,`Run canary jobs take ${n} again: it picks the same take back up. Or hand it back: canary jobs finish ${n} --give-back`):(i(),new _("internal_error",rn,`Run canary jobs take ${n} again.`))}throw i(!0),new _("internal_error",d.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 Il(e,t,n,r){if(r)throw new _("not_enough_disk",fs(n),`Tell the user how much space the checks need, then hand the batch back: canary jobs finish ${e} --give-back`);if(X().some(i=>i.sessionId===t&&!i.left))throw new _("not_enough_disk",`${fs(n)} This session's other Canary checks are using some of it.`,"Start this batch's verifier again once they finish.");let s=n;throw await He(()=>oe(`/cli/jobs/batches/${e}/decline`,{session:t,json:s}).then(()=>!0)).catch(()=>!1)?new _("machine_limit",`${fs(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 _("not_enough_disk",fs(n),"Tell the user how much space the checks need. Take the batch again once they have freed some.")}var xe="canary-scripts",U1=new RegExp(`${xe}/([\\w.-]+(?:/[\\w.-]+)*\\.(?:sh|bash|rb|py|mjs|cjs|js|ts))\\b`,"g");function am(e){let t=[...e.matchAll(/^\s*(?:export\s+)?(\w+)=.*\bdocker\b/gm)].map(r=>`|"?\\$\\{?${r[1]}\\}?"?`).join(""),n=new RegExp(`(?:\\bdocker${t})\\s+(?:container\\s+)?(?:run|create)\\b`);return e.replace(/\\\n/g," ").split(`
|
|
1858
|
+
`).find(r=>n.test(r)&&!/--label\b|CANARY_DOCKER_LABEL/.test(r))}function q1(e,t){let n=e.map(r=>r.name).filter(r=>am(Mt(P(t,r),"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 H1(e){let t=P(de(e),xe),n=Pf(e.repoFolder);return[...new Set(Dp(e.batchId).flatMap(s=>[...s.matchAll(U1)].map(o=>o[1])).filter(s=>!s.split("/").includes("..")))].filter(s=>Te(P(t,s))&&!(Te(P(n,s))&&Mt(P(n,s)).equals(Mt(P(t,s)))))}var Cr="canary-run.env",G1=/^[\w.-]+(\/[\w.-]+)*$/;function J1(e,t,n){let r=P(n,xe);Dn(r,{recursive:!0,force:!0}),Fn(r,{recursive:!0});let s=P(r,Cr);$s(s,["# 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=${xr(e.batchId)}`,`CANARY_COPY=${n}`,`CANARY_SCRATCH=${dr(e.batchId)}`,`CANARY_PORT_FIRST=${e.ports[0]}`,`CANARY_PORT_LAST=${e.ports[1]}`,`CANARY_DOCKER_LABEL=${mr(e.batchId)}`,`CANARY_COMPOSE_PROJECT=${yr(e.batchId)}`,`CANARY_SECRETS=${t.secrets}`,""].join(`
|
|
1859
|
+
`)),w1(P(n,".git","info","exclude"),`/${xe}/${Cr}
|
|
1860
|
+
`);let o=Y(P(t.scripts,pi))??{},i=[];for(let[a,c]of Object.entries(o))!G1.test(a)||a.split("/").includes("..")||Te(P(r,a))||!Te(P(t.scripts,a))||(Fn(pt(P(r,a)),{recursive:!0}),k1(P(t.scripts,a),P(r,a)),i.push({name:a,...c}));return{values:s,scripts:i}}function Y1(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 V1(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 K1(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 z1(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 X1(e,t,n,r,s,o,i,a=null){let c=t.batchId,l=e.limits,d=h=>a&&h>=a.at?"during this run":`on ${h.slice(0,10)}${a?", before this run":""}`;if(R(`You hold batch ${c} (run ${e.runId}) as ${Tl(c)}: ${e.batch.environment}.`),R(`Copy of the code the checks were planned on: ${de(t)}. Work only there; it is outside the user's checkout.`),R(s?"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."),R(`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"}.${Y1(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.`),R(`Ports for this batch: ${t.ports[0]}-${t.ports[1]}. Use only these for anything you start.`),R(`Scratch files and folders, and the data folders of services you start, go in ${dr(c)}: it is removed with the batch.`),o?.use){R(o.placed.length?`The user allowed the checks to use the project's env files ${d(o.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: ${o.placed.map(p=>p.file).join(", ")}.`:`The user allowed the checks to use the project's env files ${d(o.at)}, but none is in the checkout now.`);let h=o.placed.filter(p=>p.repointed.length);h.length&&R(`Every value in them that pointed at this machine now names ${ol}, 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: ${h.map(p=>`${p.file}: ${p.repointed.join(", ")}`).join("; ")}.`)}else o&&R(`The checks may not use the project's env files: the user said so ${d(o.at)}. Set the app's environment up yourself, and ask for any key a check needs.`);r.length&&R(`Submodules in your copy are empty: ${r.map(h=>`${h.path} at ${h.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.`),R(`Read first: ${n.canaryMd}. Test secrets: ${n.secrets} (canary.md names them).`);let u=a?Df(a,n.canaryMd):[];u.length&&R(`Added to the user's part of canary.md since this run began; an answer among these was given during this run:
|
|
1842
1861
|
${u.map(h=>` ${h}`).join(`
|
|
1843
|
-
`)}`),R(`This batch's own values (its id, copy, scratch folder, ports, Docker label and compose project name, the secrets file) are in ${i.values}, as NAME=value lines: a setup script reads them from there and writes none of them out.`),R(i.scripts.length?`Setup scripts earlier checks of this repository kept are in ${P(de(t),xe)}: ${i.scripts.map(h=>`${h.name} (${h.what}; last kept ${h.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.${U1(i.scripts,P(de(t),xe))}`:"No setup script has been kept for this repository yet: yours will be the first."),R(`When a setup script of yours has run clean, keep it for the checks after you: canary jobs keep ${c} ${xe}/<file> --what "<what it sets up>"`),R(`Your setup script says when setup is done: once its smoke check passed, its last step runs canary jobs ready with CANARY_BATCH from ${i.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 ${c} yourself, before you work on the checks.`),R(`Label what you start in Docker with --label ${mr(c)}, or use compose project name ${yr(c)}. Register other background processes: canary jobs created ${c} --pid <pid> --what "<what>".`),bf()&&R(`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 ${c}, naming the command.`),R(`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.`),R(`Keep your listener running as a background command, and start it again each time it returns: canary jobs listen ${c}`),R(`Evidence for a job goes in ${P(le(c),"packs","<job>")}/pack.json; the format: canary jobs schema`),R(""),R("Jobs, one at a time, in this order:"),e.jobs.forEach(({job:h,brief:p,state:f,earlierFiles:g,earlier:m},C)=>{R(`${C+1}. Job ${h.id}: ${h.scenario.title} [${f}]`),R(` What must hold: ${h.scenario.assertion}`);for(let A of V1(h.scenario.target))R(` ${A}`);h.scenario.target&&R(` ${K1(h.scenario.target)}`),h.scenario.claim&&R(` Claim, where the wrong outcome is the failure: ${Object.entries(h.scenario.claim).filter(([,A])=>A).map(([A,b])=>`${A}: ${b}`).join("; ")}`),R(` How to prove it (${p.method}): ${p.plan}`),R(` Data to set up: ${p.dataSetup}`),R(` Must run for real: ${p.reasons.dependsOn.join("; ")}`),p.reasons.faked.length&&R(` May be faked, only to set up or observe: ${p.reasons.faked.map(A=>`${A.part} (${A.why})`).join("; ")}`),p.reasons.limits.length&&R(` Known limits: ${p.reasons.limits.map(A=>`${A.part} (${A.why})`).join("; ")}`),p.questions.length&&R(` Expected questions: ${p.questions.join(" | ")}`),p.permissions.length&&R(` Access to ask for: ${p.permissions.join(" | ")}`),h.scenario.relatedFiles.length&&R(` Related files: ${h.scenario.relatedFiles.join(", ")}`),h.recheckOf?(R(` Re-check of an earlier result. Last time, ${Y1(h.recheckOf.verdict)}.${h.recheckOf.reasoning?` Earlier reasoning: ${h.recheckOf.reasoning}`:""}`),h.recheckOf.reproduction&&R(` Earlier reproduction: ${h.recheckOf.reproduction.steps.join(" Then ")} Look for: ${h.recheckOf.reproduction.observe}`),g.length&&R(` Earlier files (fetch each into the copy with canary jobs earlier ${h.id} <path>): ${g.join(", ")}`)):m&&(R(` Tried first on Canary's computer, which runs only the code. What it needs from this machine: ${m.needs.replace(/[.\s]+$/,"")}.${m.reasoning?` What that attempt showed: ${m.reasoning}`:""}`),g.length&&R(` Its scripts (fetch each into the copy with canary jobs earlier ${h.id} <path>, and reuse what still fits): ${g.join(", ")}`))})}function X1(e,t){let n=r=>JSON.stringify(t.jobs.find(s=>s.jobId===r)?.title??r??"");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(r=>`${r} ${n(r)}`).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 ${ur(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} ${xe}/<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 Z1(e,t){let n=!1;for(let r of ct([{runId:e.runId}]).filter(s=>s.batchId===e.batchId&&s.status==="answered")){let s=ml(r.path);s.texts.length!==0&&(s.first&&await oe(`/cli/jobs/batches/${e.batchId}/resume`,{session:t,batchKey:e.key,method:"POST"}).catch(()=>{}),R(s.first?`Canary: ${am(r)}`:`Canary: more on ${r.id} from the coding agent: ${s.texts.join(" | ")}`),n=!0)}return n}async function Q1(e){let t=Ae(),n=en(e),r=Date.now(),s=null,o=!1;for(setInterval(()=>void Z1(n,t).then(a=>{a&&process.exit(0)}).catch(()=>{}),2e3).unref();;){if(n.owner&&!sr(n.owner))return R("Canary: the Claude Code session ended; this listener stops.");if(Date.now()-r>C1){if(s)return R("Canary: can't reach Canary right now; run the listener again.");let c=gr(e)?[]:H1(n);return R(c.length?`Canary: no news yet. Of the scripts you have run, ${c.join(", ")} ${c.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 ${c.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} ${xe}/<file> --what "<what it sets up and how far it gets>"`:"Canary: no news yet.")}let a;try{a=await oe(`/cli/jobs/batches/${e}/events?after=${n.cursor}`,{session:t,batchKey:n.key,timeoutMs:Bc}),o&&R("Canary: reachable again."),s=null,o=!1}catch(c){if(Ko(c))return xt(e,l=>{l.ended=!0}),R(`Canary: stop working on batch ${e}: ${c.message} Clean up what you started and run: canary jobs finish ${e}`);if(!Nt(c))throw c;s??=Date.now(),!o&&Date.now()-s>Zg&&(o=!0,R("Canary: can't reach Canary right now; still trying.")),await an(vr);continue}n=xt(e,c=>{c.cursor=a.cursor;for(let l of a.events)l.type==="stop"&&l.jobId&&(c.stopped[l.jobId]=l.submitBy),l.type==="proof_request"&&l.jobId&&(c.proofs[l.jobId]=l.proofRequestId),l.type==="result"&&delete c.proofs[l.record.jobId],l.type==="batch_ended"&&(c.ended=!0,c.setAside=l.reason==="set_aside")});for(let c of a.events)c.type==="batch_ended"&&Pn([{runId:n.runId}],e,"all"),c.type==="wait_over"&&(Pn([{runId:n.runId}],e,c.jobId),c.jobId&&Lc(e,c.jobId));for(let c of a.events)R(X1(c,n));if(a.events.length>0)return}}var $l=(e,t)=>{if(e.stopped[t])throw new _("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]}`:""}`)},im=e=>{if(e===void 0)return null;if(!/^[1-9]\d*$/.test(e))throw new _("usage","--proof takes the request's number, as the listener printed it.");return Number(e)};async function eC(e,t){let n=hr(e);$l(n,e),await dm(n);let r=im(t.proof);await qe(()=>oe(`/cli/jobs/${e}/start`,{session:Ae(),batchKey:n.key,json:{proofRequestId:r}}),Sr).catch(async o=>{throw o instanceof L&&o.status>=500?await fi(n,e,o,r?"picking up this request":"starting this job",`canary jobs start ${e}${r?` --proof ${r}`:""}`):o});let s=!gr(n.batchId);Kc(n.batchId,"start",e,r),s&&!n.kept?.length&&R(`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} ${xe}/<file> --what "<what it sets up>"`),R(r?`Picked up request ${r} on job ${e}: its 15 minutes run from now. Answer in ${ur(n.batchId,e,r)}/delta.json.`:`Started job ${e}. Its working time is counting; waiting on the user doesn't count.`)}async function tC(e,t){let n=Ae(),r,s;if(t.wait){let a=X().filter(c=>c.sessionId===n).flatMap(c=>ct([{runId:c.runId}]).filter(l=>l.id.toLowerCase()===t.wait.toLowerCase()&&l.batchId===c.batchId).map(l=>({q:l,s:c})))[0];if(!a)throw new _("no_such_question",`No question ${t.wait} from a batch taken in this session.`);({q:r,s}=a)}else{if(!e||!!t.job==!!t.setup)throw new _("usage","Ask about one job (--job <job>) or about setting up (--setup <batch>), with the question text.");if(e.length>Vg)throw new _("question_too_long",`A question is one need, in a line or two: this one is ${e.length} characters, and ${Vg} 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.");s=t.job?hr(t.job):en(t.setup);let i=Object.keys(s.stopped).find(l=>!s.finalSent.includes(l));if(i)throw new _("job_stopped",`Job ${i} was stopped and its final evidence is due; no question can hold it up.`,`canary jobs submit ${i}${s.proofs[i]?` --proof ${s.proofs[i]}`:""}`);let a=s;await dm(a);let c=()=>qe(()=>oe(`/cli/jobs/batches/${a.batchId}/pause`,{session:n,batchKey:a.key,json:{jobId:t.job??null}}),Sr);try{await c()}catch(l){if(l instanceof L&&l.status>=500)throw await fi(a,t.job??null,l,"taking your question",`canary jobs ask ${t.job?`--job ${t.job}`:`--setup ${a.batchId}`} "<question>"`);let d=ct([{runId:a.runId}]).some(u=>u.batchId===a.batchId&&u.status==="open");if(!(l instanceof L&&l.code==="already_waiting")||d)throw l;await oe(`/cli/jobs/batches/${a.batchId}/resume`,{session:n,batchKey:a.key,method:"POST"}),await c()}try{r=Hg(s.checkout,{runId:s.runId,batchId:s.batchId,jobId:t.job??null,verifier:Rl(s.batchId),text:e})}catch(l){throw await oe(`/cli/jobs/batches/${s.batchId}/resume`,{session:n,batchKey:s.key,method:"POST"}).catch(()=>{}),l}R(`Asked ${r.id}; the clock is paused while the user answers. If this command is cut off: canary jobs ask --wait ${r.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 o=Date.now()+S1;for(;;){let i=X().find(c=>c.batchId===s.batchId);if(!i||i.ended)return Pn([{runId:s.runId}],s.batchId,"all"),R(`Canary: batch ${s.batchId} has ended, so ${r.id} needs no answer. Stop what you started and run: canary jobs finish ${s.batchId}`);let a=Jg(r.path);if(a?.status==="answered"){let c=ml(r.path).first,l=am(a),d=!0;try{c&&({resumed:d}=await qe(()=>oe(`/cli/jobs/batches/${s.batchId}/resume`,{session:n,batchKey:s.key,method:"POST"})))}catch(u){if(!Ko(u))return R(`${l} Couldn't restart the clock with Canary; run canary jobs ask --wait ${r.id} to try again.`)}return R(d?l:`${l} It came after the wait ran out, so ${r.jobId?"that job":"the jobs not yet run"} already ended.`)}if(a?.status==="expired")return R(`No answer to ${r.id} in time: Canary ended ${r.jobId?`job ${r.jobId}`:"this batch's jobs not yet run"}; it can be re-checked. Move on.`);if(Date.now()>=o)return R(`No answer to ${r.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 ${r.id}`);await an(2e3)}}var Vg=350;function am(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(s=>JSON.stringify(s)).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)",r=(e.more??[]).map(s=>` Added later: ${s.text}`).join("");return`Answer to ${e.id}${n}: ${e.answer}${r} 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.`}var cm=e=>Je(Ae()).find(t=>t.runId.startsWith(e))?.runId??e;async function nC(e){let t=cm(e),{stopped:n}=await oe(`/cli/jobs/runs/${t}/stop`,{session:Ae(),method:"POST"});_s(X().filter(r=>r.runId===t&&r.sessionId===Ae()).map(r=>r.batchId),Ln+3e4),R(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 rC(e,t){let n=cm(e),r=(()=>{try{return yi(P(ce(n),"results")).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5))}catch{return[]}})(),s=t.map(i=>r.find(a=>a.startsWith(i.toLowerCase()))??i),{retried:o}=await oe(`/cli/jobs/runs/${n}/retry`,{session:Ae(),method:"POST",json:{jobIds:s}});R(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 ${s.length?"the ones named are still going":"none of its checks is one"}.`)}async function sC(e,t){let n=Ae(),r=qg(Je(n),e);if(r.status==="expired")return R(`The wait for ${r.id} had already run out: the check timed out. Keep this answer in canary.md; the check can be re-checked.`);let s=(ot(n).userAt??"")>r.askedAt,o=(ot(n).said??[]).filter(a=>a.at>r.askedAt).map(a=>a.text),i=r.status==="answered";Gg(r,t,s,o),R(i?`Added to the answer to ${r.id}: its verifier gets it with its listener's next news.`:`Answered ${r.id}: its verifier reads it within seconds, from its waiting question or its listener.${s?" 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 oC(e,t){let n=Ae(),r=hr(e);if(r.finalSent.includes(e))throw new _("final_sent","This job's final evidence after its stop was already sent.");let s=im(t.proof),o=s?"with this answer":"with this job's evidence",i=`canary jobs submit ${e}${s?` --proof ${s}`:""}`,a=ur(r.batchId,e,s??void 0),c=P(cn(le(r.batchId)),"packs",e,...s?[`proof-${s}`]:[]);if(Te(a)&&cn(a)!==c)throw new _("pack_folder_link",`${a} is a link, so the evidence would be read from somewhere else.`,"Make it a plain folder holding the evidence files.");let l,d;try{if(!Yf(r.batchId))throw new Error("the plugin's hooks saw nothing of this batch's verifier");l=Hp(r.batchId,e,s);let h=l.calls.at(-1);h?.kind==="command"&&h.ended==="not_run"&&/\bcanary\s+jobs\s+submit\b/.test(h.what)&&l.calls.pop();let p=ct([{runId:r.runId}]).filter(g=>g.batchId===r.batchId).map(({id:g,jobId:m,text:C,status:A,answer:b,userSpoke:S})=>({id:g,jobId:m,text:C,status:A,answer:b,userSpoke:S??!1})),f=l.calls.filter(g=>g.kind==="file"&&g.ended==="ran").map(g=>g.what);d=Og(a,s?"delta":"pack",{jobId:e,commit:r.code.commit,tree:r.code.treeHash,uncommitted:r.code.uncommitted??null,scripts:iC(de(r),r.batchId,e,s),scriptsFrom:P(de(r),xe),diff:await bg(de(r)),warmCopy:r.warm??!1,stopped:!!r.stopped[e],startedAt:l.jobStartedAt,observed:{calls:l.calls,earlierCalls:l.earlierCalls,minutes:l.minutes,stopped:!!r.stopped[e],putBack:await mg(cn(de(r)),f),questions:p},byHand:qp(r.batchId)},s,ol(r.checkout))}catch(h){if(h instanceof _)throw h;if(Cl(h))throw new _("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: ${i}`);let p=sm(h);throw p?Wo(p):await fi(r,e,h,o,i)}cC(r,e,d.pack),aC(r,e,s,d.pack,l);let u={session:n,batchKey:r.key};try{let h=await qe(()=>oe(`/cli/jobs/${e}/evidence`,{...u,json:d.upload}),Sr);for(let p of h.missing){let f=d.bytes.get(p);await qe(()=>oe(`/cli/jobs/${e}/evidence/${h.uploadId}?path=${encodeURIComponent(p)}`,{...u,method:"PUT",bytes:f,timeoutMs:R1(f.length)}),Sr)}await qe(()=>oe(`/cli/jobs/${e}/evidence/${h.uploadId}/complete`,{...u,method:"POST"}),Sr)}catch(h){throw h instanceof L&&h.status>=500?await fi(r,e,h,o,i):h}if(r.stopped[e]&&xt(r.batchId,h=>void h.finalSent.push(e)),Kc(r.batchId,"sent",e,s),Lc(r.batchId,e),R(`Sent ${s?`the answer to request ${s} on`:"the evidence for"} job ${e}; Canary is judging it, and the result reaches your listener.`),d.hidden.length){let h=new Map;for(let{name:g,path:m}of d.hidden)h.set(g,[...new Set([...h.get(g)??[],m])]);let p=[...h].filter(([g])=>g!==wr).map(([g,m])=>`${g} (in ${m.join(", ")})`),f=h.get(wr);R(`Canary hid secret values before sending: ${[...p.length?[`these by their names: ${p.join("; ")}`]:[],...f?[`${wr} (in ${f.join(", ")})`]:[]].join("; and ")}. That is best effort, so keep secret values out of what you record.`)}}async function fi(e,t,n,r,s){let o;try{o=await vs(e.sessionId,t?{jobId:t,batchKey:e.key}:{batchId:e.batchId,batchKey:e.key},n)}catch(i){return xl(i)?i:new _("internal_error",rn,`Run it again in a minute: ${s}`)}return o.requeued?new _("internal_error",`Canary hit an internal error ${r}, 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}.`):o.ended>0?new _("internal_error",`Canary hit an internal error ${r}, 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 _("internal_error",`Canary hit an internal error ${r}, 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 iC(e,t,n,r){let s=P(e,xe),o=P(ur(t,n),xe),i=r?P(ur(t,n,r),`proof-${r}-scripts`):o,a=[],c=l=>{for(let d of Te(l)?yi(l,{withFileTypes:!0}):[]){let u=P(l,d.name),h=Xg(s,u).split(wi).join("/");if(d.name.startsWith(".")||d.name==="node_modules"||h===Cr||a.length>=hC)continue;if(d.isDirectory()){c(u);continue}if(!d.isFile()||Ar(u).size>lm||!$n.test(`${wl(i)}/${h}`))continue;let p=Pt(u);if(p.subarray(0,8e3).includes(0)||r&&Te(P(o,h))&&Pt(P(o,h)).equals(p))continue;Fn(pt(P(i,h)),{recursive:!0}),Os(P(i,h),p);let{atime:f,mtime:g}=Ar(u);v1(P(i,h),f,g),a.push(`${wl(i)}/${h}`)}};return c(s),a}function aC(e,t,n,r,s){let o=`${t}:${n??0}`;if(e.stopped[t]||e.sentBack?.includes(o))return;let i=s.calls.filter(u=>u.kind==="command"&&(u.ended==="ran"||u.ended==="failed")).length,a=e.jobMinutes??15,c=s.startedAt===null||s.minutes<a/3,l=s.startedAt===null?"It was never started":`It used ${Math.round(s.minutes)} of its ${a} minutes`,d="claim"in r?r.claim.verdict==="cannot_run"&&(i===0||c)&&[`This job is coming back as one that couldn't run. ${l}, and Canary's record shows ${i} command${i===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."]:i===0&&r.steps.length===0&&r.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(d)throw xt(e.batchId,u=>void(u.sentBack=[...u.sentBack??[],o])),new _("nothing_run",d[0],d[1])}function cC(e,t,n){if(!("claim"in n)||n.claim.verdict==="cannot_run")return;let[r,s]=e.ports,o=e.targets?.[t];for(let i 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 a=Number(i[1]??i[2]??NaN);if(!(Number.isNaN(a)||a>=r&&a<=s)&&!(o&&lC(o)===`${i[0].replace(/:\d+$/,"").toLowerCase()}:${a}`))throw new _("not_this_batch",`The evidence gives ${i[0]} as what was tested, which is outside this batch's ports (${r}-${s}), 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${o?`; this job's running target is ${o}, as take printed it`:""}.`)}}function lC(e){try{let t=new URL(e);return`${t.hostname.toLowerCase()}:${t.port||(t.protocol==="https:"?"443":"80")}`}catch{return null}}async function uC(e,t){let n=hr(e);if($l(n,e),!$n.test(t))throw new _("usage",`${t} isn't a path from the earlier evidence.`,"Use a path take printed under earlier files.");let r=await qe(()=>cp(`/cli/jobs/${e}/earlier?path=${encodeURIComponent(t)}`,{session:Ae(),batchKey:n.key})),s=cn(de(n)),o=pt(P(s,t));for(;!Te(o);)o=pt(o);if(cn(o)!==s&&!cn(o).startsWith(s+wi))throw new _("outside_copy",`${t} leads outside the copy through a link.`);Fn(pt(P(s,t)),{recursive:!0});let i=P(s,t);Te(i)&&(i=`${i}.earlier`);let a=k1(i,ui.O_WRONLY|ui.O_CREAT|ui.O_EXCL|ui.O_NOFOLLOW,420);try{x1(a,r)}finally{w1(a)}R(`Wrote ${t} from the earlier evidence to ${i}.`)}async function dC(e,t){let n=en(e),r=Number(t.pid),s=Number.isInteger(r)&&r>1?Rt(r):null;if(s===null)throw new _("no_such_process",`No running process ${t.pid}.`);if(!Qc(r,n))throw new _("not_this_batch",`Process ${r} 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.");xt(e,o=>void o.processes.push({pid:r,startedAt:s,what:t.what??"background process"})),R(`Recorded process ${r}; finish stops it with the batch.`)}var pi="kept.json",lm=256*1024,hC=80;async function fC(e,t,n){let r=en(e),s=cn(de(r)),o=Bo(r.checkout),i=ol(r.checkout),a=[];for(let l of t){let d=Re(Il(s,l));if(!Ir(d,[P(s,xe)])||!Ar(d).isFile()||Ar(d).size>lm||wl(d)===Cr)throw new _("not_a_setup_script",`${l} isn't a script in ${P(s,xe)}.`,"Keep the setup script, and any file it runs, from that folder.");let u=Pt(d,"utf8"),h=[...[r.batchId,xr(r.batchId)].filter(f=>u.includes(f)).map(f=>`this batch's id (${f})`),...[s,de(r),le(r.batchId),r.checkout,yl()].filter(f=>u.includes(f)).slice(0,1).map(f=>`a path on this machine (${f})`),...[...u.matchAll(/\b4[2-5]\d{3}\b/g)].slice(0,1).map(f=>`a port written out (${f[0]})`),...i.filter(f=>u.includes(f.value)).slice(0,1).map(f=>`the value of ${f.name}`)];if(h.length)throw new _("holds_this_batch",`${l} holds ${h.join(", ")}, so the next verifier would have to rewrite it.`,`Read those from ${xe}/${Cr} (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 p=om(u);if(p)throw new _("unlabelled_container",`${l} starts a container without this batch's label (${p.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 ${xe}/${Cr}), run it clean once more, and keep it again.`);a.push({name:Xg(P(s,xe),d).split(wi).join("/"),text:u})}let c=Y(P(o.scripts,pi))??{};for(let{name:l,text:d}of a)Fn(pt(P(o.scripts,l)),{recursive:!0,mode:448}),Os(P(o.scripts,l),d,{mode:384}),c[l]={what:n.what,keptAt:new Date().toISOString()};Pe(P(o.scripts,pi),c),xt(e,l=>void(l.kept=[...new Set([...l.kept??[],...a.map(d=>d.name)])])),R(`Kept ${a.map(l=>l.name).join(", ")} for later checks of this repository: the next take puts ${a.length>1?"them":"it"} in the verifier's copy.`)}async function pC(e){xt(e,t=>void(t.readyAt??=new Date().toISOString())),R("Noted: the app is up. The user now sees that setup is over and that you are getting the checks ready.")}async function gC(e,t){let n=hr(e);$l(n,e);let r=Date.now()+A1;for(;!Kf(t,n.batchId,e);){if(Date.now()>=r)throw new _("target_busy",`Another verifier is still writing to ${t}.`,"Work without writing to it, or report why the job couldn't run.");await an(2e3)}R(`You may write to ${t}; the lock is released when this job's evidence is sent or the batch finishes.`)}async function mC(e,t){if(!Te(P(le(e),"state.json")))return Dn(le(e),{recursive:!0,force:!0}),R(`Nothing of batch ${e} is on this machine.`);let n=en(e),r=Ae();if(n.sessionId!==r)throw new _("other_session","This batch was taken by another Claude Code session.");let s=n.ended?void 0:(await bi(r)).runs.flatMap(i=>i.batches).find(i=>i.batchId===n.batchId);if(s&&s.state!=="ended"&&s.holder===$c(n.key)){if(!t.giveBack)throw new _("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 i=!1,{requeued:a,ended:c}=await qe(()=>oe(`/cli/jobs/batches/${e}/give-back`,{session:r,batchKey:n.key,method:"POST"}),Sr).catch(async l=>{if(!(l instanceof L&&l.status>=500))throw l;return i=!0,vs(r,{batchId:e,batchKey:n.key},l).catch(()=>{throw new _("internal_error",rn,`Run it again in a minute: canary jobs finish ${e} --give-back`)})});R(a?`Gave batch ${e} back: jobs it hadn't sent evidence for will go to a fresh verifier.`:c>0?i?`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 o=await jn(n);R(`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 i of o)R(`Left in place: ${i}`)}async function um(){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 yC(){try{let e=await um(),t=e.agent_id,n=e.hook_event_name,r=e.tool_input;if(n==="PreToolUse"&&r?.subagent_type==="canary:verifier"&&(r.isolation||r.name))return R(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$C}}));if(n==="PostToolUse"&&e.tool_name==="AskUserQuestion"&&typeof e.session_id=="string"){let v=ot(e.session_id).asking;if(v&&Te(v)){let I=Ap(e,v);I.commands!==null&&wp(v,I.commands),I.envFiles&&bp(v,I.envFiles.files,I.envFiles.answer)}return await mi(e.session_id,$s,PC(e))}if(n==="UserPromptSubmit"&&typeof e.session_id=="string")return typeof e.prompt=="string"&&bC.test(e.prompt)?void 0:await mi(e.session_id,I1,typeof e.prompt=="string"?[e.prompt]:[]);let s=e.agent_type==="canary:verifier"&&typeof t=="string"?t:null,o=g1("sha256").update(JSON.stringify([e.tool_name??null,e.tool_input??null])).digest("hex").slice(0,16),i={call:typeof e.tool_use_id=="string"?e.tool_use_id:o,same:o},a=n==="PermissionRequest"?AC(e):null;if(a===!0)return R(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"allow"}}}));if(a&&!a.shared){let v=s&&it(s);return v&&pr(v,{same:o},"sent_back",a.reason),R(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"deny",message:OC(a.reason)}}}))}if(!s)return;if(n==="PermissionRequest")return await _C(s,o,a?a.reason:"");if(n==="PermissionDenied")return wC(s,i,e);await jC(s,typeof n=="string"?n:"",o,typeof e.duration_ms=="number"?Math.max(0,Math.round(e.duration_ms)):0);let c=String(e.tool_name),l=e.tool_input,d=gi.has(c)?l?.file_path??l?.notebook_path:null,u=c==="Bash"&&typeof l?.command=="string"?l.command:null,h=typeof d=="string"||u!==null&&!fr(u);if(n==="PostToolUse"||n==="PostToolUseFailure"){let v=h?it(s):null;if(!v)return;pr(v,i,n==="PostToolUse"?"ran":"failed",vC(e)),u!==null?Xc(v,i.call,xC(e)):typeof d=="string"&&n==="PostToolUse"&&Dp(v,i.call,Re(d));return}if(n==="PostToolBatch")return SC(s,e);if(n!=="PreToolUse")return;let p=(v,I,$)=>{v&&pr(v,i,"sent_back",$),R(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:I}}))};if(typeof d=="string"){let v=it(s);v&&si(v,i,"file",Re(d));let I=RC(s,e);I&&p(v,I,I.includes("the user's own word")?"it changes the user's part of the notes":"outside the verifier's own folders");return}if(u===null)return;let f=/\bcanary\s+jobs\s+(?:take|listen)\s+([0-9a-fA-F-]{36})\b/.exec(u)?.[1];f&&it(s)!==f&&Jf(s,f);let g=it(s);if(g&&h){let v=e.tool_input;si(g,i,"command",u,typeof v.description=="string"?v.description:"",v.run_in_background===!0)}let m=g?X().find(v=>v.batchId===g):void 0,C=m?.checkout??(typeof e.cwd=="string"?e.cwd:null),A=C&&Nn(C)?.commands==="run"?null:Dg(u),b=m?CC(u,ki(m,m.checkout),m.checkout):null,S=m?EC(u,m,typeof e.cwd=="string"?e.cwd:m.checkout):null,x=NC(s,u);x?p(g,x,"the job moved to another batch"):kC.test(u)?p(g,"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"):b?p(g,b,"it names what Canary itself keeps about the checks"):S?p(g,S,"it writes a file outside the verifier's own folders"):A&&p(g,Wg(A),A)}catch{}}function wC(e,t,n){let r=it(e),s=n.tool_input,o=n.tool_name==="Bash"&&typeof s?.command=="string"?s.command:null;!r||o===null&&!gi.has(String(n.tool_name))||(o!==null&&fr(o)&&si(r,t,"command",o),pr(r,t,"blocked",typeof n.reason=="string"?n.reason:""))}var bC=/^\s*(?:<task-notification>|<agent-message\b|Another Claude session sent a message)/,gi=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),kC=/\bcanary\s+jobs\s+(?:answer|approvals|stop|retry)\b/;function vC(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 xC(e){if(typeof e.error=="string")return e.error;let t=e.tool_response;if(typeof t?.persistedOutputPath=="string")try{return Pt(t.persistedOutputPath,"utf8")}catch{}return typeof t?.stdout=="string"?t.stdout:""}function SC(e,t){let n=it(e),r=Array.isArray(t.tool_calls)?t.tool_calls:[];if(!n||r.length===0)return;let s=Bp(n);for(let o of r){if(typeof o.tool_use_id!="string"||typeof o.tool_response!="string")continue;let i=/^Command running in background .*Output is being written to: (\S+\.output)/.exec(o.tool_response)?.[1];i?Fp(n,o.tool_use_id,i):s.has(o.tool_use_id)&&pr(n,{call:o.tool_use_id},"not_run",o.tool_response)}}function CC(e,t,n){let r=He(n),s=r?[Xe(r).dir]:[];for(let o of new Set([q(),Re(q()),P(pt(q()),"approvals"),Re(P(pt(q()),"approvals"))]))for(let i=e.indexOf(o);i!==-1;i=e.indexOf(o,i+1)){let a=/^[^\s'"`;|&<>()]*/.exec(e.slice(i))[0];if(!t.holds(Re(a))&&!Ir(Re(a),s))return`Canary: not run. ${a} 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 AC(e){let t=e.tool_input,n=String(e.tool_name),r=(n==="Bash"||n==="Monitor")&&typeof t?.command=="string"?t.command:null;if(r!==null&&fr(r))return!0;let s=t?.file_path??t?.notebook_path??t?.path,o=typeof s=="string"?Re(s):null;if(typeof e.agent_id!="string"){let d=typeof e.cwd=="string"?Rr(e.cwd):null,u=d&&He(d);if(!d||!u)return!1;let h=Xe(u),p=[h.dir,P(q(),"runs")];return r!==null?Sp(r,f=>Ir(Re(f.startsWith("~/")?P(yl(),f.slice(2)):Il(e.cwd,f)),p)):o===null?!1:IC.has(n)?Ir(o,p):gi.has(n)&&[h.canaryMd,h.secrets].map(Re).includes(o)&&Nn(d)?.commands==="run"}if(e.agent_type!=="canary:verifier")return!1;let i=it(e.agent_id),a=i?X().find(d=>d.batchId===i):void 0,c=a?.checkout??(typeof e.cwd=="string"?e.cwd:null);if(!c||Nn(c)?.commands!=="run")return!1;let l=ki(a,c);if(r!==null){let d=u=>{try{return Ar(u).size<=262144?Pt(u,"utf8"):null}catch{return null}};return li(r,{roots:l.folders.flatMap(u=>[...new Set([u,Re(u)])]),cwd:c,home:yl(),ports:a?.ports??[0,0],label:mr(a?.batchId??""),composeProject:yr(a?.batchId??""),read:d,dockerOwn:a&&((u,h)=>Xp(a.batchId,u,h))})??!0}return gi.has(n)?o===null?!1:l.holds(o)||{reason:`it changes ${s}, which isn't one of the checks' own files`,shared:!1}:!0}var IC=new Set(["Read","Grep","Glob"]);function Re(e){let t=Il(e);for(let n=t;;n=pt(n))try{return P(cn(n),t.slice(n.length))}catch{if(n===pt(n))return t}}var Ir=(e,t)=>t.map(Re).some(n=>e===n||e.startsWith(n+wi));function ki(e,t){let n=He(t),r=n&&Xe(n),s=e?[de(e),le(e.batchId)]:[],o=e?Re(P(le(e.batchId),"state.json")):null;return{folders:s,holds:i=>Ir(i,s)&&i!==o||r!==null&&i===Re(r.canaryMd)}}function RC(e,t){let n=t.tool_input,r=n?.file_path??n?.notebook_path,s=it(e),o=s?X().find(i=>i.batchId===s):void 0;return!o||typeof r!="string"?null:ki(o,o.checkout).holds(Re(r))?TC(o,Re(r),t):`Canary: not written. ${r} is outside your own folders, so nothing would remove it when the batch ends. Write the checks' scripts in your copy (${de(o)}) and scratch files in ${dr(o.batchId)}; keep a setup script for later checks with canary jobs keep.`}function TC(e,t,n){let r=He(e.checkout);if(!r||t!==Re(Xe(r).canaryMd))return null;let s=n.tool_input,o;try{o=Pt(t,"utf8")}catch{return null}let i=Array.isArray(s?.edits)?s.edits:[s??{}],a=typeof s?.content=="string"?s.content:o;if(typeof s?.content!="string")for(let l of i){if(typeof l.old_string!="string"||typeof l.new_string!="string"){a=null;break}a=l.replace_all?a.split(l.old_string).join(l.new_string):a.replace(l.old_string,()=>l.new_string)}let c=l=>l.includes(zt)?l.slice(0,l.indexOf(zt)):l;return a!==null&&c(a)===c(o)?null:`Canary: not written. Everything in canary.md above "${zt.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 "${zt.replace(/^#+ /,"")}" and "What worked and what failed", and ask a question for anything that needs the user.`}function EC(e,t,n){let r=ki(t,t.checkout).folders,s=_g(e,n).find(o=>!o.startsWith("/dev/")&&!Ir(Re(o),r));return s?`Canary: not run. It writes ${s}, 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 ${dr(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 OC=e=>`Canary: not run, because ${e}. 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.`,$C="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 NC(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(a=>a[1]),r=it(e);if(n.length===0||!r)return null;let s=X(),o=s.find(a=>a.batchId===r),i=o&&n.find(a=>!o.jobs.some(c=>c.jobId===a)&&s.some(c=>c.jobs.some(l=>l.jobId===a)));return i?`Canary: not run. Job ${i} 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 _C(e,t,n=""){let r=it(e),s=r?X().find(o=>o.batchId===r&&o.claimed):void 0;if(s){Vf(e,t,s.batchId,n);try{await oe(`/cli/jobs/batches/${s.batchId}/pause`,{session:s.sessionId,batchKey:s.key,json:{jobId:null,approval:!0},timeoutMs:$s}),bs(s.batchId)}catch(o){o instanceof L&&!Nt(o)?(ws(Jo(e).filter(i=>i.call===t).map(i=>i.name)),bs(s.batchId)):Pc(s.batchId,{call:"pause"})}}}async function jC(e,t,n,r){let s=t==="PostToolUse"||t==="PostToolUseFailure";if(!s&&t!=="PostToolBatch"&&t!=="SubagentStop")return;let o=Jo(e).filter(a=>!s||a.call===n),i=X().find(a=>o.some(c=>c.batchId===a.batchId))?.sessionId;i&&t!=="SubagentStop"&&await mi(i);for(let a of new Set(o.map(c=>c.batchId))){let c=o.filter(d=>d.batchId===a);ws(c.map(d=>d.name));let l=X().find(d=>d.batchId===a);!l||Jo(e).some(d=>d.batchId===a)||await hm(l,s?r:0).catch(()=>{})}}function PC(e){let t=e.tool_response?.answers;return t&&typeof t=="object"?Object.values(t).filter(n=>typeof n=="string"):[]}async function mi(e,t=$s,n=[]){if(Object.keys(ot(e).runs).length===0)return;let r=new Date().toISOString(),s=n.map(o=>o.trim()).filter(Boolean).map(o=>({at:r,text:o.length>300?`${o.slice(0,299)}\u2026`:o}));vt(e,o=>({...o,userAt:r,said:[...o.said??[],...s].slice(-10)})),await oe("/cli/jobs/answered",{session:e,method:"POST",timeoutMs:t}).catch(()=>{})}async function dm(e){$t(e.batchId).length&&await mi(e.sessionId),await hm(e),ws($t(e.batchId))}async function hm(e,t=0){try{await oe(`/cli/jobs/batches/${e.batchId}/resume`,{session:e.sessionId,batchKey:e.key,json:{workedMs:t,approval:!0},timeoutMs:$s})}catch(n){if(!(n instanceof L)||Nt(n))throw Pc(e.batchId,{call:"resume",since:Date.now()-t}),n}bs(e.batchId)}async function MC(e,t){let n=$t(e.batchId).length>0,r={session:e.sessionId,batchKey:e.key,timeoutMs:$s};try{t.call==="pause"&&n&&await oe(`/cli/jobs/batches/${e.batchId}/pause`,{...r,json:{jobId:null,approval:!0}}),t.call==="resume"&&!n&&await oe(`/cli/jobs/batches/${e.batchId}/resume`,{...r,json:{workedMs:Math.max(0,Date.now()-t.since),approval:!0}})}catch(s){if(!(s instanceof L)||Nt(s))return}bs(e.batchId,t.call)}function _s(e,t){e.length!==0&&zg(process.execPath,[process.argv[1],"jobs","clean-ended",...e,"--after",String(t)],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref()}async function LC(e,t){await an(Number(t.after)||0);let n=Ae();for(let r of X().filter(s=>e.includes(s.batchId)&&s.sessionId===n&&!s.left))await jn(r).catch(()=>{})}async function FC(e){await DC(e).catch(()=>{})}async function DC(e){if(!e.end){let n=(await um()).session_id,r=(typeof n=="string"?n:null)??process.env.CLAUDE_CODE_SESSION_ID;if(!r)return;if(Object.keys(ot(r).runs).length===0)return Dc(r);zg(process.execPath,[process.argv[1],"jobs","session-end","--end",r],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref();return}let t=e.end;await qe(()=>oe("/cli/jobs/session-end",{session:t,method:"POST",timeoutMs:1e4})).catch(()=>{});for(let n of X().filter(r=>r.sessionId===t))await jn(n).catch(()=>{});for(let{runId:n}of Je(t))Dn(P(ce(n),"source.bundle"),{force:!0});Dc(t)}function fm(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(ye(_1)),t.command("list").description("this session's checks, batches and open questions").action(ye(L1)),t.command("take <batch>").description("take a batch: build its copy and claim it").action(ye(F1)),t.command("listen <batch>").description("the verifier's listener: returns after the next news, or about 9 minutes").action(ye(Q1,{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(ye(eC,{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(ye(tC,{urgent:!0})),t.command("stop <run>").description("stop a run's checks that haven't finished, at the user's word").action(ye(nC)),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(ye(rC)),t.command("answer <question> <text>").description("answer a verifier's question").action(ye(sC,{local:!0})),t.command("submit <job>").option("--proof <n>","send the answer to request <n>").description("send a job's evidence").action(ye(oC,{urgent:!0})),t.command("earlier <job> <path>").description("fetch a file of the earlier evidence for a re-check").action(ye(uC)),t.command("created <batch>").requiredOption("--pid <pid>","the process id").option("--what <what>","what it is").description("record a background process for cleanup").action(ye(dC,{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(ye(fC,{local:!0})),t.command("ready <batch>").description("say the app is up, so the user sees that setup is over").action(ye(pC,{local:!0})),t.command("lock <job> <target>").description("write to a target marked safe for writes, one verifier at a time").action(ye(gC,{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(ye(mC)),t.command("session-end").option("--end <session>").description("called by the plugin's session-end hook").action(ye(FC,{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(ye(LC,{sweep:!1,local:!0})),t.command("hook").description("called by the plugin's hooks on a verifier's tool calls").action(yC),t.command("approvals <action>").description("reset: forget the user's choices for this repository, so they are asked again").action(ye(async n=>{if(n!=="reset")throw new _("usage","The only action is reset.");kp(Rr()),R("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(ye(async()=>R($g),{sweep:!1}))}w();Q();ro();nt();qt();import{appendFileSync as fA,existsSync as pA}from"node:fs";import{join as Em}from"node:path";w();_a();w();var pm=["claude","codex","cursor"];function gm(e,t=0,n=[]){if(typeof e=="string")e&&n.push(e);else if(t<3&&e&&typeof e=="object")for(let r of Object.values(e))gm(r,t+1,n);return n}var ln=e=>typeof e=="string"&&e?e:void 0,WC=new Set(["Bash","PowerShell","Monitor"]);function mm(e,t,n=process.env,r=process.platform){if(!t||typeof t!="object"||Array.isArray(t))return null;let s=t;if(e==="cursor"){let l=Array.isArray(s.workspace_roots)?s.workspace_roots:[],d=ln(s.cwd)??ln(l[0])??ln(n.CURSOR_PROJECT_DIR)??process.cwd(),u=ln(s.conversation_id)?{chat:ln(s.conversation_id)}:{};return s.hook_event_name==="beforeShellExecution"&&typeof s.command=="string"?{kind:"shell",command:s.command,cwd:d,shell:r==="win32"?"powershell":"posix",...u}:s.hook_event_name==="beforeMCPExecution"&&typeof s.tool_name=="string"?{kind:"tool",toolName:s.tool_name,cwd:d,...u}:null}if(s.hook_event_name!=="PreToolUse"||typeof s.tool_name!="string")return null;let o=ln(s.cwd)??process.cwd(),i=ln(s.session_id)?{chat:ln(s.session_id)}:{},a=s.tool_input&&typeof s.tool_input=="object"?s.tool_input:{};if(WC.has(s.tool_name)&&typeof a.command=="string")return{kind:"shell",command:a.command,cwd:o,shell:s.tool_name==="PowerShell"?"powershell":"posix",...i};let c=e==="codex"&&s.tool_name==="exec"?gm(typeof s.tool_input=="string"?s.tool_input:a):[];return c.length?{kind:"script",toolName:s.tool_name,texts:c,cwd:o,...i}:{kind:"tool",toolName:s.tool_name,cwd:o,...i}}function ym(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}}):""}Ao();w();fe();var Wn=(e,t)=>({decision:"allow",cause:e,...t?{message:t}:{}}),wm=e=>e.replace(/[\x00-\x1f\x7f]+/g,"?");function vi(e){if(e.mode==="off")return Wn("mode_off");if(!e.trigger)return Wn("not_a_trigger");if(!e.login)return null;if(!e.login.ok)return Wn(e.login.cause);if(e.chat===void 0)return null;if(e.chat===null)return Wn("no_chat");if(!e.lookup)return null;if(!e.lookup.ok)return Wn(e.lookup.cause,`Canary couldn't be asked about this push (${wm(e.lookup.detail)}), so it went ahead.`);let{hold:t}=e.lookup;return t.state==="clear"?Wn("clear"):t.state==="remind"?{decision:"deny",cause:t.state,message:t.agent}:e.skip===void 0?null:e.skip?Wn("skipped",`Canary: the person chose to continue without verifying (${wm(e.skip.reason)}). Tell them it was pushed without a Canary check.`):{decision:"deny",cause:t.state,message:t.agent}}var BC=new Set(["clear","none","running","open","remind"]);async function bm(e,t,n,r={}){let s=AbortSignal.timeout(r.timeoutMs??Tn);try{let o=new URLSearchParams({workspaceId:e.workspaceId,chat:t,...n?{raised:n}:{}}),i=await B(`/api/v1/cli/hold?${o.toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:xc(s,r.signal)});return!i||typeof i!="object"||!BC.has(String(i.state))?{ok:!1,cause:"unknown_state",detail:"Canary answered in a way this CLI version does not understand (update the CLI)"}:i.state!=="clear"&&typeof i.agent!="string"?{ok:!1,cause:"unknown_state",detail:"Canary's answer had no words to show"}:{ok:!0,hold:i}}catch(o){return s.aborted?{ok:!1,cause:"lookup_timeout",detail:`Canary did not answer within ${Math.round((r.timeoutMs??Tn)/1e3)} s`}:o instanceof L&&o.status>=400&&o.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${o.status}: ${o.message}${o.fix?` (${o.fix})`:""}`}:o instanceof L&&o.status>=500?{ok:!1,cause:"lookup_error",detail:`Canary answered ${o.status}`}:{ok:!1,cause:"lookup_unreachable",detail:o instanceof Error?o.message:String(o)}}}w();w();Q();import{randomUUID as UC}from"node:crypto";import{mkdirSync as HC,readFileSync as qC,renameSync as GC,rmSync as JC,writeFileSync as YC}from"node:fs";import{dirname as VC,join as KC}from"node:path";var Nl=()=>KC(K(),"hold","raised.json"),zC=720*60*60*1e3,XC=100,ZC=8e3;function km(e){let t;try{t=JSON.parse(qC(Nl(),"utf8"))}catch{return{}}let n=t?.chats;if(t?.version!==1||!n||typeof n!="object"||Array.isArray(n))return{};let r={};for(let[s,o]of Object.entries(n)){let i=typeof o?.at=="string"?Date.parse(o.at):NaN;Array.isArray(o?.keys)&&Number.isFinite(i)&&e-i<zC&&(r[s]={keys:o.keys.filter(a=>typeof a=="string"),at:o.at})}return r}function vm(e,t=Date.now()){let n=[...km(t)[e]?.keys??[]];for(;n.join(",").length>ZC;)n.shift();return n.length>0?n.join(","):void 0}function xm(e,t,n=Date.now()){try{Pr(`${Nl()}.lock`,"what pushes asked about",()=>{let r=km(n),s=new Set(r[e]?.keys);for(let a of t)s.delete(a),s.add(a);r[e]={keys:[...s].slice(-XC),at:new Date(n).toISOString()};let o=Nl(),i=`${o}.${UC()}.tmp`;HC(VC(o),{recursive:!0,mode:448});try{YC(i,JSON.stringify({version:1,chats:r},null,2)+`
|
|
1844
|
-
`,{flag:"wx",mode:384}),
|
|
1845
|
-
`:n==="t"?" ":n);function
|
|
1862
|
+
`)}`),R(`This batch's own values (its id, copy, scratch folder, ports, Docker label and compose project name, the secrets file) are in ${i.values}, as NAME=value lines: a setup script reads them from there and writes none of them out.`),R(i.scripts.length?`Setup scripts earlier checks of this repository kept are in ${P(de(t),xe)}: ${i.scripts.map(h=>`${h.name} (${h.what}; last kept ${h.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.${q1(i.scripts,P(de(t),xe))}`:"No setup script has been kept for this repository yet: yours will be the first."),R(`When a setup script of yours has run clean, keep it for the checks after you: canary jobs keep ${c} ${xe}/<file> --what "<what it sets up>"`),R(`Your setup script says when setup is done: once its smoke check passed, its last step runs canary jobs ready with CANARY_BATCH from ${i.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 ${c} yourself, before you work on the checks.`),R(`Label what you start in Docker with --label ${mr(c)}, or use compose project name ${yr(c)}. Register other background processes: canary jobs created ${c} --pid <pid> --what "<what>".`),vf()&&R(`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 ${c}, naming the command.`),R(`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.`),R(`Keep your listener running as a background command, and start it again each time it returns: canary jobs listen ${c}`),R(`Evidence for a job goes in ${P(le(c),"packs","<job>")}/pack.json; the format: canary jobs schema`),R(""),R("Jobs, one at a time, in this order:"),e.jobs.forEach(({job:h,brief:p,state:f,earlierFiles:g,earlier:m},C)=>{R(`${C+1}. Job ${h.id}: ${h.scenario.title} [${f}]`),R(` What must hold: ${h.scenario.assertion}`);for(let A of K1(h.scenario.target))R(` ${A}`);h.scenario.target&&R(` ${z1(h.scenario.target)}`),h.scenario.claim&&R(` Claim, where the wrong outcome is the failure: ${Object.entries(h.scenario.claim).filter(([,A])=>A).map(([A,b])=>`${A}: ${b}`).join("; ")}`),R(` How to prove it (${p.method}): ${p.plan}`),R(` Data to set up: ${p.dataSetup}`),R(` Must run for real: ${p.reasons.dependsOn.join("; ")}`),p.reasons.faked.length&&R(` May be faked, only to set up or observe: ${p.reasons.faked.map(A=>`${A.part} (${A.why})`).join("; ")}`),p.reasons.limits.length&&R(` Known limits: ${p.reasons.limits.map(A=>`${A.part} (${A.why})`).join("; ")}`),p.questions.length&&R(` Expected questions: ${p.questions.join(" | ")}`),p.permissions.length&&R(` Access to ask for: ${p.permissions.join(" | ")}`),h.scenario.relatedFiles.length&&R(` Related files: ${h.scenario.relatedFiles.join(", ")}`),h.recheckOf?(R(` Re-check of an earlier result. Last time, ${V1(h.recheckOf.verdict)}.${h.recheckOf.reasoning?` Earlier reasoning: ${h.recheckOf.reasoning}`:""}`),h.recheckOf.reproduction&&R(` Earlier reproduction: ${h.recheckOf.reproduction.steps.join(" Then ")} Look for: ${h.recheckOf.reproduction.observe}`),g.length&&R(` Earlier files (fetch each into the copy with canary jobs earlier ${h.id} <path>): ${g.join(", ")}`)):m&&(R(` Tried first on Canary's computer, which runs only the code. What it needs from this machine: ${m.needs.replace(/[.\s]+$/,"")}.${m.reasoning?` What that attempt showed: ${m.reasoning}`:""}`),g.length&&R(` Its scripts (fetch each into the copy with canary jobs earlier ${h.id} <path>, and reuse what still fits): ${g.join(", ")}`))})}function Z1(e,t){let n=r=>JSON.stringify(t.jobs.find(s=>s.jobId===r)?.title??r??"");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(r=>`${r} ${n(r)}`).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 ${ur(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} ${xe}/<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 Q1(e,t){let n=!1;for(let r of lt([{runId:e.runId}]).filter(s=>s.batchId===e.batchId&&s.status==="answered")){let s=yl(r.path);s.texts.length!==0&&(s.first&&await oe(`/cli/jobs/batches/${e.batchId}/resume`,{session:t,batchKey:e.key,method:"POST"}).catch(()=>{}),R(s.first?`Canary: ${lm(r)}`:`Canary: more on ${r.id} from the coding agent: ${s.texts.join(" | ")}`),n=!0)}return n}async function eC(e){let t=Ae(),n=en(e),r=Date.now(),s=null,o=!1;for(setInterval(()=>void Q1(n,t).then(a=>{a&&process.exit(0)}).catch(()=>{}),2e3).unref();;){if(n.owner&&!sr(n.owner))return R("Canary: the Claude Code session ended; this listener stops.");if(Date.now()-r>A1){if(s)return R("Canary: can't reach Canary right now; run the listener again.");let c=gr(e)?[]:H1(n);return R(c.length?`Canary: no news yet. Of the scripts you have run, ${c.join(", ")} ${c.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 ${c.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} ${xe}/<file> --what "<what it sets up and how far it gets>"`:"Canary: no news yet.")}let a;try{a=await oe(`/cli/jobs/batches/${e}/events?after=${n.cursor}`,{session:t,batchKey:n.key,timeoutMs:Uc}),o&&R("Canary: reachable again."),s=null,o=!1}catch(c){if(Ko(c))return xt(e,l=>{l.ended=!0}),R(`Canary: stop working on batch ${e}: ${c.message} Clean up what you started and run: canary jobs finish ${e}`);if(!_t(c))throw c;s??=Date.now(),!o&&Date.now()-s>em&&(o=!0,R("Canary: can't reach Canary right now; still trying.")),await an(vr);continue}n=xt(e,c=>{c.cursor=a.cursor;for(let l of a.events)l.type==="stop"&&l.jobId&&(c.stopped[l.jobId]=l.submitBy),l.type==="proof_request"&&l.jobId&&(c.proofs[l.jobId]=l.proofRequestId),l.type==="result"&&delete c.proofs[l.record.jobId],l.type==="batch_ended"&&(c.ended=!0,c.setAside=l.reason==="set_aside")});for(let c of a.events)c.type==="batch_ended"&&Pn([{runId:n.runId}],e,"all"),c.type==="wait_over"&&(Pn([{runId:n.runId}],e,c.jobId),c.jobId&&Fc(e,c.jobId));for(let c of a.events)R(Z1(c,n));if(a.events.length>0)return}}var Nl=(e,t)=>{if(e.stopped[t])throw new _("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]}`:""}`)},cm=e=>{if(e===void 0)return null;if(!/^[1-9]\d*$/.test(e))throw new _("usage","--proof takes the request's number, as the listener printed it.");return Number(e)};async function tC(e,t){let n=hr(e);Nl(n,e),await fm(n);let r=cm(t.proof);await He(()=>oe(`/cli/jobs/${e}/start`,{session:Ae(),batchKey:n.key,json:{proofRequestId:r}}),Sr).catch(async o=>{throw o instanceof L&&o.status>=500?await fi(n,e,o,r?"picking up this request":"starting this job",`canary jobs start ${e}${r?` --proof ${r}`:""}`):o});let s=!gr(n.batchId);zc(n.batchId,"start",e,r),s&&!n.kept?.length&&R(`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} ${xe}/<file> --what "<what it sets up>"`),R(r?`Picked up request ${r} on job ${e}: its 15 minutes run from now. Answer in ${ur(n.batchId,e,r)}/delta.json.`:`Started job ${e}. Its working time is counting; waiting on the user doesn't count.`)}async function nC(e,t){let n=Ae(),r,s;if(t.wait){let a=X().filter(c=>c.sessionId===n).flatMap(c=>lt([{runId:c.runId}]).filter(l=>l.id.toLowerCase()===t.wait.toLowerCase()&&l.batchId===c.batchId).map(l=>({q:l,s:c})))[0];if(!a)throw new _("no_such_question",`No question ${t.wait} from a batch taken in this session.`);({q:r,s}=a)}else{if(!e||!!t.job==!!t.setup)throw new _("usage","Ask about one job (--job <job>) or about setting up (--setup <batch>), with the question text.");if(e.length>zg)throw new _("question_too_long",`A question is one need, in a line or two: this one is ${e.length} characters, and ${zg} 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.");s=t.job?hr(t.job):en(t.setup);let i=Object.keys(s.stopped).find(l=>!s.finalSent.includes(l));if(i)throw new _("job_stopped",`Job ${i} was stopped and its final evidence is due; no question can hold it up.`,`canary jobs submit ${i}${s.proofs[i]?` --proof ${s.proofs[i]}`:""}`);let a=s;await fm(a);let c=()=>He(()=>oe(`/cli/jobs/batches/${a.batchId}/pause`,{session:n,batchKey:a.key,json:{jobId:t.job??null}}),Sr);try{await c()}catch(l){if(l instanceof L&&l.status>=500)throw await fi(a,t.job??null,l,"taking your question",`canary jobs ask ${t.job?`--job ${t.job}`:`--setup ${a.batchId}`} "<question>"`);let d=lt([{runId:a.runId}]).some(u=>u.batchId===a.batchId&&u.status==="open");if(!(l instanceof L&&l.code==="already_waiting")||d)throw l;await oe(`/cli/jobs/batches/${a.batchId}/resume`,{session:n,batchKey:a.key,method:"POST"}),await c()}try{r=Gg(s.checkout,{runId:s.runId,batchId:s.batchId,jobId:t.job??null,verifier:Tl(s.batchId),text:e})}catch(l){throw await oe(`/cli/jobs/batches/${s.batchId}/resume`,{session:n,batchKey:s.key,method:"POST"}).catch(()=>{}),l}R(`Asked ${r.id}; the clock is paused while the user answers. If this command is cut off: canary jobs ask --wait ${r.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 o=Date.now()+C1;for(;;){let i=X().find(c=>c.batchId===s.batchId);if(!i||i.ended)return Pn([{runId:s.runId}],s.batchId,"all"),R(`Canary: batch ${s.batchId} has ended, so ${r.id} needs no answer. Stop what you started and run: canary jobs finish ${s.batchId}`);let a=Vg(r.path);if(a?.status==="answered"){let c=yl(r.path).first,l=lm(a),d=!0;try{c&&({resumed:d}=await He(()=>oe(`/cli/jobs/batches/${s.batchId}/resume`,{session:n,batchKey:s.key,method:"POST"})))}catch(u){if(!Ko(u))return R(`${l} Couldn't restart the clock with Canary; run canary jobs ask --wait ${r.id} to try again.`)}return R(d?l:`${l} It came after the wait ran out, so ${r.jobId?"that job":"the jobs not yet run"} already ended.`)}if(a?.status==="expired")return R(`No answer to ${r.id} in time: Canary ended ${r.jobId?`job ${r.jobId}`:"this batch's jobs not yet run"}; it can be re-checked. Move on.`);if(Date.now()>=o)return R(`No answer to ${r.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 ${r.id}`);await an(2e3)}}var zg=350;function lm(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(s=>JSON.stringify(s)).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)",r=(e.more??[]).map(s=>` Added later: ${s.text}`).join("");return`Answer to ${e.id}${n}: ${e.answer}${r} 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.`}var um=e=>Je(Ae()).find(t=>t.runId.startsWith(e))?.runId??e;async function rC(e){let t=um(e),{stopped:n}=await oe(`/cli/jobs/runs/${t}/stop`,{session:Ae(),method:"POST"});js(X().filter(r=>r.runId===t&&r.sessionId===Ae()).map(r=>r.batchId),Ln+3e4),R(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 sC(e,t){let n=um(e),r=(()=>{try{return yi(P(ce(n),"results")).filter(i=>i.endsWith(".json")).map(i=>i.slice(0,-5))}catch{return[]}})(),s=t.map(i=>r.find(a=>a.startsWith(i.toLowerCase()))??i),{retried:o}=await oe(`/cli/jobs/runs/${n}/retry`,{session:Ae(),method:"POST",json:{jobIds:s}});R(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 ${s.length?"the ones named are still going":"none of its checks is one"}.`)}async function oC(e,t){let n=Ae(),r=Jg(Je(n),e);if(r.status==="expired")return R(`The wait for ${r.id} had already run out: the check timed out. Keep this answer in canary.md; the check can be re-checked.`);let s=(it(n).userAt??"")>r.askedAt,o=(it(n).said??[]).filter(a=>a.at>r.askedAt).map(a=>a.text),i=r.status==="answered";Yg(r,t,s,o),R(i?`Added to the answer to ${r.id}: its verifier gets it with its listener's next news.`:`Answered ${r.id}: its verifier reads it within seconds, from its waiting question or its listener.${s?" 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 iC(e,t){let n=Ae(),r=hr(e);if(r.finalSent.includes(e))throw new _("final_sent","This job's final evidence after its stop was already sent.");let s=cm(t.proof),o=s?"with this answer":"with this job's evidence",i=`canary jobs submit ${e}${s?` --proof ${s}`:""}`,a=ur(r.batchId,e,s??void 0),c=P(cn(le(r.batchId)),"packs",e,...s?[`proof-${s}`]:[]);if(Te(a)&&cn(a)!==c)throw new _("pack_folder_link",`${a} is a link, so the evidence would be read from somewhere else.`,"Make it a plain folder holding the evidence files.");let l,d;try{if(!Kf(r.batchId))throw new Error("the plugin's hooks saw nothing of this batch's verifier");l=Gp(r.batchId,e,s);let h=l.calls.at(-1);h?.kind==="command"&&h.ended==="not_run"&&/\bcanary\s+jobs\s+submit\b/.test(h.what)&&l.calls.pop();let p=lt([{runId:r.runId}]).filter(g=>g.batchId===r.batchId).map(({id:g,jobId:m,text:C,status:A,answer:b,userSpoke:S})=>({id:g,jobId:m,text:C,status:A,answer:b,userSpoke:S??!1})),f=l.calls.filter(g=>g.kind==="file"&&g.ended==="ran").map(g=>g.what);d=Ng(a,s?"delta":"pack",{jobId:e,commit:r.code.commit,tree:r.code.treeHash,uncommitted:r.code.uncommitted??null,scripts:aC(de(r),r.batchId,e,s),scriptsFrom:P(de(r),xe),diff:await vg(de(r)),warmCopy:r.warm??!1,stopped:!!r.stopped[e],startedAt:l.jobStartedAt,observed:{calls:l.calls,earlierCalls:l.earlierCalls,minutes:l.minutes,stopped:!!r.stopped[e],putBack:await wg(cn(de(r)),f),questions:p},byHand:Jp(r.batchId)},s,il(r.checkout))}catch(h){if(h instanceof _)throw h;if(Al(h))throw new _("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: ${i}`);let p=im(h);throw p?Wo(p):await fi(r,e,h,o,i)}lC(r,e,d.pack),cC(r,e,s,d.pack,l);let u={session:n,batchKey:r.key};try{let h=await He(()=>oe(`/cli/jobs/${e}/evidence`,{...u,json:d.upload}),Sr);for(let p of h.missing){let f=d.bytes.get(p);await He(()=>oe(`/cli/jobs/${e}/evidence/${h.uploadId}?path=${encodeURIComponent(p)}`,{...u,method:"PUT",bytes:f,timeoutMs:T1(f.length)}),Sr)}await He(()=>oe(`/cli/jobs/${e}/evidence/${h.uploadId}/complete`,{...u,method:"POST"}),Sr)}catch(h){throw h instanceof L&&h.status>=500?await fi(r,e,h,o,i):h}if(r.stopped[e]&&xt(r.batchId,h=>void h.finalSent.push(e)),zc(r.batchId,"sent",e,s),Fc(r.batchId,e),R(`Sent ${s?`the answer to request ${s} on`:"the evidence for"} job ${e}; Canary is judging it, and the result reaches your listener.`),d.hidden.length){let h=new Map;for(let{name:g,path:m}of d.hidden)h.set(g,[...new Set([...h.get(g)??[],m])]);let p=[...h].filter(([g])=>g!==wr).map(([g,m])=>`${g} (in ${m.join(", ")})`),f=h.get(wr);R(`Canary hid secret values before sending: ${[...p.length?[`these by their names: ${p.join("; ")}`]:[],...f?[`${wr} (in ${f.join(", ")})`]:[]].join("; and ")}. That is best effort, so keep secret values out of what you record.`)}}async function fi(e,t,n,r,s){let o;try{o=await xs(e.sessionId,t?{jobId:t,batchKey:e.key}:{batchId:e.batchId,batchKey:e.key},n)}catch(i){return Sl(i)?i:new _("internal_error",rn,`Run it again in a minute: ${s}`)}return o.requeued?new _("internal_error",`Canary hit an internal error ${r}, 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}.`):o.ended>0?new _("internal_error",`Canary hit an internal error ${r}, 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 _("internal_error",`Canary hit an internal error ${r}, 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 aC(e,t,n,r){let s=P(e,xe),o=P(ur(t,n),xe),i=r?P(ur(t,n,r),`proof-${r}-scripts`):o,a=[],c=l=>{for(let d of Te(l)?yi(l,{withFileTypes:!0}):[]){let u=P(l,d.name),h=Qg(s,u).split(wi).join("/");if(d.name.startsWith(".")||d.name==="node_modules"||h===Cr||a.length>=fC)continue;if(d.isDirectory()){c(u);continue}if(!d.isFile()||Ar(u).size>dm||!$n.test(`${bl(i)}/${h}`))continue;let p=Mt(u);if(p.subarray(0,8e3).includes(0)||r&&Te(P(o,h))&&Mt(P(o,h)).equals(p))continue;Fn(pt(P(i,h)),{recursive:!0}),$s(P(i,h),p);let{atime:f,mtime:g}=Ar(u);x1(P(i,h),f,g),a.push(`${bl(i)}/${h}`)}};return c(s),a}function cC(e,t,n,r,s){let o=`${t}:${n??0}`;if(e.stopped[t]||e.sentBack?.includes(o))return;let i=s.calls.filter(u=>u.kind==="command"&&(u.ended==="ran"||u.ended==="failed")).length,a=e.jobMinutes??15,c=s.startedAt===null||s.minutes<a/3,l=s.startedAt===null?"It was never started":`It used ${Math.round(s.minutes)} of its ${a} minutes`,d="claim"in r?r.claim.verdict==="cannot_run"&&(i===0||c)&&[`This job is coming back as one that couldn't run. ${l}, and Canary's record shows ${i} command${i===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."]:i===0&&r.steps.length===0&&r.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(d)throw xt(e.batchId,u=>void(u.sentBack=[...u.sentBack??[],o])),new _("nothing_run",d[0],d[1])}function lC(e,t,n){if(!("claim"in n)||n.claim.verdict==="cannot_run")return;let[r,s]=e.ports,o=e.targets?.[t];for(let i 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 a=Number(i[1]??i[2]??NaN);if(!(Number.isNaN(a)||a>=r&&a<=s)&&!(o&&uC(o)===`${i[0].replace(/:\d+$/,"").toLowerCase()}:${a}`))throw new _("not_this_batch",`The evidence gives ${i[0]} as what was tested, which is outside this batch's ports (${r}-${s}), 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${o?`; this job's running target is ${o}, as take printed it`:""}.`)}}function uC(e){try{let t=new URL(e);return`${t.hostname.toLowerCase()}:${t.port||(t.protocol==="https:"?"443":"80")}`}catch{return null}}async function dC(e,t){let n=hr(e);if(Nl(n,e),!$n.test(t))throw new _("usage",`${t} isn't a path from the earlier evidence.`,"Use a path take printed under earlier files.");let r=await He(()=>up(`/cli/jobs/${e}/earlier?path=${encodeURIComponent(t)}`,{session:Ae(),batchKey:n.key})),s=cn(de(n)),o=pt(P(s,t));for(;!Te(o);)o=pt(o);if(cn(o)!==s&&!cn(o).startsWith(s+wi))throw new _("outside_copy",`${t} leads outside the copy through a link.`);Fn(pt(P(s,t)),{recursive:!0});let i=P(s,t);Te(i)&&(i=`${i}.earlier`);let a=v1(i,ui.O_WRONLY|ui.O_CREAT|ui.O_EXCL|ui.O_NOFOLLOW,420);try{S1(a,r)}finally{b1(a)}R(`Wrote ${t} from the earlier evidence to ${i}.`)}async function hC(e,t){let n=en(e),r=Number(t.pid),s=Number.isInteger(r)&&r>1?Rt(r):null;if(s===null)throw new _("no_such_process",`No running process ${t.pid}.`);if(!el(r,n))throw new _("not_this_batch",`Process ${r} 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.");xt(e,o=>void o.processes.push({pid:r,startedAt:s,what:t.what??"background process"})),R(`Recorded process ${r}; finish stops it with the batch.`)}var pi="kept.json",dm=256*1024,fC=80;async function pC(e,t,n){let r=en(e),s=cn(de(r)),o=Bo(r.checkout),i=il(r.checkout),a=[];for(let l of t){let d=Re(Rl(s,l));if(!Ir(d,[P(s,xe)])||!Ar(d).isFile()||Ar(d).size>dm||bl(d)===Cr)throw new _("not_a_setup_script",`${l} isn't a script in ${P(s,xe)}.`,"Keep the setup script, and any file it runs, from that folder.");let u=Mt(d,"utf8"),h=[...[r.batchId,xr(r.batchId)].filter(f=>u.includes(f)).map(f=>`this batch's id (${f})`),...[s,de(r),le(r.batchId),r.checkout,wl()].filter(f=>u.includes(f)).slice(0,1).map(f=>`a path on this machine (${f})`),...[...u.matchAll(/\b4[2-5]\d{3}\b/g)].slice(0,1).map(f=>`a port written out (${f[0]})`),...i.filter(f=>u.includes(f.value)).slice(0,1).map(f=>`the value of ${f.name}`)];if(h.length)throw new _("holds_this_batch",`${l} holds ${h.join(", ")}, so the next verifier would have to rewrite it.`,`Read those from ${xe}/${Cr} (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 p=am(u);if(p)throw new _("unlabelled_container",`${l} starts a container without this batch's label (${p.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 ${xe}/${Cr}), run it clean once more, and keep it again.`);a.push({name:Qg(P(s,xe),d).split(wi).join("/"),text:u})}let c=Y(P(o.scripts,pi))??{};for(let{name:l,text:d}of a)Fn(pt(P(o.scripts,l)),{recursive:!0,mode:448}),$s(P(o.scripts,l),d,{mode:384}),c[l]={what:n.what,keptAt:new Date().toISOString()};Pe(P(o.scripts,pi),c),xt(e,l=>void(l.kept=[...new Set([...l.kept??[],...a.map(d=>d.name)])])),R(`Kept ${a.map(l=>l.name).join(", ")} for later checks of this repository: the next take puts ${a.length>1?"them":"it"} in the verifier's copy.`)}async function gC(e){xt(e,t=>void(t.readyAt??=new Date().toISOString())),R("Noted: the app is up. The user now sees that setup is over and that you are getting the checks ready.")}async function mC(e,t){let n=hr(e);Nl(n,e);let r=Date.now()+I1;for(;!Xf(t,n.batchId,e);){if(Date.now()>=r)throw new _("target_busy",`Another verifier is still writing to ${t}.`,"Work without writing to it, or report why the job couldn't run.");await an(2e3)}R(`You may write to ${t}; the lock is released when this job's evidence is sent or the batch finishes.`)}async function yC(e,t){if(!Te(P(le(e),"state.json")))return Dn(le(e),{recursive:!0,force:!0}),R(`Nothing of batch ${e} is on this machine.`);let n=en(e),r=Ae();if(n.sessionId!==r)throw new _("other_session","This batch was taken by another Claude Code session.");let s=n.ended?void 0:(await bi(r)).runs.flatMap(i=>i.batches).find(i=>i.batchId===n.batchId);if(s&&s.state!=="ended"&&s.holder===Nc(n.key)){if(!t.giveBack)throw new _("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 i=!1,{requeued:a,ended:c}=await He(()=>oe(`/cli/jobs/batches/${e}/give-back`,{session:r,batchKey:n.key,method:"POST"}),Sr).catch(async l=>{if(!(l instanceof L&&l.status>=500))throw l;return i=!0,xs(r,{batchId:e,batchKey:n.key},l).catch(()=>{throw new _("internal_error",rn,`Run it again in a minute: canary jobs finish ${e} --give-back`)})});R(a?`Gave batch ${e} back: jobs it hadn't sent evidence for will go to a fresh verifier.`:c>0?i?`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 o=await jn(n);R(`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 i of o)R(`Left in place: ${i}`)}async function hm(){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 wC(){try{let e=await hm(),t=e.agent_id,n=e.hook_event_name,r=e.tool_input;if(n==="PreToolUse"&&r?.subagent_type==="canary:verifier"&&(r.isolation||r.name))return R(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:NC}}));if(n==="PostToolUse"&&e.tool_name==="AskUserQuestion"&&typeof e.session_id=="string"){let v=it(e.session_id).asking;if(v&&Te(v)){let I=Rp(e,v);I.commands!==null&&kp(v,I.commands),I.envFiles&&vp(v,I.envFiles.files,I.envFiles.answer)}return await mi(e.session_id,Ns,MC(e))}if(n==="UserPromptSubmit"&&typeof e.session_id=="string")return typeof e.prompt=="string"&&kC.test(e.prompt)?void 0:await mi(e.session_id,R1,typeof e.prompt=="string"?[e.prompt]:[]);let s=e.agent_type==="canary:verifier"&&typeof t=="string"?t:null,o=m1("sha256").update(JSON.stringify([e.tool_name??null,e.tool_input??null])).digest("hex").slice(0,16),i={call:typeof e.tool_use_id=="string"?e.tool_use_id:o,same:o},a=n==="PermissionRequest"?IC(e):null;if(a===!0)return R(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"allow"}}}));if(a&&!a.shared){let v=s&&at(s);return v&&pr(v,{same:o},"sent_back",a.reason),R(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"deny",message:$C(a.reason)}}}))}if(!s)return;if(n==="PermissionRequest")return await jC(s,o,a?a.reason:"");if(n==="PermissionDenied")return bC(s,i,e);await PC(s,typeof n=="string"?n:"",o,typeof e.duration_ms=="number"?Math.max(0,Math.round(e.duration_ms)):0);let c=String(e.tool_name),l=e.tool_input,d=gi.has(c)?l?.file_path??l?.notebook_path:null,u=c==="Bash"&&typeof l?.command=="string"?l.command:null,h=typeof d=="string"||u!==null&&!fr(u);if(n==="PostToolUse"||n==="PostToolUseFailure"){let v=h?at(s):null;if(!v)return;pr(v,i,n==="PostToolUse"?"ran":"failed",xC(e)),u!==null?Zc(v,i.call,SC(e)):typeof d=="string"&&n==="PostToolUse"&&Bp(v,i.call,Re(d));return}if(n==="PostToolBatch")return CC(s,e);if(n!=="PreToolUse")return;let p=(v,I,$)=>{v&&pr(v,i,"sent_back",$),R(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:I}}))};if(typeof d=="string"){let v=at(s);v&&si(v,i,"file",Re(d));let I=TC(s,e);I&&p(v,I,I.includes("the user's own word")?"it changes the user's part of the notes":"outside the verifier's own folders");return}if(u===null)return;let f=/\bcanary\s+jobs\s+(?:take|listen)\s+([0-9a-fA-F-]{36})\b/.exec(u)?.[1];f&&at(s)!==f&&Vf(s,f);let g=at(s);if(g&&h){let v=e.tool_input;si(g,i,"command",u,typeof v.description=="string"?v.description:"",v.run_in_background===!0)}let m=g?X().find(v=>v.batchId===g):void 0,C=m?.checkout??(typeof e.cwd=="string"?e.cwd:null),A=C&&Nn(C)?.commands==="run"?null:Bg(u),b=m?AC(u,ki(m,m.checkout),m.checkout):null,S=m?OC(u,m,typeof e.cwd=="string"?e.cwd:m.checkout):null,x=_C(s,u);x?p(g,x,"the job moved to another batch"):vC.test(u)?p(g,"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"):b?p(g,b,"it names what Canary itself keeps about the checks"):S?p(g,S,"it writes a file outside the verifier's own folders"):A&&p(g,Ug(A),A)}catch{}}function bC(e,t,n){let r=at(e),s=n.tool_input,o=n.tool_name==="Bash"&&typeof s?.command=="string"?s.command:null;!r||o===null&&!gi.has(String(n.tool_name))||(o!==null&&fr(o)&&si(r,t,"command",o),pr(r,t,"blocked",typeof n.reason=="string"?n.reason:""))}var kC=/^\s*(?:<task-notification>|<agent-message\b|Another Claude session sent a message)/,gi=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),vC=/\bcanary\s+(?:jobs\s+(?:answer|approvals|stop|retry)|answer)\b/;function xC(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 SC(e){if(typeof e.error=="string")return e.error;let t=e.tool_response;if(typeof t?.persistedOutputPath=="string")try{return Mt(t.persistedOutputPath,"utf8")}catch{}return typeof t?.stdout=="string"?t.stdout:""}function CC(e,t){let n=at(e),r=Array.isArray(t.tool_calls)?t.tool_calls:[];if(!n||r.length===0)return;let s=qp(n);for(let o of r){if(typeof o.tool_use_id!="string"||typeof o.tool_response!="string")continue;let i=/^Command running in background .*Output is being written to: (\S+\.output)/.exec(o.tool_response)?.[1];i?Wp(n,o.tool_use_id,i):s.has(o.tool_use_id)&&pr(n,{call:o.tool_use_id},"not_run",o.tool_response)}}function AC(e,t,n){let r=qe(n),s=r?[Ze(r).dir]:[];for(let o of new Set([H(),Re(H()),P(pt(H()),"approvals"),Re(P(pt(H()),"approvals"))]))for(let i=e.indexOf(o);i!==-1;i=e.indexOf(o,i+1)){let a=/^[^\s'"`;|&<>()]*/.exec(e.slice(i))[0];if(!t.holds(Re(a))&&!Ir(Re(a),s))return`Canary: not run. ${a} 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 IC(e){let t=e.tool_input,n=String(e.tool_name),r=(n==="Bash"||n==="Monitor")&&typeof t?.command=="string"?t.command:null;if(r!==null&&fr(r))return!0;let s=t?.file_path??t?.notebook_path??t?.path,o=typeof s=="string"?Re(s):null;if(typeof e.agent_id!="string"){let d=typeof e.cwd=="string"?Rr(e.cwd):null,u=d&&qe(d);if(!d||!u)return!1;let h=Ze(u),p=[h.dir,P(H(),"runs")];return r!==null?Ap(r,f=>Ir(Re(f.startsWith("~/")?P(wl(),f.slice(2)):Rl(e.cwd,f)),p)):o===null?!1:RC.has(n)?Ir(o,p):gi.has(n)&&[h.canaryMd,h.secrets].map(Re).includes(o)&&Nn(d)?.commands==="run"}if(e.agent_type!=="canary:verifier")return!1;let i=at(e.agent_id),a=i?X().find(d=>d.batchId===i):void 0,c=a?.checkout??(typeof e.cwd=="string"?e.cwd:null);if(!c||Nn(c)?.commands!=="run")return!1;let l=ki(a,c);if(r!==null){let d=u=>{try{return Ar(u).size<=262144?Mt(u,"utf8"):null}catch{return null}};return li(r,{roots:l.folders.flatMap(u=>[...new Set([u,Re(u)])]),cwd:c,home:wl(),ports:a?.ports??[0,0],label:mr(a?.batchId??""),composeProject:yr(a?.batchId??""),read:d,dockerOwn:a&&((u,h)=>Qp(a.batchId,u,h))})??!0}return gi.has(n)?o===null?!1:l.holds(o)||{reason:`it changes ${s}, which isn't one of the checks' own files`,shared:!1}:!0}var RC=new Set(["Read","Grep","Glob"]);function Re(e){let t=Rl(e);for(let n=t;;n=pt(n))try{return P(cn(n),t.slice(n.length))}catch{if(n===pt(n))return t}}var Ir=(e,t)=>t.map(Re).some(n=>e===n||e.startsWith(n+wi));function ki(e,t){let n=qe(t),r=n&&Ze(n),s=e?[de(e),le(e.batchId)]:[],o=e?Re(P(le(e.batchId),"state.json")):null;return{folders:s,holds:i=>Ir(i,s)&&i!==o||r!==null&&i===Re(r.canaryMd)}}function TC(e,t){let n=t.tool_input,r=n?.file_path??n?.notebook_path,s=at(e),o=s?X().find(i=>i.batchId===s):void 0;return!o||typeof r!="string"?null:ki(o,o.checkout).holds(Re(r))?EC(o,Re(r),t):`Canary: not written. ${r} is outside your own folders, so nothing would remove it when the batch ends. Write the checks' scripts in your copy (${de(o)}) and scratch files in ${dr(o.batchId)}; keep a setup script for later checks with canary jobs keep.`}function EC(e,t,n){let r=qe(e.checkout);if(!r||t!==Re(Ze(r).canaryMd))return null;let s=n.tool_input,o;try{o=Mt(t,"utf8")}catch{return null}let i=Array.isArray(s?.edits)?s.edits:[s??{}],a=typeof s?.content=="string"?s.content:o;if(typeof s?.content!="string")for(let l of i){if(typeof l.old_string!="string"||typeof l.new_string!="string"){a=null;break}a=l.replace_all?a.split(l.old_string).join(l.new_string):a.replace(l.old_string,()=>l.new_string)}let c=l=>l.includes(zt)?l.slice(0,l.indexOf(zt)):l;return a!==null&&c(a)===c(o)?null:`Canary: not written. Everything in canary.md above "${zt.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 "${zt.replace(/^#+ /,"")}" and "What worked and what failed", and ask a question for anything that needs the user.`}function OC(e,t,n){let r=ki(t,t.checkout).folders,s=Pg(e,n).find(o=>!o.startsWith("/dev/")&&!Ir(Re(o),r));return s?`Canary: not run. It writes ${s}, 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 ${dr(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 $C=e=>`Canary: not run, because ${e}. 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.`,NC="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 _C(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(a=>a[1]),r=at(e);if(n.length===0||!r)return null;let s=X(),o=s.find(a=>a.batchId===r),i=o&&n.find(a=>!o.jobs.some(c=>c.jobId===a)&&s.some(c=>c.jobs.some(l=>l.jobId===a)));return i?`Canary: not run. Job ${i} 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 jC(e,t,n=""){let r=at(e),s=r?X().find(o=>o.batchId===r&&o.claimed):void 0;if(s){zf(e,t,s.batchId,n);try{await oe(`/cli/jobs/batches/${s.batchId}/pause`,{session:s.sessionId,batchKey:s.key,json:{jobId:null,approval:!0},timeoutMs:Ns}),ks(s.batchId)}catch(o){o instanceof L&&!_t(o)?(bs(Jo(e).filter(i=>i.call===t).map(i=>i.name)),ks(s.batchId)):Mc(s.batchId,{call:"pause"})}}}async function PC(e,t,n,r){let s=t==="PostToolUse"||t==="PostToolUseFailure";if(!s&&t!=="PostToolBatch"&&t!=="SubagentStop")return;let o=Jo(e).filter(a=>!s||a.call===n),i=X().find(a=>o.some(c=>c.batchId===a.batchId))?.sessionId;i&&t!=="SubagentStop"&&await mi(i);for(let a of new Set(o.map(c=>c.batchId))){let c=o.filter(d=>d.batchId===a);bs(c.map(d=>d.name));let l=X().find(d=>d.batchId===a);!l||Jo(e).some(d=>d.batchId===a)||await pm(l,s?r:0).catch(()=>{})}}function MC(e){let t=e.tool_response?.answers;return t&&typeof t=="object"?Object.values(t).filter(n=>typeof n=="string"):[]}async function mi(e,t=Ns,n=[]){if(Object.keys(it(e).runs).length===0)return;let r=new Date().toISOString(),s=n.map(o=>o.trim()).filter(Boolean).map(o=>({at:r,text:o.length>300?`${o.slice(0,299)}\u2026`:o}));vt(e,o=>({...o,userAt:r,said:[...o.said??[],...s].slice(-10)})),await oe("/cli/jobs/answered",{session:e,method:"POST",timeoutMs:t}).catch(()=>{})}async function fm(e){Nt(e.batchId).length&&await mi(e.sessionId),await pm(e),bs(Nt(e.batchId))}async function pm(e,t=0){try{await oe(`/cli/jobs/batches/${e.batchId}/resume`,{session:e.sessionId,batchKey:e.key,json:{workedMs:t,approval:!0},timeoutMs:Ns})}catch(n){if(!(n instanceof L)||_t(n))throw Mc(e.batchId,{call:"resume",since:Date.now()-t}),n}ks(e.batchId)}async function LC(e,t){let n=Nt(e.batchId).length>0,r={session:e.sessionId,batchKey:e.key,timeoutMs:Ns};try{t.call==="pause"&&n&&await oe(`/cli/jobs/batches/${e.batchId}/pause`,{...r,json:{jobId:null,approval:!0}}),t.call==="resume"&&!n&&await oe(`/cli/jobs/batches/${e.batchId}/resume`,{...r,json:{workedMs:Math.max(0,Date.now()-t.since),approval:!0}})}catch(s){if(!(s instanceof L)||_t(s))return}ks(e.batchId,t.call)}function js(e,t){e.length!==0&&Zg(process.execPath,[process.argv[1],"jobs","clean-ended",...e,"--after",String(t)],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref()}async function FC(e,t){await an(Number(t.after)||0);let n=Ae();for(let r of X().filter(s=>e.includes(s.batchId)&&s.sessionId===n&&!s.left))await jn(r).catch(()=>{})}async function DC(e){await WC(e).catch(()=>{})}async function WC(e){if(!e.end){let n=(await hm()).session_id,r=(typeof n=="string"?n:null)??process.env.CLAUDE_CODE_SESSION_ID;if(!r)return;if(Object.keys(it(r).runs).length===0)return Wc(r);Zg(process.execPath,[process.argv[1],"jobs","session-end","--end",r],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref();return}let t=e.end;await He(()=>oe("/cli/jobs/session-end",{session:t,method:"POST",timeoutMs:1e4})).catch(()=>{});for(let n of X().filter(r=>r.sessionId===t))await jn(n).catch(()=>{});for(let{runId:n}of Je(t))Dn(P(ce(n),"source.bundle"),{force:!0});Wc(t)}function gm(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(ye(j1)),t.command("list").description("this session's checks, batches and open questions").action(ye(F1)),t.command("take <batch>").description("take a batch: build its copy and claim it").action(ye(D1)),t.command("listen <batch>").description("the verifier's listener: returns after the next news, or about 9 minutes").action(ye(eC,{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(ye(tC,{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(ye(nC,{urgent:!0})),t.command("stop <run>").description("stop a run's checks that haven't finished, at the user's word").action(ye(rC)),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(ye(sC)),t.command("answer <question> <text>").description("answer a verifier's question").action(ye(oC,{local:!0})),t.command("submit <job>").option("--proof <n>","send the answer to request <n>").description("send a job's evidence").action(ye(iC,{urgent:!0})),t.command("earlier <job> <path>").description("fetch a file of the earlier evidence for a re-check").action(ye(dC)),t.command("created <batch>").requiredOption("--pid <pid>","the process id").option("--what <what>","what it is").description("record a background process for cleanup").action(ye(hC,{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(ye(pC,{local:!0})),t.command("ready <batch>").description("say the app is up, so the user sees that setup is over").action(ye(gC,{local:!0})),t.command("lock <job> <target>").description("write to a target marked safe for writes, one verifier at a time").action(ye(mC,{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(ye(yC)),t.command("session-end").option("--end <session>").description("called by the plugin's session-end hook").action(ye(DC,{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(ye(FC,{sweep:!1,local:!0})),t.command("hook").description("called by the plugin's hooks on a verifier's tool calls").action(wC),t.command("approvals <action>").description("reset: forget the user's choices for this repository, so they are asked again").action(ye(async n=>{if(n!=="reset")throw new _("usage","The only action is reset.");xp(Rr()),R("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(ye(async()=>R(_g),{sweep:!1}))}w();ee();ro();nt();Gt();import{appendFileSync as pA,existsSync as gA}from"node:fs";import{join as $m}from"node:path";w();ja();w();var mm=["claude","codex","cursor"];function ym(e,t=0,n=[]){if(typeof e=="string")e&&n.push(e);else if(t<3&&e&&typeof e=="object")for(let r of Object.values(e))ym(r,t+1,n);return n}var ln=e=>typeof e=="string"&&e?e:void 0,BC=new Set(["Bash","PowerShell","Monitor"]);function wm(e,t,n=process.env,r=process.platform){if(!t||typeof t!="object"||Array.isArray(t))return null;let s=t;if(e==="cursor"){let l=Array.isArray(s.workspace_roots)?s.workspace_roots:[],d=ln(s.cwd)??ln(l[0])??ln(n.CURSOR_PROJECT_DIR)??process.cwd(),u=ln(s.conversation_id)?{chat:ln(s.conversation_id)}:{};return s.hook_event_name==="beforeShellExecution"&&typeof s.command=="string"?{kind:"shell",command:s.command,cwd:d,shell:r==="win32"?"powershell":"posix",...u}:s.hook_event_name==="beforeMCPExecution"&&typeof s.tool_name=="string"?{kind:"tool",toolName:s.tool_name,cwd:d,...u}:null}if(s.hook_event_name!=="PreToolUse"||typeof s.tool_name!="string")return null;let o=ln(s.cwd)??process.cwd(),i=ln(s.session_id)?{chat:ln(s.session_id)}:{},a=s.tool_input&&typeof s.tool_input=="object"?s.tool_input:{};if(BC.has(s.tool_name)&&typeof a.command=="string")return{kind:"shell",command:a.command,cwd:o,shell:s.tool_name==="PowerShell"?"powershell":"posix",...i};let c=e==="codex"&&s.tool_name==="exec"?ym(typeof s.tool_input=="string"?s.tool_input:a):[];return c.length?{kind:"script",toolName:s.tool_name,texts:c,cwd:o,...i}:{kind:"tool",toolName:s.tool_name,cwd:o,...i}}function bm(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}}):""}Ao();w();fe();var Wn=(e,t)=>({decision:"allow",cause:e,...t?{message:t}:{}}),km=e=>e.replace(/[\x00-\x1f\x7f]+/g,"?");function vi(e){if(e.mode==="off")return Wn("mode_off");if(!e.trigger)return Wn("not_a_trigger");if(!e.login)return null;if(!e.login.ok)return Wn(e.login.cause);if(e.chat===void 0)return null;if(e.chat===null)return Wn("no_chat");if(!e.lookup)return null;if(!e.lookup.ok)return Wn(e.lookup.cause,`Canary couldn't be asked about this push (${km(e.lookup.detail)}), so it went ahead.`);let{hold:t}=e.lookup;return t.state==="clear"?Wn("clear"):t.state==="remind"?{decision:"deny",cause:t.state,message:t.agent}:e.skip===void 0?null:e.skip?Wn("skipped",`Canary: the person chose to continue without verifying (${km(e.skip.reason)}). Tell them it was pushed without a Canary check.`):{decision:"deny",cause:t.state,message:t.agent}}var UC=new Set(["clear","none","running","open","remind"]);async function vm(e,t,n,r={}){let s=AbortSignal.timeout(r.timeoutMs??Tn);try{let o=new URLSearchParams({workspaceId:e.workspaceId,chat:t,...n?{raised:n}:{}}),i=await W(`/api/v1/cli/hold?${o.toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:Sc(s,r.signal)});return!i||typeof i!="object"||!UC.has(String(i.state))?{ok:!1,cause:"unknown_state",detail:"Canary answered in a way this CLI version does not understand (update the CLI)"}:i.state!=="clear"&&typeof i.agent!="string"?{ok:!1,cause:"unknown_state",detail:"Canary's answer had no words to show"}:{ok:!0,hold:i}}catch(o){return s.aborted?{ok:!1,cause:"lookup_timeout",detail:`Canary did not answer within ${Math.round((r.timeoutMs??Tn)/1e3)} s`}:o instanceof L&&o.status>=400&&o.status<500?{ok:!1,cause:"lookup_refused",detail:`Canary answered ${o.status}: ${o.message}${o.fix?` (${o.fix})`:""}`}:o instanceof L&&o.status>=500?{ok:!1,cause:"lookup_error",detail:`Canary answered ${o.status}`}:{ok:!1,cause:"lookup_unreachable",detail:o instanceof Error?o.message:String(o)}}}w();w();ee();import{randomUUID as qC}from"node:crypto";import{mkdirSync as HC,readFileSync as GC,renameSync as JC,rmSync as YC,writeFileSync as VC}from"node:fs";import{dirname as KC,join as zC}from"node:path";var _l=()=>zC(K(),"hold","raised.json"),XC=720*60*60*1e3,ZC=100,QC=8e3;function xm(e){let t;try{t=JSON.parse(GC(_l(),"utf8"))}catch{return{}}let n=t?.chats;if(t?.version!==1||!n||typeof n!="object"||Array.isArray(n))return{};let r={};for(let[s,o]of Object.entries(n)){let i=typeof o?.at=="string"?Date.parse(o.at):NaN;Array.isArray(o?.keys)&&Number.isFinite(i)&&e-i<XC&&(r[s]={keys:o.keys.filter(a=>typeof a=="string"),at:o.at})}return r}function Sm(e,t=Date.now()){let n=[...xm(t)[e]?.keys??[]];for(;n.join(",").length>QC;)n.shift();return n.length>0?n.join(","):void 0}function Cm(e,t,n=Date.now()){try{Mr(`${_l()}.lock`,"what pushes asked about",()=>{let r=xm(n),s=new Set(r[e]?.keys);for(let a of t)s.delete(a),s.add(a);r[e]={keys:[...s].slice(-ZC),at:new Date(n).toISOString()};let o=_l(),i=`${o}.${qC()}.tmp`;HC(KC(o),{recursive:!0,mode:448});try{VC(i,JSON.stringify({version:1,chats:r},null,2)+`
|
|
1863
|
+
`,{flag:"wx",mode:384}),JC(i,o)}catch(a){throw YC(i,{force:!0}),a}})}catch{}}ic();w();import{homedir as eA}from"node:os";import{basename as tA,isAbsolute as nA,resolve as rA}from"node:path";var sA=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),oA=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,Am=e=>e.replace(/\\(.)/g,(t,n)=>n==="n"?`
|
|
1864
|
+
`:n==="t"?" ":n);function Em(e,t){for(let n of e)for(let r of n.matchAll(oA)){let s=r[4]!==void 0?[...r[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(i=>Am(i[1]??i[2]??"")).join(" "):Am(r[1]??r[2]??r[3]??""),o=Ml(s,t);if(o)return o}return null}function Om(e,t){let n=!e.includes("__");if(!n&&!e.startsWith("mcp__"))return null;let r=sA.get(n?e:e.slice(e.lastIndexOf("__")+2));return r?{action:r,via:"mcp",dir:t}:null}function iA(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]==="\\"){n++;continue}let r=e[n]==="$"&&e[n+1]==="("?2:e[n]==="`"?1:0;if(!r)continue;let s=Si(e,n+r,r===2?")":"`");t.push(s.tokens),n=s.end-1}return t}var xi=!1;function Si(e,t,n){let r=[],s=[],o="",i=!1,a=!1,c=!0,l=t,d=0,u=()=>{i&&r.push({word:o,quoted:a,bare:c}),o="",i=!1,a=!1,c=!0},h=f=>{u(),r.push({op:f})},p=(f,g)=>{let m=Si(e,f,g);return r.push({sub:m.tokens}),o+="$()",i=!0,m.end};for(;l<e.length;){let f=e[l],g=e[l+1];if(n==="`"&&f==="`")return u(),{tokens:r,end:l+1};if(n===")"&&f===")"&&d===0)return u(),{tokens:r,end:l+1};if(f==="\\"&&!xi){g===`
|
|
1846
1865
|
`||(o+=g??"",i=!0),l+=2;continue}if(f==="'"){i||(c=!1);let m=e.indexOf("'",l+1);o+=e.slice(l+1,m<0?void 0:m),i=!0,a=!0,l=m<0?e.length:m+1;continue}if(f==='"'){for(i||(c=!1),i=!0,a=!0,l++;l<e.length&&e[l]!=='"';)e[l]==="\\"&&!xi&&l+1<e.length&&/[$`"\\\n]/.test(e[l+1])?(o+=e[l+1],l+=2):e[l]==="$"&&e[l+1]==="("?l=p(l+2,")"):e[l]==="`"?l=p(l+1,"`"):(o+=e[l],l++);l++;continue}if(f==="#"&&!i){for(;l<e.length&&e[l]!==`
|
|
1847
1866
|
`;)l++;continue}if(f==="<"&&g==="<"&&e[l+2]!=="<"){let m=/^<<(-?)[ \t]*(?:'([^']*)'|"([^"]*)"|\\?([^\s;&|<>()]+))/.exec(e.slice(l));if(m){u(),s.push({end:m[2]??m[3]??m[4]??"",stripTabs:m[1]==="-",literal:m[4]===void 0||m[0].includes("\\")}),l+=m[0].length;continue}}if(f===`
|
|
1848
1867
|
`){h(`
|
|
1849
1868
|
`),l++;for(let m of s.splice(0))for(;;){let C=e.indexOf(`
|
|
1850
|
-
`,l),A=e.slice(l,C<0?void 0:C);if(l=C<0?e.length:C+1,(m.stripTabs?A.replace(/^\t+/,""):A)===m.end||C<0)break;if(!m.literal)for(let b of
|
|
1851
|
-
`)}catch{}let u=
|
|
1869
|
+
`,l),A=e.slice(l,C<0?void 0:C);if(l=C<0?e.length:C+1,(m.stripTabs?A.replace(/^\t+/,""):A)===m.end||C<0)break;if(!m.literal)for(let b of iA(A))r.push({sub:b})}continue}if(f===" "||f===" "||f==="\r"){u(),l++;continue}if(f===">"||f==="<"){let m=f===">";u(),l++;let C=!1;for(;l<e.length&&(e[l]===">"||e[l]==="&"||e[l]==="|");)e[l]==="&"&&(C=!0),l++;for(;l<e.length&&(e[l]===" "||e[l]===" ");)l++;let A=l;for(;l<e.length&&!/[\s;&|()<>`]/.test(e[l]);)l++;if(m&&!C){let b=e.slice(A,l);b&&r.push({write:b})}continue}if(f==="&"&&g===">"){u(),l++;continue}if((f==="&"||f==="|")&&g===f){h(f+f),l+=2;continue}if(f==="$"&&g==="("){l=p(l+2,")");continue}if(f==="`"){l=p(l+1,"`");continue}if(f==="("){d++,h(f),l++;continue}if(f===")"){d=Math.max(0,d-1),h(f),l++;continue}if(f===";"||f==="&"||f==="|"){h(f),l++;continue}if(/[0-9]/.test(f)&&!i&&/^[0-9]+[<>]/.test(e.slice(l))){l++;continue}o+=f,i=!0,l++}return u(),{tokens:r,end:e.length}}var aA=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),cA=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),Im=e=>/^(\/dev\/|\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\$TMPDIR|\$\{TMPDIR)/.test(e),un=!1,lA=new Set(["if","then","else","elif","fi","do","done","while","until","for","!","{","}","time"]),Rm=new Set(["command","exec","builtin","nohup","noglob","nice","sudo","env"]),uA=new Set(["sh","bash","zsh","dash","ksh"]),Tm=6,dA=new Set(["-c","--exec-path","--namespace","--super-prefix","--config-env","--attr-source"]);function jl(e,t){if(t===null||/[$`*?[]/.test(e.word))return null;let n=e.bare&&(e.word==="~"||e.word.startsWith("~/"))?eA()+e.word.slice(1):e.word;return e.bare&&n.startsWith("~")?null:nA(n)?n:rA(t,n)}function hA(e,t){let n=t,r=0;for(;r<e.length;r++){let o=e[r].word;if(o==="-C"){n=e[r+1]?jl(e[r+1],n):null,r++;continue}if(o.startsWith("-C")&&o.length>2){n=jl({...e[r],word:o.slice(2)},n);continue}if(/^--(git-dir|work-tree)(=|$)/.test(o)){n=null,o.includes("=")||r++;continue}if(dA.has(o)){r++;continue}if(!o.startsWith("-"))break}if(e[r]?.word!=="push")return null;let s=[];for(let{word:o}of e.slice(r+1)){if(o==="--")break;if(o==="--dry-run"||o==="--help"||o==="-h"||/^-[a-zA-Z]*n[a-zA-Z]*$/.test(o)||o==="--delete"||/^-[a-zA-Z]*d[a-zA-Z]*$/.test(o))return null;o.startsWith("-")||s.push(o)}return s.length>1&&s.slice(1).every(o=>o.startsWith(":"))?null:{dir:n}}function fA(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n].word;if(r==="--help"||r==="-h"||r==="--dry-run")return!1;if(r==="-R"||r==="--repo"){n++;continue}r.startsWith("-")||t.push(r)}return t[0]==="pr"&&(t[1]==="create"||t[1]==="new")}function Pl(e,t,n){let r=t,s=[],o=!1,i=()=>{let a=s;s=[];let c=o;o=!1;let l=m=>(!m&&c&&(un=!0),m),d=0,u=(m,C)=>m.bare&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(m.word)||!m.quoted&&(lA.has(m.word)||Rm.has(m.word)||!!C&&Rm.has(C.word)&&m.word.startsWith("-"));for(;d<a.length&&u(a[d],a[d-1]);)d++;let h=a[d];if(!h)return l(null);let p=tA(h.word.replace(/\\/g,"/")).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase(),f=a.slice(d+1);if(p==="cd"||p==="pushd")return r=f[0]&&!f[0].word.startsWith("-")?jl(f[0],r):null,l(null);let g=(m,C)=>({action:m,via:"shell",dir:C,...un?{editsFirst:!0}:{}});if(p==="git"){let m=hA(f,r);if(m)return g("push",m.dir);let C=f.find(b=>!b.word.startsWith("-"))?.word,A=(C==="checkout"||C==="switch")&&f.some(b=>/^-(b|B|c|C|-orphan)$/.test(b.word));return C&&cA.has(C)&&!A&&(un=!0),l(null)}if(p==="gh")return fA(f)?g("pr_create",r):l(null);if(p==="tee"?f.some(m=>!m.word.startsWith("-")&&!Im(m.word))&&(un=!0):(aA.has(p)||(p==="sed"||p==="perl")&&f.some(m=>/^-[a-zA-Z]*i/.test(m.word)))&&(un=!0),(p==="npm"||p==="pnpm"||p==="yarn")&&f[0]?.word==="version"&&(un=!0),n<Tm&&(uA.has(p)||p==="eval")){let m=p==="eval"?0:f.findIndex(A=>/^-[a-zA-Z]*c[a-zA-Z]*$/.test(A.word))+1,C=p==="eval"?f.map(A=>A.word).join(" "):m>0?f[m]?.word:void 0;if(C)return l(Pl(Si(C,0,null).tokens,r,n+1))}return l(null)};for(let a of e){if("word"in a){s.push(a);continue}if("write"in a){o=o||!Im(a.write);continue}if("sub"in a){let l=n<Tm?Pl(a.sub,r,n+1):null;if(l)return l;continue}let c=i();if(c)return c}return i()}function Ml(e,t,n={}){if(!/\bpush\b/.test(e)&&!/\bpr\b/.test(e))return null;xi=n.shell==="powershell",un=!1;try{return Pl(Si(e,0,null).tokens,t,0)}finally{xi=!1,un=!1}}var mA=8e3,yA=64*1024*1024;async function wA(e,t={}){let n=e.kind==="shell"?Ml(e.command,e.cwd,{shell:e.shell}):e.kind==="script"?Em(e.texts,e.cwd):Om(e.toolName,e.cwd);if(!n)return e.chat&&e.kind!=="tool"&&ld(e.kind==="shell"?[e.command]:e.texts)&&dd(e.cwd,e.chat),vi({mode:"on",trigger:null});let r={mode:wn(),trigger:n},s,o=()=>Math.max(250,Math.min(Tn,t.deadline?t.deadline-Date.now()-500:Tn)),i=[async()=>{Ke({cwd:e.cwd,agent:!0});let l=Q(),d=V().team?.id;if(!l){r.login={ok:!1,cause:"not_logged_in"};return}if(!d){r.login={ok:!1,cause:"no_workspace"};return}s={token:l,apiUrl:ue(),workspaceId:d},t.seen&&(t.seen.target=s),r.login={ok:!0}},async()=>{r.chat=e.chat??null},async()=>{r.lookup=await vm(s,e.chat,Sm(e.chat),{timeoutMs:o(),signal:t.signal})},async()=>{r.skip=mf(e.chat)}],a=null;for(let l of i){if(a=vi(r),a)break;await l()}a??=vi(r)??{decision:"allow",cause:"crash"};let c=r.lookup?.ok?r.lookup.hold.raise:void 0;return a.decision==="deny"&&Array.isArray(c)&&c.length>0&&Cm(e.chat,c),a}async function bA(e){let t=[],n=0;for await(let r of e){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>yA)throw new Error("event too large");t.push(s)}return JSON.parse(Buffer.concat(t).toString("utf8").replace(/^\uFEFF/,""))}var kA={claude:"claude-code",codex:"codex",cursor:"cursor"};async function vA(e,t){Ke({harness:kA[e]});let n=t.ceilingMs??mA;mu(250);let r=new AbortController,s,o=new Promise(d=>{s=setTimeout(()=>{r.abort(),d({decision:"allow",cause:"ceiling"})},n)}),i={},a=(async()=>{let d=await bA(t.stdin);try{gA($m(K(),"hook-debug"))&&pA($m(K(),"hook-events.log"),`${new Date().toISOString()} ${e} ${JSON.stringify(d)}
|
|
1870
|
+
`)}catch{}let u=wm(e,d);return u?wA(u,{signal:r.signal,deadline:Date.now()+n,seen:i}):{decision:"allow",cause:"not_a_trigger"}})().catch(()=>({decision:"allow",cause:r.signal.aborted?"ceiling":"crash"})),c=await Promise.race([a,o]);clearTimeout(s);let l=bm(e,c);return l&&await t.write(l),c.cause!=="not_a_trigger"&&t.note(`canary hook: ${c.decision} (${c.cause})`),await hh(c,i.target),c}function Nm(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(mm.includes(t)){let n=Number(process.env.CANARY_HOOK_CEILING_MS)>0?Number(process.env.CANARY_HOOK_CEILING_MS):void 0;await vA(t,{stdin:process.stdin,ceilingMs:n,note:r=>process.stderr.write(r+`
|
|
1852
1871
|
`),write:r=>new Promise(s=>process.stdout.write(r+`
|
|
1853
|
-
`,()=>s()))})}process.exit(0)})}w();fe();
|
|
1854
|
-
`);let c=a.replace(/\.json$/,".md");return
|
|
1855
|
-
`):"";return{result:t.data.result??null,more
|
|
1856
|
-
`),""}}function
|
|
1857
|
-
`:""}Canary \xB7 more to come: canary wait ${t}`)),process.exitCode=o}function
|
|
1858
|
-
`)}}var
|
|
1859
|
-
`))}async function
|
|
1860
|
-
`))}async function
|
|
1872
|
+
`,()=>s()))})}process.exit(0)})}w();fe();ee();function _m(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,r=Q();if(r)try{await W("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}vu();let s=!!process.env.CANARY_TOKEN;n?console.log(JSON.stringify({ok:!0,...s?{note:"CANARY_TOKEN env var still set"}:{}})):(console.log("Logged out."),s&&console.error("Note: CANARY_TOKEN is set in your environment \u2014 unset it to fully log out."))})}w();import{createHash as RA}from"node:crypto";import{mkdirSync as TA,readdirSync as EA}from"node:fs";import{dirname as OA,join as Hm}from"node:path";fe();ee();nt();w();import{copyFileSync as jm,existsSync as Ms,mkdirSync as Lm,renameSync as xA,rmSync as Ll,writeFileSync as Pm}from"node:fs";import{dirname as SA,join as Ue}from"node:path";Gt();var Ci=()=>({runs:{},told:{},said:[],endedAt:{}}),CA=4*6e4;function Mm(e){let t=Y(Ue(On(e.requestId),"request.json"));return e.session!==null&&t?.chat===e.session}function Ai(e){let t=Y(Ue(On(e),"request.json"));return Rr(typeof t?.checkout=="string"&&Ms(t.checkout)?t.checkout:process.cwd())}function AA(e,t,n){let r=ce(t);Lm(r,{recursive:!0,mode:448});let s=On(e),o=Ue(r,"source.bundle");if(!Ms(o)&&Ms(Ue(s,"source.bundle")))try{xA(Ue(s,"source.bundle"),o)}catch{jm(Ue(s,"source.bundle"),o),Ll(Ue(s,"source.bundle"),{force:!0})}for(let a of["source.json",lr])!Ms(Ue(r,a))&&Ms(Ue(s,a))&&jm(Ue(s,a),Ue(r,a));let i=Ai(e);vt(n,a=>(a.owner=cr()??a.owner??null,a.runs[t]??={checkout:i},a))}var Ps=e=>typeof e=="string"&&e?e:null,IA=e=>{try{return ot(e,"job"),!0}catch{return!1}};function Fm(e,t,n){let r=Ps(e.data.checksRun),s=n.session;if(e.type==="ended"&&s&&Mm(n)&&Ll(Ue(On(n.requestId),"source.bundle"),{force:!0}),!r||!s)return[];if(!Object.hasOwn(t.runs,r)){if(e.type==="ended"||!Mm(n))return[];AA(n.requestId,r,s),t.runs[r]=[]}let o=e.data.cMessage;switch(typeof o=="number"&&vt(s,i=>({...i,cursors:{...i.cursors,[r]:Math.max(i.cursors[r]??0,o)}})),e.type){case"checks_ready":{let i=(Array.isArray(e.data.batches)?e.data.batches:[]).map(c=>Ps(c.batchId)).filter(c=>c!==null);t.runs[r]=[...new Set([...t.runs[r]??[],...i])];let a=e.do.flatMap(c=>c.type==="start_verifier"?[c.batchId]:[]);return a.length>1&&Object.keys(Ol(Ai(n.requestId))).length===0&&(t.held={...t.held,[r]:[...new Set([...t.held?.[r]??[],...a.slice(1)])]}),[]}case"verdict":{let i=e.data.record;if(!i?.jobId||!IA(i.jobId))return[];let a=Ue(ce(r),"results",`${i.jobId}.json`);Lm(SA(a),{recursive:!0}),Pm(a,JSON.stringify(i,null,2)+`
|
|
1873
|
+
`);let c=a.replace(/\.json$/,".md");return Pm(c,$l(i,r)),i.verdict==="broken"?[{type:"read_record",path:c}]:[]}case"batch_ended":{let i=Ps(e.data.batchId);if(!i)return[];t.said.includes(`ended:${i}`)||t.said.push(`ended:${i}`),tn(i);let a=X().find(c=>c.batchId===i&&c.sessionId===s);return e.data.reason==="set_aside"?(a&&js([i],(a.setupMinutes??30)*6e4+3e4),[]):((t.endedAt??={})[i]??=Date.now(),a&&js([i],Ln+3e4),[])}case"wait_over":{let i=Ps(e.data.batchId);return i&&Pn([{runId:r}],i,Ps(e.data.jobId)),[]}case"ended":{let i=e.data.result?.running;return!(Array.isArray(i)&&i.length>0)&&!_s(r)&&Ll(Ue(ce(r),"source.bundle"),{force:!0}),[]}default:return[]}}var Dm=e=>e.asks.length>0||e.approvals.length>0||e.changed||(e.setups?.length??0)>0;function Wm(e,t,n=Date.now()){let r={asks:[],approvals:[],changed:!1},s=Object.keys(e.runs);if(!t.session||s.length===0)return{tell:r,do:[]};let o=t.session;for(let l of s)Uo(l);let i=[],a=l=>e.said.includes(`ended:${l}`);for(let l of lt(s.map(d=>({runId:d})))){if(l.status!=="open"||a(l.batchId))continue;let d=e.told[l.path];d!==void 0&&n-d<CA||(e.told[l.path]=n,l.text.trim()&&r.asks.push({text:l.text}),i.push({type:"answer",questionId:l.id,question:l.text,command:`canary jobs answer ${l.id} "<answer>"`}))}let c=Object.values(e.runs).flat().filter(l=>!a(l));for(let l of c)for(let d of Nt(l)){let u=vs(d);!u||e.said.includes(`approval:${d}`)||(e.said.push(`approval:${d}`),r.approvals.push({why:u}))}if(n-(e.setupsAt??0)>=ni){let l=ri(o,c);l.length>0&&(r.setups=l,e.setupsAt=n)}for(let[l,d]of Object.entries(e.endedAt??{}))n-d<Ln||e.said.includes(`unfinished:${l}`)||X().some(u=>u.batchId===l&&u.sessionId===o&&!u.left)&&(e.said.push(`unfinished:${l}`),i.push({type:"stop_verifier",batchId:l,restart:"never"}));for(let[l,d]of Object.entries(e.held??{})){let u=d.filter(f=>!a(f)&&!e.said.includes(`start:${f}`)),h=e.runs[l]??[];if(u.length===0||!(h.some(gr)||h.filter(f=>!d.includes(f)).every(a)))continue;let p=Ai(t.requestId);for(let f of u)e.said.push(`start:${f}`),ms(Qt(p))?i.push({type:"start_verifier",batchId:f}):ys(f,o,p)}for(let l of ws(o))!c.includes(l.batchId)||!ms(Qt(l.checkout))||gs(l.checkout)||(tn(l.batchId),i.push({type:"start_verifier",batchId:l.batchId}));return{tell:r,do:i}}async function Bm(e,t){if(e.said.includes("changed")||Object.keys(e.runs).length===0)return!1;let n=Y(Ue(On(t.requestId),"source.json"))?.treeHash;if(typeof n!="string")return!1;try{if((await Qr(Ai(t.requestId))).treeHash===n)return!1}catch{return!1}return!0}Jt();var $A=25,Ii=45e3,NA=9*6e4,_A=9e4,jA=5,PA=200,Fl=(e,t)=>Hm(K(),"requests",t===null?`${e}.json`:`${e}.${RA("sha256").update(t).digest("hex").slice(0,16)}.json`);function Um(e,t){let n=Y(Fl(e,t)),r=typeof n?.cursor=="number"&&Number.isInteger(n.cursor)&&n.cursor>=0?n.cursor:0,s=n?.checks&&typeof n.checks=="object"?{...Ci(),...n.checks}:void 0,o=Array.isArray(n?.held?.do)?{do:n.held.do,result:n.held.result,exitCode:n.held.exitCode===2?2:0}:void 0;return{cursor:r,ending:typeof n?.ending=="string"?n.ending:null,...s?{checks:s}:{},...o?{held:o}:{}}}function qm(e,t,n){TA(OA(Fl(e,t)),{recursive:!0,mode:448}),Pe(Fl(e,t),n)}function Gm(e){let t=[...e].reverse().find(r=>r.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(r=>typeof r=="string").join(`
|
|
1874
|
+
`):"";return{result:t.data.result??null,more:$t(n),do:t.do}}var Dl=()=>yn();function Jm(e,t,n,r){let s=Dl();return W(`/api/v1/cli/requests/${e}/events?after=${n}&wait=${r}`,{token:t,signal:AbortSignal.timeout(Ii),...s?{headers:{"x-canary-session":s}}:{}}).then(o=>({...o,events:o.events.map(os)}))}function MA(e,t,n){return W(`/api/v1/cli/requests/${e}/here`,{method:"POST",token:t,body:n,signal:AbortSignal.timeout(Ii)})}var LA=new Set(["start_verifier","stop_verifier","keep_late_answer"]),FA={read:Jm,pause:e=>new Promise(t=>setTimeout(t,e)),onEvent:Fm,localNews:Wm,changedFiles:Bm,here:MA,session:Dl};async function DA(e,t,n,r,s=FA){let o=Date.now()+r,i=null,a={...n},c={...Ci(),...n.checks},l={requestId:e,session:s.session()},d=()=>Object.keys(c.runs).length>0?{...a,checks:c}:a;for(;;){let u=o-Date.now();if(u<=0)return{parts:[],place:d(),ended:!1};let h=Object.keys(c.runs).length>0,p;try{p=await s.read(e,t,a.cursor,Math.max(1,Math.min(h?jA:$A,Math.floor(u/1e3)))),i=null}catch(A){if(!be(A)||(i??=Date.now(),Date.now()-i>_A))throw A;await s.pause(2e3);continue}let f=[],g=a.cursor;for(let A of p.events){let b=s.onEvent(A,c,l),S=GA(A.data.checksRun),x=new Set(Object.values(c.held??{}).flat()),v=(S===null||Object.hasOwn(c.runs,S)?A.do:A.do.filter(I=>!LA.has(I.type))).filter(I=>I.type!=="start_verifier"||!x.has(I.batchId));(A.part||b.length>0)&&f.push({seq:A.seq,say:$t(A.say),do:[...v,...b]}),a={cursor:A.seq,ending:A.type==="ended"&&typeof A.data.ending=="string"?A.data.ending:a.ending}}if(!p.ended){let A=s.localNews(c,l);p.events.some(S=>S.type==="verdict")&&await s.changedFiles(c,l)&&(A.tell.changed=!0);let b=Dm(A.tell)?await WA(s,e,t,A.tell):"";b&&A.tell.changed&&c.said.push("changed"),(b||A.do.length>0)&&f.push({seq:null,say:$t(b),do:A.do})}let m=p.ended&&!p.events.some(A=>A.type==="ended")&&g>0,C=Gm(m?(await s.read(e,t,g-1,0)).events:p.events)?.result;if(p.ended||f.length>0)return{parts:f,place:d(),ended:p.ended,...C?{result:C}:{}}}}async function WA(e,t,n,r){try{return(await e.here(t,n,r)).say}catch(s){return process.stderr.write(`Canary couldn't word what happened on this machine (${s instanceof Error?s.message:String(s)}); what to do about it is still given.
|
|
1875
|
+
`),""}}function BA(e,t){let n={...Ci(),...e,runs:{...e?.runs},told:{...e?.told},said:[...e?.said??[]],endedAt:{...e?.endedAt},held:{...e?.held}};for(let[r,s]of Object.entries(t?.runs??{}))n.runs[r]=[...new Set([...n.runs[r]??[],...s])];for(let[r,s]of Object.entries(t?.held??{}))n.held[r]=[...new Set([...n.held[r]??[],...s])];for(let[r,s]of Object.entries(t?.told??{}))n.told[r]=Math.max(n.told[r]??0,s);for(let[r,s]of Object.entries(t?.endedAt??{}))n.endedAt[r]=Math.min(n.endedAt[r]??s,s);return n.said=[...new Set([...n.said,...t?.said??[]])],t?.setupsAt&&(n.setupsAt=Math.max(n.setupsAt??0,t.setupsAt)),n}async function UA(e,t){let n=[];for(;;){let r=await Jm(e,t,n.at(-1)?.seq??0,0);if(n.push(...r.events),r.ended||r.events.length<PA)return{events:n,ended:r.ended}}}function Wl(e,t,n){if(n instanceof L)return n.status===404?D(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?D(e,"not_logged_in","Your Canary login is no longer valid.","run `canary login`",3):be(n)?D(e,"unreachable","Canary couldn't be reached.",`run \`canary wait ${t}\` again in a minute`,2):D(e,n.code??"api_error",n.message,n.fix,n.status>=500?2:3);let r=as(n);if(r)return D(e,"home_not_writable",r.message,r.fix,2);D(e,"internal_error",n instanceof Error?n.message:String(n),void 0,2)}function Tr(e,t,n,r,s,o,i){e?console.log(JSON.stringify({ok:!0,requestId:t,say:n,do:r,ended:s,...i?{result:i}:{},exitCode:o})):(n&&console.log(n),s||console.log(`${n?`
|
|
1876
|
+
`:""}Canary \xB7 more to come: canary wait ${t}`)),process.exitCode=o}function qA(e){if(st.test(e))return e;if(!/^[0-9a-f][0-9a-f-]{5,34}$/i.test(e))return null;let t;try{t=EA(Hm(K(),"requests"))}catch{return null}let n=new Set(t.map(r=>r.slice(0,36)).filter(r=>st.test(r)&&r.toLowerCase().startsWith(e.toLowerCase())));return n.size===1?[...n][0]:null}async function HA(e,t){Ke({cwd:process.cwd(),agent:t,mode:"wait"});let n=Q();if(!n)return D(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!st.test(e))return D(t,"invalid_request_id","That isn't a request id.","use the id Canary gave when you asked",3);let r=Dl(),s=Um(e,r);if(s.held){Tr(t,e,"",s.held.do,!0,s.held.exitCode,s.held.result),qm(e,r,{cursor:s.cursor,ending:s.ending,...s.checks?{checks:s.checks}:{}});return}let o;try{o=await DA(e,n,s,NA)}catch(p){return Wl(t,e,p)}let i=Um(e,r),a=o.parts.filter(p=>p.seq===null||p.seq>i.cursor),c={...o.place,cursor:Math.max(o.place.cursor,i.cursor),...o.place.checks||i.checks?{checks:BA(i.checks,o.place.checks)}:{}},l=a.flatMap(p=>p.do),d=[...l.filter(p=>p.type==="ask"),...l.filter(p=>p.type!=="ask")],u=ss(a.map(p=>p.say)),h=c.ending==="failed"?2:0;i.held?(Tr(t,e,u,d,!1,0),c={...c,held:i.held}):t&&o.ended&&u&&d.some(p=>p.type==="ask")?(Tr(t,e,u,[],!1,0),c={...c,held:{do:d,...o.result?{result:o.result}:{},exitCode:h}}):Tr(t,e,u,d,o.ended,h,o.result);try{qm(e,r,c)}catch(p){process.stderr.write(`Canary couldn't save where this wait got to (${p instanceof Error?p.message:String(p)}); the next wait may show these lines again.
|
|
1877
|
+
`)}}var GA=e=>typeof e=="string"&&e.trim()?e.trim():null;async function JA(e,t,n=!1){Ke({cwd:process.cwd(),agent:t,mode:"show"});let r=Q();if(!r)return D(t,"not_logged_in","Not logged in","run `canary login` first",3);let s=qA(e);if(!s)return D(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:o,ended:i}=await UA(s,r),a=Gm(o),c=n?$t((await W(`/api/v1/cli/requests/${s}/repro`,{token:r,signal:AbortSignal.timeout(Ii)})).say):ss([...o.map(l=>l.say),a?.more??""]);Tr(t,s,c,a?.do.filter(l=>l.type==="fix"||l.type==="pr_section")??[],i,0,a?.result??void 0)}catch(o){Wl(t,s,o)}}var YA=(e,t,n)=>W(`/api/v1/cli/requests/${e}/answer`,{method:"POST",token:t,body:n,signal:AbortSignal.timeout(Ii)});async function VA(e,t,n,r,s,o=YA){Ke({cwd:process.cwd(),agent:s,mode:"answer"});let i=Q();if(!i)return D(s,"not_logged_in","Not logged in","run `canary login` first",3);if(!st.test(e))return D(s,"invalid_request_id","That isn't a request id.","use the id in the command Canary gave with its question",3);let a=n.trim();if(!a)return D(s,"no_answer","There's no answer in those words.",`put the answer in quotes: canary answer ${e} --id ${t} "<answer>"`,3);try{Tr(s,e,$t((await o(e,i,{id:t,text:a,from:r})).say),[],!1,0)}catch(c){Wl(s,e,c)}}function Ym(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").action((t,n)=>HA(t,n.json===!0)),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)=>JA(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 iu("--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,r)=>VA(t,r.id,n.join(" "),r.from,r.json===!0))}w();fe();ee();Jt();w();fe();Jt();var KA={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"},zA=15e3;function XA(e){return e&&KA[e]||"Other"}var ZA=e=>{let t=e?.finding?.nextActionCodeRef??e?.codeRefs?.[0]??e?.checkReadback?.codeRefs?.[0]??null;return t?{file:t.file,line:t.startLine??null}:null},QA=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 eI(e,t,n){if(e.status!=="completed"||kt(e.materiality)===null)return null;let r=t??null,s=r?.isStatic===!0?"source":"runtime",o=e.result==="pass"?"passed":e.result==="fail"?"failed":"could_not_run",i=F(r?.assertion)||null;return{checkRunId:e.checkRunId,checkUrl:`${n}/checks/${e.checkRunId}`,scenarioId:e.stageBCheckId??e.checkRunId,category:XA(r?.lane),title:F(e.title),proof:s,status:o,whatWasTried:s==="source"?F(r?.finding?.whatWasTested)||null:F(r?.finding?.reproduce??r?.finding?.whatWasTested)||null,expected:i||F(r?.finding?.whatWasTested)||null,observed:F(r?.finding?.headline??r?.verdict?.reasonOneLiner)||null,assertion:i,location:ZA(r),evidence:QA(r),fix:s==="source"&&F(r?.finding?.reproduce)||null,reason:o==="could_not_run"&&(F(r?.verdict?.reasonOneLiner)||is[e.blockedReason??""])||null}}async function Vm(e,t,n){let r=new Map,s=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;for(let o of t)if(!(o.status!=="completed"||r.has(o.checkRunId)||!s.test(o.checkRunId)))try{r.set(o.checkRunId,await W(`/api/v1/red-team/runs/${e}/checks/${o.checkRunId}/finding`,{token:n.token,signal:AbortSignal.timeout(zA),...n.baseUrl?{baseUrl:n.baseUrl}:{}}))}catch{r.set(o.checkRunId,null)}return r}function Km(e,t,n){let r=e.stageC.checks.map(s=>eI(s,t.get(s.checkRunId)??null,n.runUrl)).filter(s=>s!==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:r,passed:r.filter(s=>s.status==="passed").length,failed:r.filter(s=>s.status==="failed").length,couldNotRun:r.filter(s=>s.status==="could_not_run").length,errored:e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns}}var Qm=new Set(["completed","failed","cancelled"]);function zm(e){return Qm.has(e.status)?null:e.status==="queued"?"queued":e.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function Xm(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 Bl(e,t,n,r,s={}){let o=Q();if(!o)return D(e,"not_logged_in","Not logged in","run `canary login` first",3),null;if(t.some(i=>!st.test(i)))return D(e,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await W(n,{token:o,...r?{baseUrl:r}:{},...s})}catch(i){if(i instanceof L){if(i.status===404)return D(e,"not_found","no such run or check in your workspace",void 0,3,{httpStatus:404}),null;let a=!be(i)&&i.status>=400&&i.status<500,c=i.fix??(i.status===401?"run `canary login`":a?void 0:"run the command again in a minute");return D(e,"api_error",i.message,c,a?3:2,{httpStatus:i.status}),null}throw i}}var Zm=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 tI(e,t,n){let r=await Bl(t,[e],`/api/v1/red-team/runs/${e}`,n);if(!r)return;let s=r.run,o=r.repository?.fullName??"";if(t){let l=s.stageC.checks.filter(p=>kt(p.materiality)!==null).map(p=>({checkRunId:p.checkRunId,scenarioId:p.stageBCheckId??p.checkRunId,title:F(p.title),status:Xm(p)})),d={runId:s.runId,status:s.status,progress:zm(s),treeHash:s.target.treeHash??"",repo:o,reverifySourceRunId:s.reverifySourceRunId??null,startedAt:s.startedAt??null,completedAt:s.completedAt??null,failureMessage:s.failure?.publicMessage??null,checks:l,passed:l.filter(p=>p.status==="passed").length,failed:l.filter(p=>p.status==="failed").length,couldNotRun:l.filter(p=>p.status==="could_not_run").length,errored:s.stageC.failedCheckRuns+s.stageC.cancelledCheckRuns},u={},h=Q();if(Qm.has(s.status)&&h){let p=await Vm(e,s.stageC.checks,{token:h,...n?{baseUrl:n}:{}});u=Km(s,p,{runUrl:`${Tt().replace(/\/+$/,"")}/runs/${e}`,repo:o,files:null})}return void console.log(JSON.stringify({ok:!0,...d,...u}))}let i=zm(s),a=[`run ${F(s.runId)} \xB7 ${F(s.status)}${i?` \xB7 ${i}`:""}${s.target.treeHash?` \xB7 tree ${F(s.target.treeHash).slice(0,12)}`:""}`];s.failure?.publicMessage&&a.push(` ${F(s.failure.publicMessage)}`);let c=s.stageC;a.push(`checks ${c.checks.length} \xB7 ${c.results.pass} passed \xB7 ${c.results.fail} failed \xB7 ${c.results.blocked} could not verify \xB7 ${c.failedCheckRuns+c.cancelledCheckRuns} errored`);for(let l of c.checks){let d=Xm(l),u=d==="could_not_run"?"could not verify":d,h=l.result==="blocked"?is[l.blockedReason??""]:void 0;a.push(` ${kt(l.materiality)??"P3"} ${u.padEnd(16)} ${F(l.title)} ${F(l.checkRunId)}${h?` (${h})`:""}`)}console.log(a.join(`
|
|
1878
|
+
`))}async function nI(e,t,n,r){let s=await Bl(n,[e,t],`/api/v1/red-team/runs/${e}/checks/${t}/finding`,r);if(!s)return;if(n)return void console.log(JSON.stringify({ok:!0,runId:e,checkRunId:t,...s}));let o=[];o.push(F(s.finding?.headline)||"(no finding written for this check yet)"),s.verdict&&o.push(`verdict: ${F(s.verdict.result)}${s.verdict.reasonOneLiner?` \u2014 ${F(s.verdict.reasonOneLiner)}`:""}${s.isStatic?" (reasoned from the code, not run)":""}`),s.assertion&&o.push(`assertion: ${F(s.assertion)}`),s.observable&&o.push(`observable: ${F(s.observable)}`),s.checkReadback?.whyThisCheck&&o.push(`why this check: ${F(s.checkReadback.whyThisCheck)}`),s.finding?.whatWasTested&&o.push(`tested: ${F(s.finding.whatWasTested)}`),s.finding?.reproduce&&o.push(`reproduce: ${F(s.finding.reproduce)}`),s.finding?.nextActionCodeRef&&o.push(`\u2192 ${Zm(s.finding.nextActionCodeRef)}`);for(let i of s.codeRefs??[])o.push(` ref ${Zm(i)}${i.reason?` \u2014 ${F(i.reason)}`:""}`);for(let i of s.evidence??[])o.push(` evidence ${F(i.modality)}: ${F(i.caption)}${i.media?` ${F(i.media.url)}`:i.failureReason?` (${F(i.failureReason)})`:""}`);for(let i of s.verdict?.limitations??[])o.push(` limitation: ${F(i)}`);s.network?.failures?.length&&o.push(` network failures: ${s.network.failures.length}`),console.log(o.join(`
|
|
1879
|
+
`))}async function rI(e,t,n,r,s,o){if(await Bl(s,[e,t],`/api/v1/red-team/runs/${e}/checks/${t}/report`,o,{method:"POST",body:{reported:n,...r?{note:r}:{}}})){if(s)return void console.log(JSON.stringify({ok:!0,runId:e,checkRunId:t,reported:n}));console.log(`reported ${n}${r?`: ${F(r)}`:""}`)}}async function sI(e,t,n){let r=Q();if(!r)return D(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!st.test(e))return D(t,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let s;try{s=await hc(e,r,{...n?{baseUrl:n}:{},onProgress:i=>console.error(` ${i}`)})}catch(i){if(i instanceof bt)return D(t,i.code,i.message,`run \`canary run wait ${e}\` again to keep waiting`,2,{runId:e});if(i instanceof L){if(i.status===404)return D(t,"not_found","no such run in your workspace",void 0,3,{httpStatus:404});let a=!be(i)&&i.status>=400&&i.status<500;return D(t,"api_error",i.message,i.fix??(i.status===401?"run `canary login`":a?void 0:`run \`canary run wait ${e}\` again`),a?3:2,{runId:e,httpStatus:i.status})}throw i}let o=fc(s.run,s.run.target?.treeHash??"",s.findings,s.run.reverify);console.log(t?JSON.stringify(o):pc(o)),process.exitCode=o.exitCode}function ey(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,r)=>{try{if(!n)return D(r.json===!0,"bad_id","pass the run id `canary verify` printed","canary run <runId>",3);await tI(n,r.json===!0)}catch(s){D(r.json===!0,"internal_error",s instanceof Error?s.message:String(s),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,r,s)=>{let o=s.optsWithGlobals().json===!0;try{await sI(n,o)}catch(i){D(o,"internal_error",i instanceof Error?i.message:String(i),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,r,s)=>{try{let o=[s.fixed?"fixed":null,s.disputed!==void 0?"disputed":null,s.skipped!==void 0?"skipped":null].filter(Boolean);if(o.length>1)return D(s.json===!0,"bad_report","report exactly one of --fixed, --disputed, --skipped",void 0,3);if(o.length===1){let i=(o[0]==="disputed"?s.disputed:o[0]==="skipped"?s.skipped:void 0)?.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").trim();return i!==void 0&&!i?D(s.json===!0,"bad_report",`--${o[0]} needs a reason`,void 0,3):await rI(n,r,o[0],i,s.json===!0)}await nI(n,r,s.json===!0)}catch(o){D(s.json===!0,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}})}w();to();In();fe();mn();ee();nt();import{readFileSync as hI,unlinkSync as fI,writeFileSync as pI}from"node:fs";import{basename as gI,join as mI}from"node:path";import{setTimeout as yI}from"node:timers/promises";w();import{emitKeypressEvents as oI}from"node:readline";var iI=36,aI=12,ty=64*1024,Ul=new Intl.Segmenter(void 0,{granularity:"grapheme"}),cI={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},lI={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function Ri(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 uI(e,t){let n="";for(let{segment:r}of[...Ul.segment(ie(e))].reverse()){if(us(r+n)>t)break;n=r+n}return n}function ny(e,t,n){let r=e.question,s=Math.max(1,t-5),o=(c,l="text")=>` ${ds(ie(c),l,n)}`,i=0;if(r.secret){for(let c of Ul.segment(e.input??""))if(++i===24)break}let a=r.secret?"\u2022".repeat(i):uI(e.input??"",Math.max(1,s-2));return[o("CANARY \xB7 SETUP","gold"),o(`${e.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${Ri(e.seconds)}`),o(`CLI workspace ${e.workspace}`,"muted"),"",o(r.key,"gold"),...Yt(r.prompt,s).map(c=>o(c)),o(e.inputActive?`\u203A ${a||(r.secret?"(hidden)":"")}`:e.inputSubmitted?"Value captured locally.":"Input deferred","muted"),o(e.inputNotice??(r.secret?"Your value stays hidden.":""),"muted"),o(e.inputActive?"Enter submit \xB7 Esc/Ctrl+C later":e.inputSubmitted?"Waiting for verification to continue.":"Run canary setup to resume.","muted")]}function dI(e,t,n,r){let s=Math.max(1,t-5),o=Math.max(1,n-2),i=e.outcome?lI[e.outcome.status]:e.question?"Your input is needed":cI[e.status],a=e.outcome?.status==="green"?"green":"gold",c=(u,h="text")=>ds(ie(u),h,r),l;if(o<=3)l=[c(i,a),c(`Elapsed ${Ri(e.seconds)}`,"muted")].slice(0,o);else if(e.question&&!e.outcome)l=ny(e,t,r);else{let u=e.seconds%1.6,h=!e.outcome&&["pending","running"].includes(e.status)&&u<1.4?Math.sin(u/1.4*Math.PI*2)*Math.sin(u/1.4*Math.PI):0,p=rr[Math.max(0,Math.min(16,Math.round(h*10)+8))];if(t>=76&&n>=23){let f={1:c("CANARY \xB7 SETUP","gold"),3:c(i,a),5:c(`Elapsed ${Ri(e.seconds)}`,"muted")};l=["",...p.map((g,m)=>` ${c(g,a)} ${f[m]??""}`)]}else l=[` ${c("CANARY \xB7 SETUP","gold")}`,` ${c(i,a)}`,` ${c(`Elapsed ${Ri(e.seconds)}`,"muted")}`];l.push("",` ${c(`Repository ${e.repository}`)}`,` ${c(`CLI workspace ${e.workspace}`)}`),e.detail&&!e.outcome&&l.push(...Yt(e.detail,s).map(f=>` ${c(f,"muted")}`)),e.outcome||l.push("",` ${c("Ctrl+C stops watching \xB7 canary setup resumes","muted")}`)}return(l.length>o?[...l.slice(0,Math.max(0,o-2)),...l.slice(-2)]:l).map(u=>_o(u,Math.max(1,t-1)))}function ry(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,r=!process.env.NO_COLOR,s=nr(t),o=performance.now(),i={...e,status:"submitting",seconds:0},a=!1,c=!1,l,d=!1,u,h,p=()=>({columns:t.columns||80,rows:t.rows||24}),f=k=>{try{t.write(k)}catch{}},g=()=>f(`${ve}0m${ve}?25h`);function m(){if(a||d)return;i.seconds=(performance.now()-o)/1e3;let{columns:k,rows:N}=p();try{s.render(dI(i,k,N,r))}catch{x()}}function C(){let{columns:k,rows:N}=p();return n.isTTY&&k>=iI&&N>=aI&&ny(i,k,!1).length<=N-2}function A(){let k=i.question;if(!k)return;d=!0;try{s.render([])}catch{}let N=Math.max(1,p().columns-3);f(`
|
|
1861
1880
|
Input needed: ${ie(k.key)}
|
|
1862
1881
|
${Yt(k.prompt,N).join(`
|
|
1863
1882
|
`)}
|
|
@@ -1865,37 +1884,37 @@ ${Yt(k.prompt,N).join(`
|
|
|
1865
1884
|
Answer with: canary setup --answer '<value>'
|
|
1866
1885
|
`)}function b(){h&&!C()?h.settle(null,!0):m()}function S(){!a||h||c||(c=!0,process.off("SIGINT",I),process.off("SIGTERM",$),process.off("exit",x),g(),l!==void 0&&(f(`
|
|
1867
1886
|
Stopped watching. Run canary setup to resume verification.
|
|
1868
|
-
`),process.exit(l)))}function x(){a||(a=!0,clearInterval(u),t.off("resize",b),h?.settle(null),S())}function v(k){l=k,x(),S()}function I(){h?h.settle(null):v(130)}function $(){v(143)}async function y(k,N){return a||h||N?.aborted?null:(i.question={...k},i.input="",i.inputActive=!0,i.inputSubmitted=!1,i.inputNotice=void 0,d=!1,C()?new Promise(G=>{let Le=n.isRaw,Ce=n.readableFlowing===!0,ae="",T="",M=!1,E=!1,U="",J=!1,
|
|
1869
|
-
`)),T="";else if(M){let Un=(Ee||se.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(se.sequence??"").includes("\x1B")||(T.length+Un.length<=
|
|
1887
|
+
`),process.exit(l)))}function x(){a||(a=!0,clearInterval(u),t.off("resize",b),h?.settle(null),S())}function v(k){l=k,x(),S()}function I(){h?h.settle(null):v(130)}function $(){v(143)}async function y(k,N){return a||h||N?.aborted?null:(i.question={...k},i.input="",i.inputActive=!0,i.inputSubmitted=!1,i.inputNotice=void 0,d=!1,C()?new Promise(G=>{let Le=n.isRaw,Ce=n.readableFlowing===!0,ae="",T="",M=!1,E=!1,U="",J=!1,ne=!1,Ye=!1,St=!1,et;function z(Ee,se=!1){St||(et={answer:et&&Ee!==null?et.answer:Ee,showStatic:se||et?.showStatic||!1},ne||=!!U&&!E,ae=T="",i.input="",(M||E||U||ne)&&(i.inputNotice="Finishing clipboard input.",m()),gt())}function gt(){if(St||!et||J||M||E||U||ne)return;let{answer:Ee,showStatic:se}=et;St=!0,n.off("keypress",Bn),n.off("data",_r),n.off("data",Ws),n.off("end",At),n.off("error",At),n.off("close",At),N?.removeEventListener("abort",Ct);try{n.setRawMode(Le)}catch{}Ce||n.pause(),f(`${ve}?2004l`),ae="",T="",i.input="",i.inputActive=!1,i.inputSubmitted=Ee!==null,i.inputNotice=Ee===null?"You can provide this value later.":"Input received locally.",h=void 0,se&&!a?A():m(),g(),S(),G(Ee)}function Ct(){z(null)}function At(){M=E=J=ne=!1,U="",z(null)}function _r(Ee){J=!0;for(let se of typeof Ee=="string"?Ee:Ee.toString("utf8")){let Un=E?`${ve}201~`:`${ve}200~`;U=se===Un[U.length]?U+se:se==="\x1B"?se:"",U===Un&&(E=!E,U="")}}function Ws(){J=!1,gt()}function we(Ee){ae.length+Ee.length>ty?(Ye=!0,i.inputNotice="Too long. Ctrl+U clears input."):(ae+=Ee,Ye||(i.inputNotice=void 0))}function Bn(Ee,se){if(!(St||!se))try{if(!J&&se.name==="escape"&&(U=""),!U&&se.sequence?.startsWith("\x1B")&&(ne=!1),et){se.name==="paste-start"?M=!0:se.name==="paste-end"&&(M=!1),gt();return}if(se.name==="paste-start"){M=!0,T="";return}if(se.name==="escape"||se.ctrl&&["c","d"].includes(se.name??"")){Ct();return}if(se.name==="paste-end")M=!1,we(T.replace(/\r\n?/g,`
|
|
1888
|
+
`)),T="";else if(M){let Un=(Ee||se.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(se.sequence??"").includes("\x1B")||(T.length+Un.length<=ty?T+=Un:(Ye=!0,i.inputNotice="Too long. Ctrl+U clears input."));return}else if(se.ctrl&&se.name==="u")ae="",Ye=!1,i.inputNotice=void 0;else if(se.name==="backspace")ae=[...Ul.segment(ae)].slice(0,-1).map(Ay=>Ay.segment).join("");else if(se.name==="return"||se.name==="enter"){if(!ae.trim())i.inputNotice="Enter a value, or Esc to answer later.";else if(!Ye){z(ae);return}}else!se.ctrl&&!se.meta&&Ee&&we(Ee.replace(/[\x00-\x1f\x7f-\x9f]/g,""));i.input=ae,m()}catch{Ct()}}h={settle:z};try{if(n.prependListener("data",_r),oI(n),n.on("keypress",Bn),n.on("data",Ws),n.once("end",At),n.once("error",At),n.once("close",At),N?.addEventListener("abort",Ct,{once:!0}),N?.aborted){Ct();return}n.setRawMode(!0),n.resume(),f(`${ve}?2004h${ve}?25l`),m()}catch{Ct()}}):(i.inputActive=!1,A(),null))}return t.on("resize",b),process.on("SIGINT",I),process.on("SIGTERM",$),process.once("exit",x),u=setInterval(m,80),u.unref(),f(`${ve}?25l`),m(),{update(k,N){a||(i.status=k,i.detail=N,h||(i.question=void 0,i.input=void 0,d=!1),f(`${ve}?25l`),m())},warn(k){if(!a)try{s.render([])}catch{x()}f(`
|
|
1870
1889
|
Warning: ${k.split(/\r?\n/).map(ie).join(`
|
|
1871
1890
|
`)}
|
|
1872
1891
|
|
|
1873
1892
|
`),m()},ask:y,finish(k){if(a)return;h?.settle(null),i.question=void 0,i.outcome=k,d=!1,m(),x();let N=[k.message,...k.updatedFiles?.length?[`Updated locally: ${k.updatedFiles.join(", ")}`]:[],...k.warning?[`Warning: ${k.warning}`]:[],...k.next?[`Next: ${k.next}`]:[]].filter(G=>!!G);N.length&&f(`
|
|
1874
1893
|
${N.flatMap(G=>G.split(/\r?\n/).map(ie)).join(`
|
|
1875
1894
|
`)}
|
|
1876
|
-
`)},stop:x}}
|
|
1877
|
-
`);function
|
|
1895
|
+
`)},stop:x}}Ba();zr();Fe();Gt();Eo();cc();var Er=3e3,Ti=2,wI=9e4,sy=new Set(["pending","running","needs_input","green","red","error","interrupted"]);function Me(e,t){for(let n of[...e.secrets].sort((r,s)=>s.length-r.length))n&&(t=t.split(n).join("[redacted]"));return t}var ql=e=>mI(e,".canary","verify-job.json");function Ls(e){try{let t=JSON.parse(hI(ql(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||!To(t.source)||typeof t.recipeHash!="string"||typeof t.scope.apiUrl!="string"||![t.scope.userId,t.scope.workspaceId,t.scope.repositoryId].every(r=>typeof r=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(r))))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 ze("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 bI(e){return Ls(e)?.jobId??null}var oy=(e,t)=>pI(ql(e),JSON.stringify(t)+`
|
|
1896
|
+
`);function Ei(e){try{fI(ql(e))}catch{}}var Or=(e,t)=>yI(e,void 0,{signal:t});function kI(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 vI(e,t){let n,r;try{n=Bt(e),Vr(e),r=Xn(e).name}catch(u){if(u instanceof ze||u instanceof re){t?console.log(JSON.stringify({ok:!1,error:u.code,message:u.message,..."fix"in u&&u.fix?{fix:u.fix}:{}})):console.error(`\u2717 ${u.message}${"fix"in u&&u.fix?`
|
|
1878
1897
|
Fix: ${u.fix}`:""}`),process.exitCode=1;return}throw u}let s=r??null,o=n.setupSh.trim().split(`
|
|
1879
|
-
`).length,i=
|
|
1880
|
-
`)||void 0,next:`Open Canary: ${Tt().replace(/\/+$/,"")}/repositories`}):(console.log("\u2713 Verified \u2014 the recipe boots from zero in a clean sandbox. This repo is set up on Canary."),i&&console.log(` Workspace: ${i.name}`),t.approved?.healed&&(console.log(" The cloud verifier adjusted the setup while fixing the boot."),d.length?console.log(` Updated locally to match: ${d.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"){
|
|
1898
|
+
`).length,i=kI(n.runJson),a=[...new Set([...n.envManifest.map(u=>u.name),...Object.keys(n.envValues)])],c=n.envManifest.filter(u=>u.neededAt==="boot").map(u=>u.name),{missing:l}=Da(n.envManifest,n.envValues),d=l.length===0;t?console.log(JSON.stringify({ok:d,repo:s,recipe:{setupShLines:o,services:i,envKeys:a,bootRequired:c,missing:l}})):(console.log(`Repo ${s??"(local repository)"}`),console.log(`Recipe .canary/ \xB7 setup.sh (${o} lines) \xB7 run.json (${i.length} service${i.length===1?"":"s"}${i.length?": "+i.join(", "):""})`),console.log(`Env ${a.length} key${a.length===1?"":"s"} \xB7 ${c.length} boot-required \xB7 ${l.length?`MISSING: ${l.join(", ")}`:"all present"}`),d?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.`)),d||(process.exitCode=1)}async function iy(e,t,n,r,s={}){if(t.status==="green"){let o=Ls(e),i=o?.workspace,a=s.recipeChanged??!1;if(o?.recipeHash)try{a||=bn(Bt(e))!==o.recipeHash}catch{a=!0}let c=!1;if(o?.source){let u=(p,f)=>p.sha256===f.sha256&&p.treeHash===f.treeHash&&p.baseTreeHash===f.baseTreeHash&&p.baseSha===f.baseSha&&p.provenance.baselineMode===f.provenance.baselineMode&&(p.provenance.baseRef??null)===(f.provenance.baseRef??null);if(t.approved?.source&&!u(t.approved.source,o.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 h;try{h=await An(e,{baseRef:o.source.provenance.baseRef??void 0}),c=h.manifest.treeHash!==o.source.treeHash||h.manifest.baseTreeHash!==o.source.baseTreeHash||h.manifest.provenance.baselineMode!==o.source.provenance.baselineMode||(h.manifest.provenance.baseRef??null)!==(o.source.provenance.baseRef??null)}catch{c=!0}finally{await h?.dispose()}}if(o?.recipeHash)try{a||=bn(Bt(e))!==o.recipeHash}catch{a=!0}let l=s.writeBack!==!1&&!a&&!c;if(a||c){let u="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.";r.warnings.push(u),!n&&!r.display&&console.error(`! ${u}`)}Ei(e);let d=[];if(t.approved?.healed&&l)try{d=Rd(e,t.approved)}catch(u){let h=Me(r,`Could not update .canary/ with the approved changes: ${u instanceof Error?u.message:String(u)}`);r.warnings.push(h),r.display||console.error(`! ${h}`)}return n?console.log(JSON.stringify({ok:!0,status:"green",jobId:t.jobId,...i?{workspace:i}:{},...a?{recipeChanged:!0}:{},...c?{sourceChanged:!0}:{},...o?.source?{source:o.source,repositoryId:o.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}:{},...d.length?{updatedFiles:d}:{}}}:{}})):r.display?r.display.finish({status:"green",message:`Your recipe boots from zero in a clean sandbox.${i?` Workspace: ${i.name}.`:""}`,updatedFiles:d,warning:r.warnings.join(`
|
|
1899
|
+
`)||void 0,next:`Open Canary: ${Tt().replace(/\/+$/,"")}/repositories`}):(console.log("\u2713 Verified \u2014 the recipe boots from zero in a clean sandbox. This repo is set up on Canary."),i&&console.log(` Workspace: ${i.name}`),t.approved?.healed&&(console.log(" The cloud verifier adjusted the setup while fixing the boot."),d.length?console.log(` Updated locally to match: ${d.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"){Ei(e);let o={phase:t.failure?.phase?Me(r,t.failure.phase):null,failingCommand:t.failure?.failingCommand?Me(r,t.failure.failingCommand):null,log:t.failure?.log?Me(r,t.failure.log):null};return n?console.log(JSON.stringify({ok:!1,status:t.status,jobId:t.jobId,failure:o})):r.display?r.display.finish({status:t.status,message:`Verification ${t.status==="error"?"errored":"failed"}${o.phase?` (${o.phase})`:""}${o.failingCommand?` at: ${o.failingCommand}`:""}${o.log?`
|
|
1881
1900
|
|
|
1882
1901
|
${o.log.slice(-2e3)}`:""}`,warning:r.warnings.join(`
|
|
1883
1902
|
`)||void 0,next:"Fix the recipe in .canary/ and run canary setup again."}):(console.error(`\u2717 Verify ${t.status==="error"?"errored":"failed"}${o.phase?` (${o.phase})`:""}${o.failingCommand?` at: ${o.failingCommand}`:""}`),o.log&&console.error(`
|
|
1884
1903
|
${o.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 o={...t.needsInput,key:Me(r,t.needsInput.key),prompt:Me(r,t.needsInput.prompt)};return n?console.log(JSON.stringify({ok:!1,status:"needs_input",jobId:t.jobId,needsInput:o})):(console.log(`? The cloud verifier needs input${o.secret?" (a secret \u2014 pass the real value, don't echo it anywhere else)":""}:`),console.log(` ${o.key}: ${o.prompt}`),console.log(`
|
|
1885
|
-
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function
|
|
1886
|
-
`+(d?" .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
|
|
1904
|
+
Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function ay(e,t){return e.status==="needs_input"&&e.needsInput?.questionId===t.questionId}async function xI(e,t,n){let r=new AbortController,s=new AbortController,o=e.display.ask({...t,key:Me(e,t.key),prompt:Me(e,t.prompt)},r.signal).then(a=>({kind:"answer",value:a})),i=(async()=>{for(;;){await Or(Er,s.signal);let a=await n(s.signal);if(!ay(a,t))return{kind:"state",view:a}}})();try{return await Promise.race([o,i])}finally{s.abort(),r.abort(),await Promise.allSettled([o,i])}}async function SI(e,t,n,r,s,o){let i="",a=null;async function c(d){for(;;)try{let u=await W(`/api/v1/cli/verify/${t}`,{token:n,baseUrl:s.context?.apiUrl,signal:d});if(!u||!sy.has(u.status))throw new Error("Verification returned an unrecognized state. Run canary setup again to retry.");return a=null,u}catch(u){if(d?.aborted)throw u;if(u instanceof L&&u.status===0&&(a===null&&(a=Date.now(),s.display?s.display.update("retrying","Cloud service unreachable. Retrying the same job."):r||console.log(" \u2026 cloud service unreachable \u2014 retrying")),Date.now()-a<wI)){await Or(Er,d);continue}throw u}}let l;for(;;){let d=l??await c();if(l=void 0,d.status==="interrupted")return"interrupted";if(d.status==="needs_input"&&o&&d.needsInput?.questionId===o.questionId&&Date.now()<o.until){await Or(Er);continue}if(d.status==="needs_input"&&d.needsInput&&s.display){let u=d.needsInput,h=await xI({...s,display:s.display},u,c);if(h.kind==="state"){l=h.view;continue}let p=h.value;if(p===null)return s.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 f=await c();if(!ay(f,u)){l=f;continue}s.display.update("answering","Sending your answer to the verifier.");try{await uy(e,t,n,u,p,r,s)}catch(g){if(g instanceof L&&g.status===409)continue;throw g}o={questionId:u.questionId,until:Date.now()+3e4},s.display.update("answering","Answer received. Waiting for verification to continue."),await Or(Er);continue}if((d.status==="pending"||d.status==="running")&&(s.display?s.display.update(d.status):d.status!==i&&!r&&console.log(` \u2026 ${d.status==="pending"?"queued":"verifying in a clean cloud sandbox (boot + heal \u2014 this can take a while)"}`)),i=d.status,await iy(e,d,r,s))return"terminal";await Or(Er)}}async function Oi(e,t,n,r,s,o){Yn();let i=t;for(let a=0;;){if(await SI(e,i,n,r,s,o)==="terminal")return;if(Ei(e),s.freshUpload=!0,a>=Ti){r?console.log(JSON.stringify({ok:!1,status:"interrupted",jobId:i})):s.display?s.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}a+=1,r?console.error(JSON.stringify({event:"resubmitted",attempt:a,of:Ti})):s.display?s.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${Ti}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${Ti})`);let l=await ly(e,n,r,s);if(l===null)return;i=l,o=void 0}}async function cy(e,t,n,r){let s=r.context??=await xn(e,t),o=n.scope;if(o.apiUrl.replace(/\/+$/,"")!==s.apiUrl.replace(/\/+$/,"")||o.userId!==s.userId||o.workspaceId!==s.workspaceId)throw new re("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 vn({...s,token:t})).repositoryId!==o.repositoryId)throw new re("setup_receipt_scope_mismatch","The setup job saved in .canary/verify-job.json belongs to a different repository. Remove the file to start over.");r.baseRef??=n.source?.provenance.baseRef??void 0,ns(n.source,s,o.repositoryId,{requestKey:`setup:${n.recipeHash}`,uploadId:n.sourceUploadId})}async function ly(e,t,n,r){let s=Bt(e);Vr(e);let{missing:o}=Da(s.envManifest,s.envValues);if(o.length)return n?console.log(JSON.stringify({ok:!1,error:"missing_boot_env",missing:o})):r.display?r.display.finish({status:"error",message:`Boot-required environment values are missing: ${o.join(", ")}`,next:"Fill .canary/env.json and run canary setup again."}):console.error(`\u2717 Boot-required env without values: ${o.join(", ")} \u2014 fill .canary/env.json first.`),process.exitCode=1,null;let i=r.context??=await xn(e,t),a=await vn({...i,token:t}),c=await An(e,{baseRef:r.baseRef});try{r.display?.update("submitting","Uploading your local source and the .canary/ recipe.");let l=bn(s),d=await tr(c,i,a.repositoryId,t,{requestKey:`setup:${l}`,fresh:r.freshUpload});r.freshUpload=!1;let u=await W("/api/v1/cli/verify",{method:"POST",token:t,baseUrl:i.apiUrl,body:{workspaceId:i.workspaceId,repositoryId:a.repositoryId,source:d,setupSh:s.setupSh,runJson:JSON.stringify(s.runJson??null),env:{manifest:s.envManifest,values:s.envValues}}});if(!u?.jobId||u.repositoryId!==a.repositoryId||u.workspace&&u.workspace.id!==i.workspaceId||u.source&&u.source.sha256!==c.manifest.sha256)throw new Error("Canary's answer does not match the repository and source that were uploaded. Run canary setup again.");return oy(e,{jobId:u.jobId,recipeHash:l,workspace:u.workspace??a.workspace,source:c.manifest,sourceUploadId:d.uploadId,scope:{apiUrl:i.apiUrl,userId:i.userId,workspaceId:i.workspaceId,repositoryId:a.repositoryId}}),ns(c.manifest,i,a.repositoryId,{requestKey:`setup:${l}`,uploadId:d.uploadId}),u.jobId}finally{await c.dispose()}}async function CI(e,t,n){let r=Q();if(!r){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}Jr();let s=Ls(e);s?.scope&&await cy(e,r,s,n);let o=s?.jobId??null;if(o){n.display?.update("submitting","Checking your saved verification job.");let a=null,c=!1,l=Date.now()+3e4;for(;;)try{if(a=await W(`/api/v1/cli/verify/${o}`,{token:r,baseUrl:n.context?.apiUrl}),!a||!sy.has(a.status))throw new Error("Saved verification returned an unrecognized state. Run canary setup again to retry.");break}catch(d){if(d instanceof L&&d.status===0){if(Date.now()<l){n.display?.update("retrying","Cloud service unreachable. Checking your saved job before continuing."),await Or(Er);continue}c=!0}else if(!(d instanceof L&&d.status===404))throw d;break}if(c){t?console.log(JSON.stringify({ok:!1,error:"unreachable",jobId:o})):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(a){if(a.status==="pending"||a.status==="running"||a.status==="needs_input"){n.display?n.display.update(a.status==="needs_input"?"answering":a.status,"Resuming your saved verification job."):t||console.log(`Resuming verify job ${o} \u2026`),await Oi(e,o,r,t,n);return}if(a.status==="green"||a.status==="red"||a.status==="error"){let d=!1;if(s?.recipeHash)try{d=bn(Bt(e))!==s.recipeHash}catch{d=!0}t?console.error(JSON.stringify({event:"previous_job_result",jobId:o,...d?{recipeChanged:!0}:{}})):n.display?n.warnings.push(d?"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 ${o} finished after the previous run stopped \u2014 applying its result now.
|
|
1905
|
+
`+(d?" .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 iy(e,a,t,n,{writeBack:!d,recipeChanged:d});return}}Ei(e),n.freshUpload=!0}let i=await ly(e,r,t,n);i!==null&&(n.display?n.display.update("pending","Recipe sent. Waiting for the cloud verifier."):t||console.log(`Shipped the recipe \u2014 verify job ${i}`),await Oi(e,i,r,t,n))}async function uy(e,t,n,r,s,o,i){if(r.secret&&s&&i.secrets.add(s),await W(`/api/v1/cli/verify/${t}/answer`,{method:"POST",token:n,baseUrl:i.context?.apiUrl,body:{questionId:r.questionId,value:s}}),r.secret){let a=Ls(e),c=!1;try{c=!!a?.recipeHash&&bn(Bt(e))===a.recipeHash}catch{}try{if(a?.recipeHash&&!c)throw new Error("Local recipe changed since submission; the answered value was not written over it.");Wa(e,[{name:r.key,value:s,class:"external_boot",why:r.prompt.slice(0,200)||"asked during cloud verification"}]),c&&a&&oy(e,{...a,recipeHash:bn(Bt(e))}),!o&&!i.display&&console.log(`Saved ${Me(i,r.key)} to .canary/env.json for future runs.`)}catch(l){let d=Me(i,`Could not save ${r.key} to .canary/env.json: ${l instanceof Error?l.message:String(l)}`);i.display?i.display.warn(d):console.error(`! ${d}`)}}}async function AI(e,t,n,r){let s=Q(),o=bI(e);if(!s||!o){n?console.log(JSON.stringify({ok:!1,error:o?"not_logged_in":"no_active_job",fix:o?"canary login":"canary setup"})):r.display?r.display.finish({status:"error",message:o?"You're not signed in.":"No active verification job.",next:o?"Run canary login first.":"Run canary setup first."}):console.error(o?"\u2717 Not logged in \u2014 run `canary login`.":"\u2717 No active verify job \u2014 run `canary setup` first."),process.exitCode=1;return}let i=Ls(e);i?.scope&&await cy(e,s,i,r);let a=await W(`/api/v1/cli/verify/${o}`,{token:s,baseUrl:r.context?.apiUrl});if(a.status!=="needs_input"||!a.needsInput){r.display?r.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 Oi(e,o,s,n,r);return}let c=a.needsInput;r.display?.update("answering","Sending your answer to the verifier."),await uy(e,o,s,c,t,n,r),r.display?r.display.update("answering","Answer received. Waiting for verification to continue."):n||console.log(`Answered ${Me(r,c.key)} \u2014 resuming \u2026`),await Oi(e,o,s,n,r,{questionId:c.questionId,until:Date.now()+3e4})}function dy(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();Ke({cwd:n});let r=t.json===!0;if(t.check){vI(n,r);return}let s={secrets:new Set(t.answer?[t.answer]:[]),warnings:[],baseRef:t.base};try{let o=V().team;s.display=ry({json:r,animation:t.animation!==!1,repository:gI(n),workspace:o?.name||(o?.id?"Saved workspace":"Select a workspace")}),t.answer!==void 0?await AI(n,t.answer,r,s):await CI(n,r,s)}catch(o){if(o instanceof ze||o instanceof We||o instanceof re){let i=Me(s,o.message),a="fix"in o&&o.fix?Me(s,o.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:o.code,message:i,...a?{fix:a}:{}})):s.display?s.display.finish({status:"error",message:i,next:a}):console.error(`\u2717 ${i}${a?`
|
|
1887
1906
|
Fix: ${a}`:""}`)}else if(o instanceof L){let i=Me(s,o.message),a="fix"in o&&o.fix?Me(s,o.fix):void 0;r?console.log(JSON.stringify({ok:!1,error:"api_error",status:o.status,message:i,...a?{fix:a}:{}})):s.display?s.display.finish({status:"error",message:i,next:a||"Run canary setup in this repository to resume."}):console.error(`\u2717 ${i}${a?`
|
|
1888
|
-
Fix: ${a}`:""}`)}else{let i=Me(s,o instanceof Error?o.message:String(o));r?console.log(JSON.stringify({ok:!1,error:"setup_error",message:i})):s.display?s.display.finish({status:"error",message:i,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${i}`)}process.exitCode=1}finally{s.display?.stop()}process.exitCode||await
|
|
1889
|
-
`,{flag:"w",mode:384})}catch{}}function
|
|
1907
|
+
Fix: ${a}`:""}`)}else{let i=Me(s,o instanceof Error?o.message:String(o));r?console.log(JSON.stringify({ok:!1,error:"setup_error",message:i})):s.display?s.display.finish({status:"error",message:i,next:"Run canary setup in this repository to resume."}):console.error(`\u2717 ${i}`)}process.exitCode=1}finally{s.display?.stop()}process.exitCode||await ls({json:r})})}Jt();w();ee();nt();import{lstatSync as II,mkdirSync as RI,readFileSync as hy,writeFileSync as fy}from"node:fs";import{join as Hl}from"node:path";var TI=5e3,EI=/^[a-z0-9][a-z0-9-]{0,39}$/,OI=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,$I="npm i -g @runcanary/cli@latest --prefer-online";function gy(e){let t=Hl(K(),"skills");return{dir:t,body:Hl(t,`${e}.md`),meta:Hl(t,`${e}.json`)}}function NI(e){let t=gy(e);try{let n=JSON.parse(hy(t.meta,"utf8"));return{body:hy(t.body,"utf8"),meta:n}}catch{return null}}function Fs(e){try{return II(e).isSymbolicLink()}catch{return!1}}function _I(e,t){let n=gy(e);try{if(Fs(K())||Fs(n.dir)||Fs(n.body)||Fs(n.meta)||(RI(n.dir,{recursive:!0,mode:448}),Fs(n.dir)))return;fy(n.body,t.body,{flag:"w",mode:384}),fy(n.meta,JSON.stringify(t.meta,null,2)+`
|
|
1908
|
+
`,{flag:"w",mode:384})}catch{}}function py(e){return e instanceof Error?e.message:String(e)}async function jI(e,t){let n;try{n=await fetch(e,{headers:{...Wt(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${t}`},signal:AbortSignal.timeout(TI)})}catch(r){return{kind:"failed",reason:py(r)}}if(n.status===404)return{kind:"missing"};if(!n.ok){let r=(await n.text().catch(()=>"")).trim().slice(0,200);return{kind:"failed",reason:`HTTP ${n.status}${r?`: ${r}`:""}`}}try{return{kind:"ok",body:await n.text(),contentVersion:n.headers.get("x-canary-skills-version")??void 0}}catch(r){return{kind:"failed",reason:`response body interrupted: ${py(r)}`}}}async function Gl(e){let t=await jI(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 _I(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=NI(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 r=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 ${r} \u2014 retry when the server is reachable`}}}}function PI(e,t){let n=o=>o.replace(/^v/,"").split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),r=n(e),s=n(t);for(let o=0;o<3;o++){let i=(r[o]??0)-(s[o]??0);if(i!==0)return i<0?-1:1}return 0}function MI(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 my(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 $r(e,t,n={}){if(!e.ok)return t?{stream:"stdout",text:JSON.stringify({ok:!1,error:e.error,...n})+`
|
|
1890
1909
|
`,exit:1}:{stream:"stderr",text:`\u2717 ${e.error}
|
|
1891
1910
|
`,exit:1};if(t){let r={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(r)+`
|
|
1892
|
-
`,exit:0}}return{stream:"stdout",text:`${
|
|
1911
|
+
`,exit:0}}return{stream:"stdout",text:`${my(e)}
|
|
1893
1912
|
|
|
1894
1913
|
${e.body}${e.body.endsWith(`
|
|
1895
1914
|
`)?"":`
|
|
1896
|
-
`}`,exit:0}}function Ds(e){(e.stream==="stdout"?process.stdout:process.stderr).write(e.text),process.exit(e.exit)}function
|
|
1897
|
-
`,exit:0}}function
|
|
1898
|
-
Ask Canary anything, in your own words: canary "find issues in billing" (or on stdin: canary -)`);var
|
|
1915
|
+
`}`,exit:0}}function Ds(e){(e.stream==="stdout"?process.stdout:process.stderr).write(e.text),process.exit(e.exit)}function LI(e,t,n={}){if(!e.ok||t){let r=$r(e,t,n);return r.stream==="stdout"?{stdout:r.text,stderr:"",exit:r.exit}:{stdout:"",stderr:r.text,exit:r.exit}}return{stdout:e.body,stderr:`${my(e)}
|
|
1916
|
+
`,exit:0}}function $i(){return ue().replace(/\/+$/,"")}function yy(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 Gl({key:"index",url:`${$i()}/llms.txt`,cliVersion:e.version()??"0.0.0",notFound:`this Canary server (${$i()}) does not publish skills yet`});Ds($r(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 r=!!n.json;EI.test(t)||Ds($r({ok:!1,error:`invalid operation name "${t.slice(0,60)}" \u2014 run \`canary skills\` to list the operations`},r));let s=e.version()??"0.0.0";if(n.asset!==void 0){OI.test(n.asset)||Ds($r({ok:!1,error:`invalid asset name "${n.asset.slice(0,80)}" \u2014 assets are lowercase file names ending in .html, .json, .md or .txt`},r));let i=await Gl({key:`${t}--${n.asset}`,url:`${$i()}/skills/${t}/${n.asset}`,cliVersion:s,notFound:`no such asset "${n.asset}" for "${t}" \u2014 run \`canary skill ${t}\` to see which files it publishes`}),a=LI(i,r,{name:t,asset:n.asset});a.stderr&&process.stderr.write(a.stderr);let c=()=>process.exit(a.exit);a.stdout?process.stdout.write(a.stdout,c):c()}let o=await Gl({key:t,url:`${$i()}/skills/${t}.md`,cliVersion:s,notFound:`no such operation "${t}" \u2014 run \`canary skills\` to list the operations`});if(o.ok){let i=MI(o.body);if(i&&s!=="0.0.0-dev"&&PI(s,i)<0){let a=`"${t}" needs Canary CLI ${i} or newer (you have ${s}). Update: ${$I}`,c=$r({ok:!1,error:a},r,{needsCli:i,cliVersion:s});Ds({...c,exit:2})}}Ds($r(o,r,{name:t}))})}w();fe();ee();In();var FI=3e3;function DI(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 wy(e){e.command("whoami").description("Show the currently authenticated user").option("--json","output machine-readable JSON").action(async t=>{let n=t.json===!0,r=Q();if(!r){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 s=V().team,o=s?.id&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.id)?s:void 0,i=await W(`/api/v1/cli/auth/whoami${o?`?workspaceId=${encodeURIComponent(o.id)}`:""}`,{token:r}),a=o?{id:o.id,name:o.name??i.team.name}:void 0,c=bc(),l=c&&a?await $o({token:r,apiUrl:ue().replace(/\/+$/,""),userId:i.user.id},c,a.id,AbortSignal.timeout(FI)):void 0,d=yc();if(n)console.log(JSON.stringify({ok:!0,user:i.user,team:i.team,workspace:a,...i.usage?{usage:i.usage}:{},...c?{repository:{name:c,...l?.state?{state:l.state}:{}}}:{},...d.length?{pushCheck:{pending:d}}:{}}));else{console.log(`${i.user.email} (${a?.name??"No workspace selected"})`),i.usage&&console.log(DI(i.usage)),c&&(console.log(jo(c)),console.log(Rn));for(let u of d)console.log(`Push check on ${u.label}: ${u.why} Run \`${u.command}\` in a terminal. ${u.after}`)}}catch(s){let o=s instanceof L&&s.status===401,i=o?"invalid_token":s instanceof Error?s.message:String(s);n?console.log(JSON.stringify({ok:!1,error:i})):console.error(o?"Your CLI session is no longer valid. Run `canary login`.":`Error: ${i}`),process.exitCode=1}})}w();fe();ee();Fe();async function vy(){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 Nr(e,t,n,r={}){e?console.log(JSON.stringify({ok:!1,error:t,message:n,...r})):console.error(n),process.exitCode=1}function by(e,t){if(t instanceof L&&t.status===401){Nr(e,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}Nr(e,"workspace_error",t instanceof Error?t.message:String(t))}async function WI(e){let t=await vy(),n=V().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 r=String(t.length).length;t.forEach((s,o)=>{let i=s.id===n?"*":" ",a=String(o+1).padStart(r," ");console.log(`${i} ${a} ${s.name}`)})}function ky(e,t){if(!Ne(n=>({...n,team:{id:e.id,name:e.name}}))){Nr(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}ho(),console.log(t?JSON.stringify({ok:!0,workspace:{id:e.id,name:e.name}}):`Switched to ${e.name}.`)}async function BI(e,t){let n=await vy(),r=e.trim();if(/^\d+$/.test(r)){let o=Number(r);if(o<1||o>n.length){Nr(t,"workspace_not_found",`No workspace #${o} \u2014 you have ${n.length}. Run: canary workspace list`,{available:n.map(i=>({id:i.id,name:i.name})),fix:"canary workspace list"});return}ky(n[o-1],t);return}let s=n.filter(o=>o.id===r||o.name.toLowerCase()===r.toLowerCase());if(s.length===0){Nr(t,"workspace_not_found",`No workspace matching "${e}".`,{available:n.map(o=>({id:o.id,name:o.name})),fix:"canary workspace list"});return}if(s.length>1){Nr(t,"workspace_ambiguous",`"${e}" matches multiple workspaces \u2014 use the id.`,{matches:s.map(o=>({id:o.id,name:o.name})),fix:`canary workspace use ${s[0].id}`});return}ky(s[0],t)}function UI(e){let t=V().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 xy(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 r=n.json===!0;try{await WI(r)}catch(s){by(r,s)}}),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,r)=>{let s=r.json===!0;try{await BI(n,s)}catch(o){by(s,o)}}),t.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(n=>UI(n.json===!0))}Fe();mn();var Se=new ou;Se.name("canary").description("Canary \u2014 break the code your AI writes.").version(wt);var Cy=process.argv[2]==="hook"||process.argv[2]==="jobs"||process.argv[2]==="wait";Cy||md();Cy||fo();lf(Se);wy(Se);_m(Se);yy(Se);xy(Se);dy(Se);Fh(Se);ey(Se);Ym(Se);kf(Se);gm(Se);bf(Se);wc(Se);Nm(Se);Se.addHelpText("after",`
|
|
1917
|
+
Ask Canary anything, in your own words: canary "find issues in billing" (or on stdin: canary -)`);var qI=new Set(["help",...Se.commands.flatMap(e=>[e.name(),...e.aliases()])]),HI=new Set(["-h","--help",...Se.options.flatMap(e=>[e.short,e.long]).filter(e=>!!e)]),Sy=op(process.argv.slice(2),qI,HI);Cf()||(Sy?ap(process.cwd(),Sy):Se.parseAsync(process.argv)).catch(e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)});
|
|
1899
1918
|
/*! Bundled license information:
|
|
1900
1919
|
|
|
1901
1920
|
smol-toml/dist/error.js:
|