@runcanary/cli 0.1.16 → 0.1.17

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.
Files changed (2) hide show
  1. package/dist/canary.js +1199 -159
  2. 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 _y=Object.create;var Oi=Object.defineProperty;var $y=Object.getOwnPropertyDescriptor;var Iy=Object.getOwnPropertyNames;var Ay=Object.getPrototypeOf,Ry=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 X=(e,t)=>()=>(e&&(t=e(e=0)),t);var dn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ti=(e,t)=>{for(var n in t)Oi(e,n,{get:t[n],enumerable:!0})},Ey=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Iy(t))!Ry.call(e,s)&&s!==n&&Oi(e,s,{get:()=>t[s],enumerable:!(r=$y(t,s))||r.enumerable});return e};var Oy=(e,t,n)=>(n=e!=null?_y(Ay(e)):{},Ey(t||!e||!e.__esModule?Oi(n,"default",{value:e,enumerable:!0}):n,e));var E,w=X(()=>{E={".claude-plugin/marketplace.json":`{
4
+ var Ay=Object.create;var $i=Object.defineProperty;var Iy=Object.getOwnPropertyDescriptor;var Ry=Object.getOwnPropertyNames;var Ty=Object.getPrototypeOf,Ey=Object.prototype.hasOwnProperty;var _r=(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),Ni=(e,t)=>{for(var n in t)$i(e,n,{get:t[n],enumerable:!0})},Oy=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ry(t))!Ey.call(e,s)&&s!==n&&$i(e,s,{get:()=>t[s],enumerable:!(r=Iy(t,s))||r.enumerable});return e};var $y=(e,t,n)=>(n=e!=null?Ay(Ty(e)):{},Oy(t||!e||!e.__esModule?$i(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 _y=Object.create;var Oi=Object.defineProperty;var $y=Object.getOwnPropertyDe
15
15
  }
16
16
  `,"canary/.claude-plugin/plugin.json":`{
17
17
  "name": "canary",
18
- "version": "0.1.16",
18
+ "version": "0.1.17",
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",
@@ -123,7 +123,265 @@ What came back is not yours to write. Canary captures it: what every command you
123
123
  A request for more proof names what was missing. Give exactly that: part of the scenario run again, one full rerun, or, when an earlier command of yours already printed it, which command that was.
124
124
 
125
125
  On a re-check, fetch the earlier files with \`canary jobs earlier <job> <path>\` and read them before running anything. The earlier script was written for another copy and other ports, so make it this run's script: point it at your copy and your ports, within the Boundaries above. Keep the steps it reproduces the same, adapting them only where the code changed (a renamed endpoint, say), and say in the evidence what you changed and why.
126
+ `,"canary/hooks/card.ts":`/**
127
+ * Reads the cards Canary's server writes into a reply (services/backend/src/render/agent/words.ts: \`card\`, \`titleRow\`,
128
+ * \`stepper\`, \`inline\`) without changing a word: the skin only decides how they look.
129
+ */
130
+
131
+ export type Mark = '\u{1F535}' | '\u{1F534}' | '\u{1F7E2}' | '\u{1F7E1}' | '\u26AA'
132
+
133
+ /** One stage of the stepper: \u2713 done, \u25C9 now, \u25CB next, \u2298 can't happen. */
134
+ export interface Step {
135
+ mark: '\u2713' | '\u25C9' | '\u25CB' | '\u2298'
136
+ name: string
137
+ }
138
+
139
+ export interface Card {
140
+ mark: Mark
141
+ title: string
142
+ rows: string[]
143
+ /** The stepper, when the card's last row is one; it is then left out of \`rows\`. */
144
+ steps: Step[] | null
145
+ }
146
+
147
+ /** A reply in order: the agent's own text, and each card Canary sent with its markdown as written. */
148
+ export type Part = { kind: 'text'; text: string } | { kind: 'card'; card: Card; raw: string }
149
+
150
+ /** A run of a line's text with one style, its markdown markers gone and its escapes undone. */
151
+ export interface Run {
152
+ text: string
153
+ bold?: true
154
+ italic?: true
155
+ code?: true
156
+ }
157
+
158
+ const HEADER = /^\\|\\s*(\u{1F535}|\u{1F534}|\u{1F7E2}|\u{1F7E1}|\u26AA)\\s+\\*\\*Canary\\*\\*:?\\s*(.*?)\\s*\\|\\s*$/u
159
+ const DIVIDER = /^\\|\\s*:?-{3,}:?\\s*\\|\\s*$/
160
+ const ROW = /^\\|\\s*(.*?)\\s*\\|\\s*$/
161
+ const FENCE = /^\\s*(\`\`\`|~~~)/
162
+ const STEP = /^([\u2713\u25C9\u25CB\u2298]) (\\S.*)$/u
163
+ /** What \`inline\` escapes with a backslash. */
164
+ const ESCAPED = new Set(['\\\\', '\`', '*', '_', '[', ']', '<', '>', '|', '~'])
165
+
166
+ /** Splits a reply into its own text and Canary's cards; a card inside a code fence stays text. */
167
+ export function parts(text: string): Part[] {
168
+ const lines = text.split('\\n')
169
+ const out: Part[] = []
170
+ let held: string[] = []
171
+ let fenced = false
172
+ const flush = () => {
173
+ const kept = held.join('\\n').trim()
174
+ if (kept !== '') out.push({ kind: 'text', text: kept })
175
+ held = []
176
+ }
177
+ for (let i = 0; i < lines.length; i++) {
178
+ const line = lines[i]!
179
+ if (FENCE.test(line)) fenced = !fenced
180
+ const head = fenced ? null : HEADER.exec(line)
181
+ if (head === null || i + 1 >= lines.length || !DIVIDER.test(lines[i + 1]!)) {
182
+ held.push(line)
183
+ continue
184
+ }
185
+ flush()
186
+ const rows: string[] = []
187
+ let next = i + 2
188
+ for (; next < lines.length; next++) {
189
+ const row = ROW.exec(lines[next]!)
190
+ if (row === null) break
191
+ rows.push(row[1]!)
192
+ }
193
+ const steps = rows.length > 0 ? stepsOf(rows[rows.length - 1]!) : null
194
+ out.push({
195
+ kind: 'card',
196
+ card: { mark: head[1] as Mark, title: head[2]!, rows: steps === null ? rows : rows.slice(0, -1), steps },
197
+ raw: lines.slice(i, next).join('\\n'),
198
+ })
199
+ i = next - 1
200
+ }
201
+ flush()
202
+ return out
203
+ }
204
+
205
+ /** The stepper row, read mark by mark; null for any other row. */
206
+ export function stepsOf(row: string): Step[] | null {
207
+ const steps = row.split(' \xB7 ').map(part => STEP.exec(part))
208
+ if (steps.length < 2 || steps.some(step => step === null)) return null
209
+ return steps.map(step => ({ mark: step![1] as Step['mark'], name: step![2]! }))
210
+ }
211
+
212
+ /** A line's runs: \`**bold**\`, \`*italic*\` and \`\` \`code\` \`\`, with the server's backslash escapes undone. */
213
+ export function runs(line: string): Run[] {
214
+ const out: Run[] = []
215
+ let text = ''
216
+ let bold = false
217
+ let italic = false
218
+ const push = (run: Run) => {
219
+ const last = out[out.length - 1]
220
+ if (last !== undefined && last.bold === run.bold && last.italic === run.italic && last.code === run.code) last.text += run.text
221
+ else out.push(run)
222
+ }
223
+ const flush = () => {
224
+ if (text !== '') push({ text, ...(bold ? { bold: true } : {}), ...(italic ? { italic: true } : {}) })
225
+ text = ''
226
+ }
227
+ for (let i = 0; i < line.length; i++) {
228
+ const char = line[i]!
229
+ if (char === '\\\\' && i + 1 < line.length && ESCAPED.has(line[i + 1]!)) {
230
+ text += line[++i]
231
+ } else if (line.startsWith('**', i)) {
232
+ flush()
233
+ bold = !bold
234
+ i++
235
+ } else if (char === '*') {
236
+ flush()
237
+ italic = !italic
238
+ } else if (char === '\`' && line.indexOf('\`', i + 1) > i) {
239
+ flush()
240
+ const end = line.indexOf('\`', i + 1)
241
+ push({ text: line.slice(i + 1, end), code: true })
242
+ i = end
243
+ } else {
244
+ text += char
245
+ }
246
+ }
247
+ flush()
248
+ return out
249
+ }
250
+
251
+ /** A line's words as a person reads them. */
252
+ export const wordsOf = (line: string): string => runs(line).map(run => run.text).join('')
253
+ `,"canary/hooks/fonts.LICENSE.txt":`The report card's fonts (hooks/fonts.ts) are cut from these four, each licensed under the SIL Open Font License,
254
+ Version 1.1, copied below:
255
+
256
+ Archivo, as CanarySans: Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo)
257
+ Archivo Black, as CanaryDisplay: Copyright 2017 The Archivo Black Project Authors (https://github.com/Omnibus-Type/ArchivoBlack)
258
+ IBM Plex Mono, as CanaryMono: Copyright \xA9 2017 IBM Corp. with Reserved Font Name "Plex"
259
+ Caveat, as CanaryPen: Copyright 2014 The Caveat Project Authors (https://github.com/googlefonts/caveat)
260
+
261
+ Each is a Modified Version, cut to the characters the card draws, and carries none of the original font names: the card
262
+ names them CanarySans, CanaryDisplay, CanaryMono and CanaryPen.
263
+
264
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
265
+ This license is copied below, and is also available with a FAQ at:
266
+ http://scripts.sil.org/OFL
267
+
268
+
269
+ -----------------------------------------------------------
270
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
271
+ -----------------------------------------------------------
272
+
273
+ PREAMBLE
274
+ The goals of the Open Font License (OFL) are to stimulate worldwide
275
+ development of collaborative font projects, to support the font creation
276
+ efforts of academic and linguistic communities, and to provide a free and
277
+ open framework in which fonts may be shared and improved in partnership
278
+ with others.
279
+
280
+ The OFL allows the licensed fonts to be used, studied, modified and
281
+ redistributed freely as long as they are not sold by themselves. The
282
+ fonts, including any derivative works, can be bundled, embedded,
283
+ redistributed and/or sold with any software provided that any reserved
284
+ names are not used by derivative works. The fonts and derivatives,
285
+ however, cannot be released under any other type of license. The
286
+ requirement for fonts to remain under this license does not apply
287
+ to any document created using the fonts or their derivatives.
288
+
289
+ DEFINITIONS
290
+ "Font Software" refers to the set of files released by the Copyright
291
+ Holder(s) under this license and clearly marked as such. This may
292
+ include source files, build scripts and documentation.
293
+
294
+ "Reserved Font Name" refers to any names specified as such after the
295
+ copyright statement(s).
296
+
297
+ "Original Version" refers to the collection of Font Software components as
298
+ distributed by the Copyright Holder(s).
299
+
300
+ "Modified Version" refers to any derivative made by adding to, deleting,
301
+ or substituting -- in part or in whole -- any of the components of the
302
+ Original Version, by changing formats or by porting the Font Software to a
303
+ new environment.
304
+
305
+ "Author" refers to any designer, engineer, programmer, technical
306
+ writer or other person who contributed to the Font Software.
307
+
308
+ PERMISSION & CONDITIONS
309
+ Permission is hereby granted, free of charge, to any person obtaining
310
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
311
+ redistribute, and sell modified and unmodified copies of the Font
312
+ Software, subject to the following conditions:
313
+
314
+ 1) Neither the Font Software nor any of its individual components,
315
+ in Original or Modified Versions, may be sold by itself.
316
+
317
+ 2) Original or Modified Versions of the Font Software may be bundled,
318
+ redistributed and/or sold with any software, provided that each copy
319
+ contains the above copyright notice and this license. These can be
320
+ included either as stand-alone text files, human-readable headers or
321
+ in the appropriate machine-readable metadata fields within text or
322
+ binary files as long as those fields can be easily viewed by the user.
323
+
324
+ 3) No Modified Version of the Font Software may use the Reserved Font
325
+ Name(s) unless explicit written permission is granted by the corresponding
326
+ Copyright Holder. This restriction only applies to the primary font name as
327
+ presented to the users.
328
+
329
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
330
+ Software shall not be used to promote, endorse or advertise any
331
+ Modified Version, except to acknowledge the contribution(s) of the
332
+ Copyright Holder(s) and the Author(s) or with their explicit written
333
+ permission.
334
+
335
+ 5) The Font Software, modified or unmodified, in part or in whole,
336
+ must be distributed entirely under this license, and must not be
337
+ distributed under any other license. The requirement for fonts to
338
+ remain under this license does not apply to any document created
339
+ using the Font Software.
340
+
341
+ TERMINATION
342
+ This license becomes null and void if any of the above conditions are
343
+ not met.
344
+
345
+ DISCLAIMER
346
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
347
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
348
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
349
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
350
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
351
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
352
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
353
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
354
+ OTHER DEALINGS IN THE FONT SOFTWARE.
355
+ `,"canary/hooks/fonts.ts":`// The landing page's own faces (Archivo, Archivo Black, IBM Plex Mono, Caveat), cut to the characters cards use, as
356
+ // woff2 in base64, with each glyph's advance and pair kerning so a card can be measured the way it is laid out.
357
+ // Generated from the fonts the landing page ships.
358
+ //
359
+ // Archivo: Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo)
360
+ // Archivo Black: Copyright 2017 The Archivo Black Project Authors (https://github.com/Omnibus-Type/ArchivoBlack)
361
+ // IBM Plex Mono: Copyright \xA9 2017 IBM Corp. with Reserved Font Name "Plex"
362
+ // Caveat: Copyright 2014 The Caveat Project Authors (https://github.com/googlefonts/caveat)
363
+ // Each is licensed under the SIL Open Font License, Version 1.1, in fonts.LICENSE.txt beside this file. These cuts are
364
+ // Modified Versions and go by CanarySans, CanaryDisplay, CanaryMono and CanaryPen, never by a Reserved Font Name.
365
+
366
+ export const FONTS = {
367
+ "display": "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",
368
+ "sans": "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",
369
+ "sansBold": "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",
370
+ "mono": "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",
371
+ "pen": "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"
372
+ } as const
373
+
374
+ export interface Metrics {
375
+ upm: number
376
+ ascent: number
377
+ descent: number
378
+ adv: Record<string, number>
379
+ kern: Record<string, number>
380
+ }
381
+
382
+ export const METRICS: Record<keyof typeof FONTS, Metrics> = {"display": {"upm": 1000, "ascent": 878, "descent": -210, "adv": {" ": 333, "!": 333, "\\"": 500, "#": 660, "$": 667, "%": 1000, "&": 889, "'": 278, "(": 389, ")": 389, "*": 556, "+": 660, ",": 333, "-": 333, ".": 333, "/": 278, "0": 667, "1": 667, "2": 667, "3": 667, "4": 667, "5": 667, "6": 667, "7": 667, "8": 667, "9": 667, ":": 333, ";": 333, "<": 660, "=": 660, ">": 660, "?": 611, "@": 740, "A": 778, "B": 778, "C": 778, "D": 778, "E": 722, "F": 667, "G": 833, "H": 833, "I": 389, "J": 667, "K": 833, "L": 667, "M": 944, "N": 833, "O": 833, "P": 722, "Q": 833, "R": 778, "S": 722, "T": 722, "U": 833, "V": 778, "W": 1000, "X": 778, "Y": 778, "Z": 722, "[": 389, "\\\\": 278, "]": 389, "^": 660, "_": 500, "\`": 333, "a": 667, "b": 667, "c": 667, "d": 667, "e": 667, "f": 389, "g": 667, "h": 667, "i": 333, "j": 333, "k": 667, "l": 333, "m": 1000, "n": 667, "o": 667, "p": 667, "q": 667, "r": 444, "s": 611, "t": 444, "u": 667, "v": 611, "w": 944, "x": 667, "y": 611, "z": 556, "{": 389, "|": 278, "}": 389, "~": 660, "\xB7": 333, "\xD7": 660, "\u2013": 500, "\u2014": 1000, "\u2018": 278, "\u2019": 278, "\u201C": 500, "\u201D": 500, "\u2022": 500, "\u2026": 1000}, "kern": {"AC": -18, "AG": -18, "AO": -18, "AQ": -19, "AT": -69, "AU": -34, "AV": -55, "AW": 8, "AY": -85, "Ap": 17, "Au": -10, "Av": -17, "A\u201D": -68, "A\u2019": -67, "BA": -17, "BU": -26, "B,": 25, "B.": 16, "C,": 25, "C.": 17, "DA": -43, "DV": -34, "DW": 17, "DY": -34, "D,": -10, "D.": -17, "FA": -94, "Fa": -26, "Fe": -34, "Fl": 8, "Fo": -34, "Fr": -34, "F,": -146, "F.": -153, "G,": 16, "G.": 10, "JA": -26, "Ja": -17, "Je": -26, "Jo": -26, "Ju": -26, "Jy": -17, "J,": -18, "J.": -26, "KC": -34, "KG": -34, "KO": -34, "Ke": -34, "Ko": -34, "Ku": -26, "Kv": -17, "Ky": -17, "LC": -17, "LG": -17, "LO": -17, "LT": -51, "LU": -26, "LV": -51, "LW": -17, "LY": -77, "Lw": -17, "Ly": -10, "L\u201D": -51, "L\u2019": -51, "NA": -10, "OA": -34, "OT": -26, "OV": -43, "OW": -17, "OX": -52, "OY": -68, "O,": -17, "O.": -26, "PA": -85, "Pa": -17, "Pe": -26, "Po": -26, "P,": -180, "P.": -188, "QA": 17, "QT": -18, "QV": -43, "QY": -51, "Q,": 33, "Q.": 17, "RC": -18, "RG": -18, "RO": -17, "RQ": -20, "RT": -9, "RU": -17, "RV": -17, "RY": -43, "Re": -25, "Ro": -26, "Ru": -17, "Rw": 17, "TA": -68, "TC": -34, "TG": -34, "TO": -34, "TQ": -34, "Ta": -51, "Tc": -60, "Te": -60, "Th": 27, "Tl": 19, "Tm": -43, "To": -68, "Tr": -43, "Ts": -68, "Tu": -43, "Tw": -10, "Ty": -17, "Tz": -34, "T:": -34, "T,": -146, "T.": -153, "T;": -34, "T-": -68, "UA": -34, "U,": -26, "U.": -34, "VA": -57, "VC": -34, "VG": -34, "VO": -34, "VQ": -34, "Va": -43, "Ve": -51, "Vi": 16, "Vo": -51, "Vr": -34, "Vu": -34, "V:": -26, "V,": -120, "V.": -128, "V;": -26, "V-": -43, "WC": -17, "WG": -17, "WO": -17, "Wa": -17, "Wd": -26, "We": -26, "Wh": 33, "Wi": 33, "Wo": -26, "Wu": -17, "W,": -43, "W.": -52, "W-": -10, "XC": -34, "XG": -34, "XO": -34, "YA": -94, "YC": -60, "YG": -60, "YO": -60, "YS": -43, "Ya": -86, "Yd": -94, "Ye": -94, "Yo": -85, "Yp": -51, "Yq": -85, "Yu": -60, "Yv": -26, "Y:": -60, "Y,": -162, "Y.": -170, "Y;": -60, "Y-": -86, "ab": 10, "ag": 16, "ap": 10, "at": -17, "av": -17, "bb": 10, "bv": -26, "ch": -17, "ck": -17, "cl": -26, "cy": -17, "dd": 10, "dw": 10, "eb": -10, "eg": 25, "ev": -26, "ex": -26, "f ": 58, "fa": -10, "fe": -17, "ff": 25, "fk": 10, "fo": -17, "f,": -52, "f!": 83, "f.": -60, "f?": 83, "f\u201D": 83, "f\u2019": 83, "gg": 10, "gl": 10, "gr": 18, "gy": 17, "ke": -34, "ko": -34, "ky": 17, "ly": 17, "nv": -27, "n\u2019": -17, "ov": -34, "ow": -18, "ox": -35, "oy": -17, "oz": 17, "o,": -10, "o.": -17, "pw": -26, "py": -17, "p,": -10, "p.": -17, "ra": 17, "rc": 17, "rd": 25, "re": 16, "rg": 25, "rj": 42, "rk": 33, "rl": 33, "rm": 50, "rn": 50, "ro": 16, "rp": 42, "rq": 25, "rr": 42, "rs": 25, "rt": 50, "ru": 33, "rv": 58, "ry": 58, "r:": 42, "r,": -68, "r.": -77, "r;": 42, "sw": -26, "vc": -26, "vd": -17, "ve": -26, "vo": -26, "vq": -25, "v,": -85, "v.": -93, "wa": -11, "wc": -10, "wd": -11, "we": -11, "wh": 17, "wo": -17, "wq": -17, "w,": -77, "w.": -85, "xc": -17, "xd": -17, "xe": -17, "xo": -17, "ya": -17, "yc": -17, "yd": -17, "ye": -17, "yo": -17, "y,": -85, "y.": -94, "zc": -10, "zd": -10, "ze": -10, "zo": -10, "\u201CA": -68, "\u2018A": -60, "\u2019d": -17, "\u2019l": 17, "\u2019r": 10, "\u2019s": -26, "\u2019v": 17}}, "sans": {"upm": 1000, "ascent": 878, "descent": -210, "adv": {" ": 209, "!": 273, "\\"": 374, "#": 582, "$": 510, "%": 950, "&": 692, "'": 209, "(": 355, ")": 355, "*": 407, "+": 625, ",": 277, "-": 333, ".": 277, "/": 294, "0": 573, "1": 521, "2": 567, "3": 573, "4": 555, "5": 571, "6": 573, "7": 553, "8": 574, "9": 573, ":": 296, ";": 296, "<": 625, "=": 625, ">": 625, "?": 578, "@": 1005, "A": 682, "B": 698, "C": 728, "D": 734, "E": 677, "F": 612, "G": 796, "H": 736, "I": 267, "J": 559, "K": 662, "L": 536, "M": 847, "N": 736, "O": 788, "P": 665, "Q": 788, "R": 727, "S": 673, "T": 606, "U": 731, "V": 648, "W": 924, "X": 680, "Y": 655, "Z": 635, "[": 296, "\\\\": 294, "]": 296, "^": 625, "_": 485, "\`": 187, "a": 545, "b": 567, "c": 519, "d": 567, "e": 548, "f": 280, "g": 556, "h": 563, "i": 225, "j": 223, "k": 514, "l": 225, "m": 860, "n": 563, "o": 570, "p": 567, "q": 567, "r": 332, "s": 510, "t": 297, "u": 562, "v": 504, "w": 723, "x": 513, "y": 504, "z": 498, "{": 353, "|": 245, "}": 353, "~": 625, "\xB7": 333, "\xD7": 625, "\u2013": 500, "\u2014": 1000, "\u2018": 239, "\u2019": 239, "\u201C": 394, "\u201D": 394, "\u2022": 391, "\u2026": 844}, "kern": {"A?": -30, "A/": 30, "A\u201C": -105, "A\u201D": -105, "F ": -35, "K/": 30, "K\u201C": -37, "K ": -36, "L?": -50, "L/": 30, "L\u201C": -140, "L\u201D": -100, "L\u2019": -100, "P ": -45, "T/": -40, "X\u201C": -30, "Y/": -40, "Y\u201C": -25, "Y ": -45, "f?": 20, "f)": 21, "f}": 21, "f\u2019": 20, "k ": -35, "r\u2019": 20, "r ": -20, "t)": 3, "7)": -10, "7}": -10, "/J": -20, "\\\\A": 20, "\\\\Y": -40, "\\\\7": -20, "\\\\]": -20, "\u201CA": -105, "\u201CJ": -100, "\u201D.": -50, "\u201D,": -50, "\u201D\u2026": -50, "\u2019A": -95, "\u2019c": -60, "\u2019d": -60, "\u2019e": -60, "\u2019g": -80, "\u2019m": -20, "\u2019n": -20, "\u2019o": -60, "\u2019p": -20, "\u2019q": -60, "\u2019r": -20, "\u2019s": -60, "\u2019z": -40, " Y": -45, "A\\"": -95, "A'": -95, "A*": -80, "AC": -13, "AG": -13, "AO": -13, "AQ": -13, "AT": -87, "AU": -15, "AV": -28, "AW": -28, "AX": -23, "AY": -75, "Au": -5, "Av": -15, "Aw": -15, "Ax": -10, "Ay": -20, "BV": -10, "BW": -10, "BX": -10, "BY": -13, "CT": -20, "CV": -3, "CW": -3, "CX": -5, "CY": -5, "D\\"": -5, "D'": -5, "D,": -35, "D.": -35, "D:": -10, "D;": -10, "DA": -13, "DT": -23, "DV": -13, "DW": -13, "DX": -13, "DY": -13, "DZ": -10, "D\u2026": -35, "EJ": -20, "F,": -60, "F-": -20, "F.": -60, "F:": -15, "F;": -15, "FA": -55, "FJ": -75, "FX": -25, "FY": -25, "FZ": -45, "Fa": -25, "Fc": -25, "Fd": -25, "Fe": -25, "Fo": -25, "Fq": -25, "F\u2013": -20, "F\u2014": -20, "F\u2026": -60, "GV": -5, "GW": -5, "K\\"": -15, "K'": -15, "K*": -21, "K-": -52, "KA": -50, "KC": -34, "KG": -34, "KJ": -22, "KO": -34, "KQ": -34, "KT": -30, "KV": -40, "KW": -40, "KX": -20, "KY": -40, "KZ": -10, "Ka": -22, "Kc": -22, "Kd": -22, "Ke": -22, "Ko": -22, "Kq": -22, "Ku": -22, "Kv": -37, "Kw": -37, "Ky": -37, "K\xB7": -66, "K\u2013": -52, "K\u2014": -52, "K\u2022": -66, "L\\"": -100, "L'": -100, "L*": -90, "L-": -80, "LC": -30, "LG": -30, "LJ": -20, "LO": -30, "LQ": -30, "LT": -81, "LU": -35, "LV": -95, "LW": -95, "LX": -129, "LY": -118, "LZ": -20, "Lv": -40, "Lw": -40, "Lx": -20, "Ly": -40, "L\xB7": -150, "L\u2013": -80, "L\u2014": -80, "L\u2022": -150, "O\\"": -5, "O'": -5, "O,": -35, "O.": -35, "O:": -10, "O;": -10, "OA": -13, "OT": -23, "OV": -13, "OW": -13, "OX": -13, "OY": -13, "OZ": -10, "O\u2026": -35, "P,": -90, "P.": -90, "PA": -50, "PJ": -70, "PT": -20, "PX": -25, "PY": -15, "PZ": -30, "Pa": -10, "Pc": -10, "Pd": -10, "Pe": -10, "Po": -10, "Pq": -10, "P\u2026": -90, "Q\\"": -5, "Q'": -5, "Q,": -35, "Q.": -35, "Q:": -10, "Q;": -10, "QA": -13, "QT": -23, "QV": -13, "QW": -13, "QX": -13, "QY": -13, "QZ": -10, "Q\u2026": -35, "RC": -14, "RG": -14, "RJ": -30, "RO": -14, "RQ": -14, "RT": -25, "RU": -17, "RV": -10, "RW": -10, "RX": -18, "RY": -22, "Ra": -10, "Rc": -10, "Rd": -10, "Re": -10, "Ro": -10, "Rq": -10, "Ru": -10, "Rv": -15, "Rw": -15, "Ry": -15, "SY": -31, "T,": -50, "T.": -50, "T:": -20, "T;": -20, "TA": -87, "TC": -23, "TG": -23, "TJ": -105, "TO": -23, "TQ": -23, "TX": -20, "TY": -20, "TZ": -20, "Ta": -80, "Tc": -80, "Td": -80, "Te": -80, "Tm": -70, "Tn": -70, "To": -80, "Tp": -70, "Tq": -80, "Tr": -70, "Ts": -80, "Tt": -40, "Tu": -70, "Tv": -35, "Tw": -35, "Tx": -35, "Ty": -35, "Tz": -35, "T\u2026": -50, "UA": -15, "V,": -141, "V-": -50, "V.": -141, "V:": -10, "V;": -10, "VA": -28, "VC": -13, "VG": -13, "VJ": -85, "VO": -13, "VQ": -13, "VX": -20, "VY": -20, "Va": -45, "Vc": -45, "Vd": -45, "Ve": -45, "Vm": -25, "Vn": -25, "Vo": -45, "Vp": -25, "Vq": -45, "Vr": -25, "Vs": -35, "Vu": -35, "Vv": -20, "Vw": -20, "Vx": -30, "Vy": -20, "Vz": -30, "V\u2013": -50, "V\u2014": -50, "V\u2026": -141, "W,": -141, "W-": -50, "W.": -141, "W:": -10, "W;": -10, "WA": -28, "WC": -13, "WG": -13, "WJ": -85, "WO": -13, "WQ": -13, "WX": -20, "WY": -20, "Wa": -45, "Wc": -45, "Wd": -45, "We": -45, "Wm": -25, "Wn": -25, "Wo": -45, "Wp": -25, "Wq": -45, "Wr": -25, "Ws": -35, "Wu": -35, "Wv": -20, "Ww": -20, "Wx": -30, "Wy": -20, "Wz": -30, "W\u2013": -50, "W\u2014": -50, "W\u2026": -141, "X-": -50, "XA": -23, "XC": -13, "XG": -13, "XO": -13, "XQ": -13, "XT": -20, "XV": -20, "XW": -20, "XY": -30, "XZ": -20, "Xa": -13, "Xc": -13, "Xd": -13, "Xe": -13, "Xo": -13, "Xq": -13, "Xs": -13, "Xt": -31, "Xu": -20, "Xv": -40, "Xw": -40, "Xx": -40, "Xy": -40, "Xz": -20, "X\xB7": -50, "X\u2013": -50, "X\u2014": -50, "X\u2022": -50, "Y,": -195, "Y-": -131, "Y.": -195, "Y:": -45, "Y;": -45, "YA": -75, "YC": -13, "YG": -13, "YJ": -130, "YO": -13, "YQ": -13, "YS": -31, "YT": -20, "YV": -20, "YW": -20, "YX": -30, "Ya": -95, "Yc": -95, "Yd": -95, "Ye": -95, "Yf": -51, "Yg": -90, "Ym": -55, "Yn": -55, "Yo": -95, "Yp": -55, "Yq": -95, "Yr": -55, "Ys": -81, "Yt": -35, "Yu": -61, "Yv": -45, "Yw": -45, "Yx": -55, "Yz": -63, "Y\xB7": -50, "Y\u2013": -131, "Y\u2014": -131, "Y\u2022": -50, "Y\u2026": -195, "Z-": -99, "ZC": -10, "ZG": -10, "ZO": -10, "ZQ": -10, "ZT": -20, "ZX": -20, "Z\u2013": -99, "Z\u2014": -99, "b\\"": -5, "b'": -5, "bv": -5, "bw": -5, "bx": -20, "by": -2, "bz": -20, "e\\"": -5, "e'": -5, "ex": -3, "f\\"": 15, "f'": 15, "f*": 10, "f,": -40, "f-": -10, "f.": -40, "f7": 21, "f:": -10, "f;": -10, "f]": 21, "fa": -5, "fc": -5, "fd": -5, "fe": -5, "fo": -5, "fq": -5, "f\u2013": -10, "f\u2014": -10, "f\u2026": -40, "k-": -50, "ka": -23, "kc": -33, "kd": -33, "ke": -33, "ko": -33, "kq": -33, "ks": -21, "kv": -20, "kw": -20, "kx": -35, "ky": -20, "kz": -20, "k\xB7": -60, "k\u2013": -50, "k\u2014": -50, "k\u2022": -60, "o\\"": -5, "o'": -5, "ov": -5, "ow": -5, "ox": -20, "oy": -2, "oz": -20, "p\\"": -5, "p'": -5, "pv": -5, "pw": -5, "px": -20, "py": -2, "pz": -20, "r,": -105, "r.": -105, "ra": -10, "rc": -10, "rd": -10, "re": -10, "ro": -10, "rq": -10, "r\u2026": -105, "sx": -15, "v,": -120, "v.": -120, "v:": -10, "v;": -10, "va": -10, "vc": -5, "vd": -5, "ve": -5, "vo": -5, "vq": -5, "v\u2026": -120, "w,": -120, "w.": -120, "w:": -10, "w;": -10, "wa": -10, "wc": -5, "wd": -5, "we": -5, "wo": -5, "wq": -5, "w\u2026": -120, "x-": -30, "xa": -20, "xc": -20, "xd": -20, "xe": -20, "xo": -20, "xq": -20, "x\u2013": -30, "x\u2014": -30, "y,": -120, "y.": -120, "y:": -10, "y;": -10, "ya": -10, "yc": -5, "yd": -5, "ye": -5, "yo": -5, "yq": -5, "y\u2026": -120, "za": -20, "zc": -20, "zd": -20, "ze": -20, "zo": -20, "zq": -20, "0\\"": 14, "0'": 14, "0-": 40, "0\u2013": 40, "0\u2014": 40, "1\\"": -8, "1'": -8, "1-": 40, "1\u2013": 40, "1\u2014": 40, "2-": 10, "2\u2013": 10, "2\u2014": 10, "3-": 40, "3\u2013": 40, "3\u2014": 40, "4-": 40, "4\u2013": 40, "4\u2014": 40, "5-": 40, "5\u2013": 40, "5\u2014": 40, "6-": 20, "6\u2013": 20, "6\u2014": 20, "7,": -120, "7-": -40, "7.": -120, "77": -10, "7]": -10, "7\u2013": -40, "7\u2014": -40, "7\u2026": -120, "8-": 30, "8\u2013": 30, "8\u2014": 30, "9-": 40, "9\u2013": 40, "9\u2014": 40, "\xB7X": -50, "\xB7Y": -50, "\u2022X": -50, "\u2022Y": -50, "-0": 40, "-1": 40, "-2": 40, "-3": 40, "-4": 40, "-5": 40, "-6": 40, "-8": 30, "-9": 20, "-V": -50, "-W": -50, "-X": -50, "-Y": -131, "-x": -30, "\u20130": 40, "\u20131": 40, "\u20132": 40, "\u20133": 40, "\u20134": 40, "\u20135": 40, "\u20136": 40, "\u20138": 30, "\u20139": 20, "\u2013V": -50, "\u2013W": -50, "\u2013X": -50, "\u2013Y": -131, "\u2013x": -30, "\u20140": 40, "\u20141": 40, "\u20142": 40, "\u20143": 40, "\u20144": 40, "\u20145": 40, "\u20146": 40, "\u20148": 30, "\u20149": 20, "\u2014V": -50, "\u2014W": -50, "\u2014X": -50, "\u2014Y": -131, "\u2014x": -30, "\\",": -50, "\\".": -50, "\\"4": -15, "\\"A": -95, "\\"J": -100, "\\"c": -5, "\\"d": -5, "\\"e": -5, "\\"o": -5, "\\"q": -5, "\\"\u2026": -50, "',": -50, "'.": -50, "'4": -15, "'A": -95, "'J": -100, "'c": -5, "'d": -5, "'e": -5, "'o": -5, "'q": -5, "'\u2026": -50}}, "sansBold": {"upm": 1000, "ascent": 878, "descent": -210, "adv": {" ": 200, "!": 292, "\\"": 444, "#": 583, "$": 541, "%": 966, "&": 729, "'": 246, "(": 357, ")": 357, "*": 407, "+": 636, ",": 300, "-": 333, ".": 300, "/": 298, "0": 575, "1": 576, "2": 576, "3": 576, "4": 577, "5": 575, "6": 576, "7": 576, "8": 576, "9": 575, ":": 336, ";": 336, "<": 636, "=": 636, ">": 636, "?": 613, "@": 998, "A": 709, "B": 706, "C": 721, "D": 728, "E": 672, "F": 609, "G": 794, "H": 732, "I": 282, "J": 585, "K": 695, "L": 570, "M": 844, "N": 732, "O": 782, "P": 670, "Q": 782, "R": 717, "S": 667, "T": 619, "U": 724, "V": 671, "W": 954, "X": 686, "Y": 677, "Z": 634, "[": 339, "\\\\": 298, "]": 339, "^": 636, "_": 507, "\`": 209, "a": 556, "b": 592, "c": 547, "d": 592, "e": 561, "f": 307, "g": 591, "h": 584, "i": 252, "j": 250, "k": 543, "l": 252, "m": 861, "n": 584, "o": 598, "p": 592, "q": 592, "r": 362, "s": 541, "t": 314, "u": 583, "v": 529, "w": 758, "x": 546, "y": 529, "z": 509, "{": 394, "|": 245, "}": 394, "~": 636, "\xB7": 333, "\xD7": 636, "\u2013": 500, "\u2014": 1000, "\u2018": 280, "\u2019": 280, "\u201C": 482, "\u201D": 482, "\u2022": 425, "\u2026": 965}, "kern": {"A?": -30, "A/": 30, "A\u201C": -100, "A\u201D": -100, "F ": -30, "K/": 30, "K\u201C": -60, "K ": -50, "L?": -50, "L/": 30, "L\u201C": -140, "L\u201D": -100, "L\u2019": -100, "P ": -50, "T/": -40, "X\u201C": -30, "Y/": -40, "Y\u201C": -30, "Y ": -50, "f?": 20, "f)": 30, "f}": 30, "f\u2019": 20, "k ": -30, "r\u2019": 20, "r ": -20, "t)": 5, "7)": -10, "7}": -10, "/J": -20, "\\\\A": 20, "\\\\Y": -40, "\\\\7": -20, "\\\\]": -20, "\u201CA": -100, "\u201CJ": -100, "\u201D.": -50, "\u201D,": -50, "\u201D\u2026": -50, "\u2019A": -100, "\u2019c": -60, "\u2019d": -60, "\u2019e": -60, "\u2019g": -80, "\u2019m": -20, "\u2019n": -20, "\u2019o": -60, "\u2019p": -20, "\u2019q": -60, "\u2019r": -20, "\u2019s": -60, "\u2019z": -40, " Y": -50, "A\\"": -100, "A'": -100, "A*": -80, "AC": -15, "AG": -15, "AO": -15, "AQ": -15, "AT": -85, "AU": -15, "AV": -35, "AW": -35, "AX": -25, "AY": -80, "Au": -10, "Av": -20, "Aw": -20, "Ax": -10, "Ay": -25, "BV": -10, "BW": -10, "BX": -10, "BY": -15, "CT": -20, "CV": -5, "CW": -5, "CX": -10, "CY": -10, "D\\"": -10, "D'": -10, "D,": -30, "D.": -30, "D:": -10, "D;": -10, "DA": -15, "DT": -25, "DV": -15, "DW": -15, "DX": -15, "DY": -15, "DZ": -10, "D\u2026": -30, "EJ": -20, "F,": -60, "F-": -20, "F.": -60, "F:": -10, "F;": -10, "FA": -55, "FJ": -80, "FX": -30, "FY": -30, "FZ": -40, "Fa": -30, "Fc": -30, "Fd": -30, "Fe": -30, "Fo": -30, "Fq": -30, "F\u2013": -20, "F\u2014": -20, "F\u2026": -60, "GV": -5, "GW": -5, "K\\"": -20, "K'": -20, "K*": -30, "K-": -70, "KA": -50, "KC": -55, "KG": -55, "KJ": -40, "KO": -55, "KQ": -55, "KT": -30, "KV": -70, "KW": -70, "KX": -20, "KY": -70, "KZ": -10, "Ka": -40, "Kc": -40, "Kd": -40, "Ke": -40, "Ko": -40, "Kq": -40, "Ku": -40, "Kv": -60, "Kw": -60, "Ky": -60, "K\xB7": -80, "K\u2013": -70, "K\u2014": -70, "K\u2022": -80, "L\\"": -100, "L'": -100, "L*": -90, "L-": -80, "LC": -30, "LG": -30, "LJ": -20, "LO": -30, "LQ": -30, "LT": -90, "LU": -35, "LV": -90, "LW": -90, "LX": -170, "LY": -125, "LZ": -20, "Lv": -40, "Lw": -40, "Lx": -20, "Ly": -40, "L\xB7": -150, "L\u2013": -80, "L\u2014": -80, "L\u2022": -150, "O\\"": -10, "O'": -10, "O,": -30, "O.": -30, "O:": -10, "O;": -10, "OA": -15, "OT": -25, "OV": -15, "OW": -15, "OX": -15, "OY": -15, "OZ": -10, "O\u2026": -30, "P,": -90, "P.": -90, "PA": -50, "PJ": -70, "PT": -20, "PX": -30, "PY": -20, "PZ": -30, "Pa": -10, "Pc": -10, "Pd": -10, "Pe": -10, "Po": -10, "Pq": -10, "P\u2026": -90, "Q\\"": -10, "Q'": -10, "Q,": -30, "Q.": -30, "Q:": -10, "Q;": -10, "QA": -15, "QT": -25, "QV": -15, "QW": -15, "QX": -15, "QY": -15, "QZ": -10, "Q\u2026": -30, "RC": -5, "RG": -5, "RJ": -30, "RO": -5, "RQ": -5, "RT": -20, "RU": -10, "RV": -10, "RW": -10, "RX": -20, "RY": -20, "Ra": -10, "Rc": -10, "Rd": -10, "Re": -10, "Ro": -10, "Rq": -10, "Ru": -10, "Rv": -10, "Rw": -10, "Ry": -10, "SY": -40, "T,": -50, "T.": -50, "T:": -20, "T;": -20, "TA": -85, "TC": -25, "TG": -25, "TJ": -110, "TO": -25, "TQ": -25, "TX": -20, "TY": -20, "TZ": -20, "Ta": -80, "Tc": -80, "Td": -80, "Te": -80, "Tm": -70, "Tn": -70, "To": -80, "Tp": -70, "Tq": -80, "Tr": -70, "Ts": -80, "Tt": -40, "Tu": -70, "Tv": -30, "Tw": -30, "Tx": -30, "Ty": -30, "Tz": -30, "T\u2026": -50, "UA": -15, "V,": -150, "V-": -50, "V.": -150, "V:": -10, "V;": -10, "VA": -35, "VC": -15, "VG": -15, "VJ": -90, "VO": -15, "VQ": -15, "VX": -20, "VY": -20, "Va": -50, "Vc": -50, "Vd": -50, "Ve": -50, "Vm": -20, "Vn": -20, "Vo": -50, "Vp": -20, "Vq": -50, "Vr": -20, "Vs": -40, "Vu": -40, "Vv": -20, "Vw": -20, "Vx": -30, "Vy": -20, "Vz": -30, "V\u2013": -50, "V\u2014": -50, "V\u2026": -150, "W,": -150, "W-": -50, "W.": -150, "W:": -10, "W;": -10, "WA": -35, "WC": -15, "WG": -15, "WJ": -90, "WO": -15, "WQ": -15, "WX": -20, "WY": -20, "Wa": -50, "Wc": -50, "Wd": -50, "We": -50, "Wm": -20, "Wn": -20, "Wo": -50, "Wp": -20, "Wq": -50, "Wr": -20, "Ws": -40, "Wu": -40, "Wv": -20, "Ww": -20, "Wx": -30, "Wy": -20, "Wz": -30, "W\u2013": -50, "W\u2014": -50, "W\u2026": -150, "X-": -50, "XA": -25, "XC": -15, "XG": -15, "XO": -15, "XQ": -15, "XT": -20, "XV": -20, "XW": -20, "XY": -30, "XZ": -20, "Xa": -15, "Xc": -15, "Xd": -15, "Xe": -15, "Xo": -15, "Xq": -15, "Xs": -15, "Xt": -40, "Xu": -20, "Xv": -40, "Xw": -40, "Xx": -40, "Xy": -40, "Xz": -20, "X\xB7": -50, "X\u2013": -50, "X\u2014": -50, "X\u2022": -50, "Y,": -200, "Y-": -140, "Y.": -200, "Y:": -50, "Y;": -50, "YA": -80, "YC": -15, "YG": -15, "YJ": -130, "YO": -15, "YQ": -15, "YS": -40, "YT": -20, "YV": -20, "YW": -20, "YX": -30, "Ya": -100, "Yc": -100, "Yd": -100, "Ye": -100, "Yf": -60, "Yg": -90, "Ym": -60, "Yn": -60, "Yo": -100, "Yp": -60, "Yq": -100, "Yr": -60, "Ys": -90, "Yt": -40, "Yu": -70, "Yv": -50, "Yw": -50, "Yx": -60, "Yz": -65, "Y\xB7": -50, "Y\u2013": -140, "Y\u2014": -140, "Y\u2022": -50, "Y\u2026": -200, "Z-": -90, "ZC": -10, "ZG": -10, "ZO": -10, "ZQ": -10, "ZT": -20, "ZX": -20, "Z\u2013": -90, "Z\u2014": -90, "b\\"": -10, "b'": -10, "bx": -25, "bz": -20, "e\\"": -10, "e'": -10, "ex": -5, "f\\"": 10, "f'": 10, "f*": 10, "f,": -40, "f-": -10, "f.": -40, "f7": 30, "f:": -10, "f;": -10, "f]": 30, "fa": -5, "fc": -5, "fd": -5, "fe": -5, "fo": -5, "fq": -5, "f\u2013": -10, "f\u2014": -10, "f\u2026": -40, "k-": -50, "ka": -25, "kc": -35, "kd": -35, "ke": -35, "ko": -35, "kq": -35, "ks": -30, "kv": -20, "kw": -20, "kx": -40, "ky": -20, "kz": -20, "k\xB7": -60, "k\u2013": -50, "k\u2014": -50, "k\u2022": -60, "o\\"": -10, "o'": -10, "ox": -25, "oz": -20, "p\\"": -10, "p'": -10, "px": -25, "pz": -20, "r,": -110, "r.": -110, "ra": -10, "rc": -10, "rd": -10, "re": -10, "ro": -10, "rq": -10, "r\u2026": -110, "sx": -20, "v,": -120, "v.": -120, "v:": -10, "v;": -10, "va": -5, "v\u2026": -120, "w,": -120, "w.": -120, "w:": -10, "w;": -10, "wa": -5, "w\u2026": -120, "x-": -30, "xa": -25, "xc": -25, "xd": -25, "xe": -25, "xo": -25, "xq": -25, "x\u2013": -30, "x\u2014": -30, "y,": -120, "y.": -120, "y:": -10, "y;": -10, "ya": -5, "y\u2026": -120, "za": -20, "zc": -20, "zd": -20, "ze": -20, "zo": -20, "zq": -20, "0-": 40, "0\u2013": 40, "0\u2014": 40, "1\\"": -10, "1'": -10, "1-": 40, "1\u2013": 40, "1\u2014": 40, "2-": 10, "2\u2013": 10, "2\u2014": 10, "3-": 40, "3\u2013": 40, "3\u2014": 40, "4-": 40, "4\u2013": 40, "4\u2014": 40, "5-": 40, "5\u2013": 40, "5\u2014": 40, "6-": 20, "6\u2013": 20, "6\u2014": 20, "7,": -120, "7-": -40, "7.": -120, "77": -10, "7]": -10, "7\u2013": -40, "7\u2014": -40, "7\u2026": -120, "8-": 30, "8\u2013": 30, "8\u2014": 30, "9-": 40, "9\u2013": 40, "9\u2014": 40, "\xB7X": -50, "\xB7Y": -50, "\u2022X": -50, "\u2022Y": -50, "-0": 40, "-1": 40, "-2": 40, "-3": 40, "-4": 40, "-5": 40, "-6": 40, "-8": 30, "-9": 20, "-V": -50, "-W": -50, "-X": -50, "-Y": -140, "-x": -30, "\u20130": 40, "\u20131": 40, "\u20132": 40, "\u20133": 40, "\u20134": 40, "\u20135": 40, "\u20136": 40, "\u20138": 30, "\u20139": 20, "\u2013V": -50, "\u2013W": -50, "\u2013X": -50, "\u2013Y": -140, "\u2013x": -30, "\u20140": 40, "\u20141": 40, "\u20142": 40, "\u20143": 40, "\u20144": 40, "\u20145": 40, "\u20146": 40, "\u20148": 30, "\u20149": 20, "\u2014V": -50, "\u2014W": -50, "\u2014X": -50, "\u2014Y": -140, "\u2014x": -30, "\\",": -50, "\\".": -50, "\\"4": -10, "\\"A": -100, "\\"J": -100, "\\"c": -10, "\\"d": -10, "\\"e": -10, "\\"o": -10, "\\"q": -10, "\\"\u2026": -50, "',": -50, "'.": -50, "'4": -10, "'A": -100, "'J": -100, "'c": -10, "'d": -10, "'e": -10, "'o": -10, "'q": -10, "'\u2026": -50}}, "mono": {"upm": 1000, "ascent": 1025, "descent": -275, "adv": {" ": 600, "!": 600, "\\"": 600, "#": 600, "$": 600, "%": 600, "&": 600, "'": 600, "(": 600, ")": 600, "*": 600, "+": 600, ",": 600, "-": 600, ".": 600, "/": 600, "0": 600, "1": 600, "2": 600, "3": 600, "4": 600, "5": 600, "6": 600, "7": 600, "8": 600, "9": 600, ":": 600, ";": 600, "<": 600, "=": 600, ">": 600, "?": 600, "@": 600, "A": 600, "B": 600, "C": 600, "D": 600, "E": 600, "F": 600, "G": 600, "H": 600, "I": 600, "J": 600, "K": 600, "L": 600, "M": 600, "N": 600, "O": 600, "P": 600, "Q": 600, "R": 600, "S": 600, "T": 600, "U": 600, "V": 600, "W": 600, "X": 600, "Y": 600, "Z": 600, "[": 600, "\\\\": 600, "]": 600, "^": 600, "_": 600, "\`": 600, "a": 600, "b": 600, "c": 600, "d": 600, "e": 600, "f": 600, "g": 600, "h": 600, "i": 600, "j": 600, "k": 600, "l": 600, "m": 600, "n": 600, "o": 600, "p": 600, "q": 600, "r": 600, "s": 600, "t": 600, "u": 600, "v": 600, "w": 600, "x": 600, "y": 600, "z": 600, "{": 600, "|": 600, "}": 600, "~": 600, "\xB7": 600, "\xD7": 600, "\u2013": 600, "\u2014": 600, "\u2018": 600, "\u2019": 600, "\u201C": 600, "\u201D": 600, "\u2022": 600, "\u2026": 600}, "kern": {}}, "pen": {"upm": 1000, "ascent": 960, "descent": -300, "adv": {" ": 242, "!": 210, "\\"": 237, "#": 559, "$": 450, "%": 600, "&": 564, "'": 117, "(": 330, ")": 330, "*": 363, "+": 446, ",": 198, "-": 326, ".": 198, "/": 330, "0": 450, "1": 450, "2": 450, "3": 450, "4": 450, "5": 434, "6": 471, "7": 446, "8": 450, "9": 438, ":": 198, ";": 198, "<": 446, "=": 446, ">": 446, "?": 374, "@": 643, "A": 511, "B": 523, "C": 477, "D": 587, "E": 534, "F": 466, "G": 494, "H": 574, "I": 409, "J": 315, "K": 508, "L": 426, "M": 729, "N": 619, "O": 505, "P": 468, "Q": 492, "R": 544, "S": 495, "T": 458, "U": 482, "V": 490, "W": 720, "X": 524, "Y": 504, "Z": 522, "[": 330, "\\\\": 330, "]": 330, "^": 446, "_": 446, "\`": 353, "a": 446, "b": 444, "c": 364, "d": 402, "e": 334, "f": 300, "g": 364, "h": 473, "i": 196, "j": 213, "k": 374, "l": 178, "m": 569, "n": 459, "o": 362, "p": 378, "q": 377, "r": 360, "s": 350, "t": 331, "u": 370, "v": 331, "w": 517, "x": 343, "y": 341, "z": 315, "{": 330, "|": 330, "}": 330, "~": 446, "\xB7": 187, "\xD7": 446, "\u2013": 446, "\u2014": 566, "\u2018": 117, "\u2019": 117, "\u201C": 267, "\u201D": 267, "\u2022": 187, "\u2026": 594}, "kern": {"AC": -20, "AE": -10, "AG": -10, "AH": -10, "AI": 10, "AJ": 10, "AL": -10, "AM": 10, "AO": -20, "AP": -10, "AQ": -20, "AS": -35, "AT": -50, "AU": -20, "AV": -40, "AW": -20, "AX": -10, "AY": -65, "AZ": -10, "Aj": 10, "An": -10, "Aq": -10, "Ar": -10, "As": -10, "Au": -10, "Av": -5, "Ax": 10, "Ay": -10, "Az": 20, "BC": -20, "BF": -20, "BI": -10, "BJ": -10, "BP": -10, "BR": -10, "BS": -20, "BT": -40, "BU": -20, "BV": -50, "BW": -50, "BX": -40, "BY": -65, "BZ": -30, "Bf": 10, "Bg": 10, "Bi": 10, "Bj": 10, "Bk": 10, "Bl": 10, "Bm": 10, "Bx": 10, "Bz": 40, "CA": -20, "CC": -10, "CE": -10, "CG": -10, "CJ": -10, "CK": -10, "CO": -10, "CP": -10, "CQ": -20, "CS": -10, "CT": -20, "CU": -10, "CV": -20, "CW": -20, "CX": -30, "CY": -35, "CZ": -40, "Cc": -5, "Cd": -10, "Cj": 10, "Cl": 5, "Cn": -5, "Cs": -10, "Ct": 10, "Cu": -10, "Cv": -20, "Cw": -10, "Cx": 20, "Cz": 20, "DA": -10, "DF": -10, "DI": -10, "DJ": -10, "DM": -5, "DT": -40, "DV": -30, "DW": -10, "DX": -50, "DY": -50, "DZ": -30, "Db": 10, "Dc": 10, "De": 10, "Df": 20, "Dg": 10, "Dh": 10, "Di": 15, "Dj": 5, "Dk": 10, "Dl": 10, "Dm": 20, "Do": 10, "Dp": 10, "Dq": 10, "Dr": 10, "Ds": 10, "Dt": 20, "Dv": 30, "Dw": 20, "Dx": 20, "Dy": 10, "Dz": 30, "EC": -10, "ED": -10, "EG": -10, "EJ": -10, "EO": -10, "EQ": -20, "ES": -40, "ET": -10, "EU": -20, "EV": -25, "EW": -30, "EX": -40, "EY": -50, "EZ": -20, "Ev": -10, "Ew": -10, "Ex": 10, "Ey": -10, "Ez": 20, "FA": -40, "FC": -10, "FD": 20, "FF": 20, "FI": 10, "FJ": 20, "FL": 10, "FM": -10, "FN": 10, "FO": 10, "FP": -10, "FQ": 10, "FS": 10, "FT": -30, "FV": 10, "FW": 10, "FY": 10, "FZ": -10, "Fa": -30, "Fc": -20, "Fd": -20, "Fe": -15, "Ff": 10, "Fg": -10, "Fh": 20, "Fi": 10, "Fj": 10, "Fk": 10, "Fl": 20, "Fn": -20, "Fo": -20, "Fp": -10, "Fq": -10, "Fr": -10, "Ft": 10, "Fu": -10, "Fv": 10, "Fz": 10, "GA": -10, "GI": -10, "GJ": -10, "GM": -10, "GN": 10, "GP": -20, "GS": -10, "GU": -10, "GV": -10, "GW": -20, "GX": -40, "GY": -40, "GZ": -20, "Gf": 10, "Gh": 10, "Gi": 10, "Gj": 10, "Gk": 10, "Gl": 10, "Gm": 10, "Gt": 10, "Gv": 10, "Gx": 10, "Gz": 10, "Hb": 10, "Hf": 10, "Hh": 10, "Hi": 10, "Hj": 20, "Hk": 10, "Hl": 10, "Hm": 10, "Ht": 20, "Hv": 10, "Hx": 20, "Hy": 10, "Hz": 20, "IA": 10, "ID": 30, "IF": 40, "II": 30, "IJ": 40, "IK": 10, "IL": 10, "IM": 30, "IN": 20, "IR": 10, "IU": 10, "IV": 30, "IW": 20, "IX": 10, "IY": 30, "IZ": 20, "Ia": -10, "Ib": 10, "Ic": -10, "Id": -10, "Ie": -10, "If": 20, "Ig": -10, "Ih": 30, "Ii": 20, "Ij": 30, "Ik": 20, "Il": 20, "In": -10, "Io": -10, "Ip": 10, "Iq": -20, "Ir": -10, "Is": -10, "It": 10, "Iu": -10, "Iv": -20, "Iw": -25, "Ix": 10, "Iy": -10, "Iz": 20, "JI": -10, "JJ": 10, "JO": -10, "JP": -10, "JQ": -10, "JR": -10, "JT": 10, "JU": -10, "JX": -25, "JY": -20, "JZ": -20, "Ja": -10, "Jb": 10, "Jc": -10, "Jd": -10, "Je": -10, "Jf": 10, "Jh": 10, "Ji": 10, "Jj": 20, "Jk": 10, "Jl": 20, "Jn": -10, "Jo": -10, "Jp": 10, "Jq": -10, "Jt": 20, "Ju": -20, "Jz": 10, "KC": -10, "KD": 10, "KF": 20, "KG": -10, "KJ": 20, "KM": 20, "KO": -10, "KT": -10, "KX": -10, "Ka": -40, "Kc": -40, "Kd": -40, "Ke": -40, "Kf": 10, "Kg": -40, "Kh": 10, "Ki": 10, "Kj": 40, "Kk": 10, "Kl": 10, "Kn": -40, "Ko": -50, "Kp": 10, "Kq": -50, "Ks": -40, "Kt": 10, "Ku": -60, "Kv": -30, "Kw": -40, "Kx": -10, "Ky": -30, "LC": -20, "LE": -20, "LG": -20, "LI": -40, "LL": -20, "LO": -25, "LQ": -30, "LS": -65, "LT": -70, "LU": -45, "LV": -70, "LW": -40, "LY": -90, "LZ": -10, "Lb": -10, "Lf": 10, "Lg": -10, "Lh": -10, "Li": 10, "Lj": 20, "Lk": 10, "Ll": 10, "Ln": -20, "Lp": 10, "Lq": -40, "Ls": -10, "Lt": -10, "Lu": -40, "Lv": -60, "Lw": -40, "Lx": 10, "Ly": -20, "Lz": 30, "MJ": 10, "MP": -10, "MQ": -10, "MS": -20, "MT": -30, "MU": -20, "MV": -20, "MW": -30, "MX": -10, "MY": -50, "MZ": -10, "Mb": 10, "Mf": 10, "Mh": 10, "Mi": 10, "Mk": 10, "Ml": 10, "Mp": 10, "Mq": -10, "Mt": 20, "Mu": -10, "Mv": 10, "Mx": 10, "My": -10, "Mz": 10, "NW": -10, "NX": -20, "NY": -20, "NZ": -10, "Nb": 10, "Ne": 10, "Nf": 10, "Ng": 10, "Nh": 10, "Ni": 20, "Nj": 20, "Nk": 20, "Nl": 20, "Nm": 10, "Nq": 10, "Nt": 20, "Nv": 30, "Nx": 30, "Ny": 10, "Nz": 40, "OA": -10, "OD": -10, "OI": -10, "OL": 10, "OQ": 10, "OT": -10, "OV": -10, "OW": -10, "OX": -40, "OY": -40, "OZ": -20, "Of": 20, "Og": 20, "Oh": 10, "Oi": 20, "Oj": 20, "Ok": 10, "Ol": 20, "Om": 20, "Oo": 10, "Op": 10, "Oq": 10, "Os": 10, "Ot": 20, "Ov": 30, "Ow": 10, "Ox": 30, "Oy": 20, "Oz": 30, "PA": -40, "PD": -10, "PI": -10, "PJ": -10, "PM": -30, "PN": -10, "PS": 10, "PX": -35, "PY": -20, "PZ": -50, "Pa": -40, "Pc": -30, "Pd": -40, "Pe": -20, "Pf": 10, "Pg": -10, "Ph": 10, "Pi": 10, "Pj": 20, "Pk": 10, "Pl": 10, "Pm": 10, "Pn": -10, "Po": -30, "Pq": -30, "Ps": -20, "Pt": 20, "Pu": -30, "Pv": 10, "Px": 10, "Pz": 10, "QJ": 80, "QT": -10, "QV": -10, "QW": -10, "QX": -20, "QY": -30, "QZ": -10, "Qb": 10, "Qf": 20, "Qg": 20, "Qh": 10, "Qi": 20, "Qj": 90, "Qk": 10, "Ql": 20, "Qm": 20, "Qp": 20, "Qt": 30, "Qv": 20, "Qx": 20, "Qy": 50, "Qz": 40, "RA": -25, "RB": -10, "RC": -20, "RD": 10, "RE": -20, "RF": 10, "RG": -10, "RI": -10, "RJ": 30, "RL": -10, "RM": -20, "RN": 10, "RO": -10, "RQ": -10, "RT": -10, "RU": -20, "RV": -10, "RW": -10, "RX": -20, "RY": -30, "RZ": -45, "Ra": -10, "Rc": -10, "Rd": -10, "Re": -10, "Rf": 20, "Rg": -10, "Rj": 30, "Rn": -10, "Ro": -10, "Rp": 20, "Rq": -30, "Rr": -10, "Rs": -10, "Rt": 10, "Ru": -30, "Rw": -10, "Rx": 10, "Ry": 10, "Rz": 20, "SD": 20, "SE": -10, "SF": 30, "SI": 10, "SJ": 30, "SL": 20, "SN": 10, "SO": 10, "SV": 20, "SW": 10, "SY": 10, "SZ": -10, "Sa": -10, "Sb": 10, "Sc": -20, "Sd": -25, "Se": -20, "Sf": 20, "Sg": -20, "Sh": 20, "Si": 20, "Sj": 30, "Sk": 10, "Sl": 20, "Sn": -20, "So": -10, "Sq": -20, "Sr": -10, "Ss": -10, "St": 20, "Su": -20, "Sv": -50, "Sw": -30, "Sx": 10, "Sy": -15, "Sz": 20, "TA": -50, "TC": -10, "TD": 10, "TE": -10, "TF": 30, "TG": -10, "TI": 10, "TM": -30, "TT": -30, "TV": 10, "TX": -10, "TZ": -10, "Ta": -90, "Tc": -80, "Td": -110, "Te": -90, "Tf": 20, "Tg": -80, "Th": 20, "Tj": 20, "Tk": 10, "Tl": 20, "Tm": -50, "Tn": -90, "To": -90, "Tp": -80, "Tq": -120, "Tr": -80, "Ts": -80, "Tt": 10, "Tu": -90, "Tv": -70, "Tw": -100, "Tx": -60, "Ty": -50, "Tz": -40, "UE": 10, "UF": 10, "UQ": 30, "UR": 10, "UT": 20, "UU": 10, "UV": 10, "UX": -10, "UY": -10, "UZ": -10, "Ub": 20, "Uf": 30, "Ug": 10, "Uh": 30, "Ui": 30, "Uj": 40, "Uk": 20, "Ul": 30, "Um": 30, "Up": 10, "Ur": 10, "Us": 10, "Ut": 50, "Uu": 10, "Uv": 50, "Uw": 10, "Ux": 30, "Uy": 10, "Uz": 30, "VA": -55, "VC": -20, "VE": -20, "VF": 10, "VG": -10, "VM": -30, "VN": -10, "VO": -10, "VP": -20, "VQ": -10, "VT": 20, "VU": -10, "VX": -20, "VY": -10, "VZ": -20, "Va": -50, "Vc": -30, "Vd": -30, "Ve": -30, "Vg": -30, "Vm": -10, "Vn": -30, "Vo": -30, "Vp": -20, "Vq": -30, "Vr": -20, "Vs": -30, "Vu": -30, "Vw": -30, "WA": -20, "WD": 20, "WF": 20, "WI": 10, "WJ": 20, "WL": 10, "WM": -10, "WS": 10, "WT": 30, "WV": 10, "WX": -10, "WY": 10, "WZ": -10, "Wb": 20, "Wd": -10, "We": 10, "Wf": 30, "Wh": 30, "Wi": 30, "Wj": 40, "Wk": 20, "Wl": 40, "Wm": 10, "Wt": 40, "Wv": 30, "Wx": 20, "Wy": 20, "Wz": 30, "XA": -25, "XC": -20, "XE": -10, "XG": -20, "XI": -10, "XM": -25, "XN": -10, "XO": -20, "XP": -10, "XQ": -25, "XS": -20, "XU": -20, "XX": -30, "XY": -20, "Xe": -10, "Xf": 10, "Xg": -10, "Xi": 10, "Xj": 30, "Xk": 10, "Xl": 20, "Xm": 10, "Xo": -10, "Xp": 10, "Xq": -40, "Xu": -30, "Xv": -20, "Xw": -30, "Xx": 10, "Xy": -20, "Xz": 30, "YA": -55, "YC": -30, "YD": 10, "YE": -30, "YF": 20, "YG": -30, "YH": -10, "YI": 10, "YJ": 10, "YM": -35, "YO": -20, "YP": -10, "YQ": -10, "YR": -10, "YS": -10, "YT": -15, "YX": -30, "YY": -10, "YZ": -40, "Ya": -70, "Yc": -60, "Yd": -60, "Ye": -60, "Yg": -60, "Ym": -30, "Yn": -60, "Yo": -60, "Yp": -50, "Yq": -60, "Yr": -60, "Ys": -60, "Yu": -60, "Yv": -20, "Yw": -50, "Yx": -50, "Yy": -40, "Yz": -30, "ZA": -20, "ZB": -10, "ZC": -20, "ZD": -10, "ZE": -20, "ZG": -20, "ZL": -10, "ZO": -30, "ZP": -10, "ZQ": -10, "ZR": -10, "ZS": -20, "ZU": -10, "ZW": -10, "ZX": -10, "ZY": -20, "ZZ": -10, "Za": -20, "Zb": -10, "Zc": -10, "Zd": -30, "Ze": -40, "Zg": -40, "Zj": 10, "Zk": 10, "Zm": -10, "Zn": -50, "Zo": -30, "Zp": -10, "Zq": -50, "Zr": -40, "Zs": -30, "Zt": -10, "Zu": -30, "Zv": -20, "Zw": -40, "Zx": -10, "Zy": -30, "Zz": 10, "av": -20, "aw": -10, "ay": -20, "ba": -10, "bc": -10, "bd": -10, "bh": -5, "bj": -5, "bu": -10, "bx": -10, "by": -10, "cl": 10, "cw": -10, "cy": -5, "dn": -10, "dt": 10, "du": -10, "el": 10, "fa": -10, "ff": 10, "fh": 10, "fi": 10, "fj": 10, "fl": 20, "fm": 10, "ft": 40, "fv": 10, "fy": 10, "gi": 10, "gy": 10, "hf": -10, "hg": -20, "hq": -10, "hs": -10, "hv": -30, "hw": -15, "hy": -30, "if": 10, "iv": 10, "jt": 10, "ju": -10, "jx": 10, "jy": 10, "jz": 10, "kc": 20, "ke": 10, "kf": 20, "kh": 10, "ki": 10, "kk": 20, "kl": 20, "km": 10, "ko": 10, "kr": 10, "kt": 10, "ku": 10, "kv": 10, "ky": -10, "kz": 10, "ll": 10, "lt": 10, "lz": 20, "md": 10, "mo": 20, "mv": -15, "mw": -10, "my": -10, "nb": -15, "ns": -5, "nt": -10, "nu": -10, "nv": -20, "nw": -20, "ny": -20, "oj": -5, "ou": -10, "ov": 5, "ow": -10, "oy": -10, "pn": -10, "pu": -10, "py": -10, "qh": -10, "qj": 10, "qn": -10, "qo": -10, "qu": -10, "ra": -5, "ri": 5, "rv": 20, "sf": 10, "st": 10, "sv": 20, "sx": 15, "sz": 20, "ti": 5, "tv": 10, "tx": 20, "tz": 30, "ub": -10, "uf": 10, "ui": 10, "uk": 10, "ul": 10, "ux": 10, "uz": 30, "va": -10, "vf": 10, "vi": 10, "vt": 10, "vv": 20, "vx": 20, "vy": 10, "vz": 10, "wi": 10, "wx": 10, "xf": 10, "xi": 10, "xk": 10, "xl": 10, "xn": -10, "xp": 10, "xq": -10, "xu": -5, "xv": 10, "xx": 15, "xy": -10, "xz": 10, "ya": -10, "yd": -10, "ye": 10, "yn": -10, "yt": 10, "yu": -10, "yv": 10, "yx": 10, "zf": 10, "zi": 10, "zt": 10, "zv": 10, "zx": 10, "zz": 20}}}
126
383
  `,"canary/hooks/hooks.json":`{
384
+ "modules": ["./register.tsx"],
127
385
  "hooks": {
128
386
  "SessionEnd": [
129
387
  {
@@ -252,6 +510,788 @@ On a re-check, fetch the earlier files with \`canary jobs earlier <job> <path>\`
252
510
  ]
253
511
  }
254
512
  }
513
+ `,"canary/hooks/inked.ts":`import { runs, wordsOf, type Run } from './card'
514
+ import { FONTS, METRICS, type Metrics } from './fonts'
515
+ import type { Block, Mark, Pip, Report, Score } from './report'
516
+
517
+ /**
518
+ * The final report as the lab's inked report card: the run's id up top, the verdict with its "yet" in pen, the score as
519
+ * a bar stopped at what capped it, the counts, each finding under its status (the first must-fix circled, the
520
+ * report's own last word beside it in pen), what a first result leaves open, the way to 5/5 as the report writes it with
521
+ * its first step highlighted, and the note and receipt at the foot. In the landing page's faces and its bone and ink,
522
+ * dark when the app is dark. Drawn as HTML inside an SVG, which the desktop app draws as an image; it has to be given
523
+ * its size, so every block is measured with the faces' own glyph widths first.
524
+ *
525
+ * Every word is the server's. A table's column names and a status repeated row after row are said by the layout
526
+ * instead, and the run's id, which the report gives in \`canary show <id>\`, is also set at the top.
527
+ */
528
+
529
+ export interface Drawing {
530
+ source: string
531
+ width: number
532
+ height: number
533
+ alt: string
534
+ }
535
+
536
+ /** The card's markup, its style, and the height it was measured to: what the SVG wraps, and what a layout check reads. */
537
+ export interface Card {
538
+ html: string
539
+ style: string
540
+ height: number
541
+ alt: string
542
+ }
543
+
544
+ /** Room around the card for its shadow, and the card's padding. */
545
+ const MARGIN = 10
546
+ const PAD = { top: 22, x: 26, bottom: 20 }
547
+ /** Read the room a little short, so the browser never fits fewer words on a line than the measure says. */
548
+ const SLACK = 0.95
549
+ /**
550
+ * The score's number box; the bar's cells, the gap between them and where they sit in the bar's row; and the least
551
+ * room the caption keeps beside the line it hangs from before it moves left.
552
+ */
553
+ const NUMBER = 80
554
+ const BAR = { cell: 22, gap: 6, top: 13, row: 48 }
555
+ const HANG_ROOM = 200
556
+
557
+ /** Each face at the size and line height a part of the card sets it in. */
558
+ const T = {
559
+ kicker: { face: METRICS.mono, px: 11, line: 16 },
560
+ verdict: { face: METRICS.display, px: 26, line: 30 },
561
+ why: { face: METRICS.sans, px: 16, line: 22 },
562
+ whyBold: { face: METRICS.sansBold, px: 16, line: 22 },
563
+ reading: { face: METRICS.pen, px: 22, line: 26 },
564
+ count: { face: METRICS.mono, px: 13, line: 20 },
565
+ status: { face: METRICS.mono, px: 10.5, line: 16 },
566
+ title: { face: METRICS.sansBold, px: 16, line: 22 },
567
+ how: { face: METRICS.sans, px: 14, line: 21 },
568
+ note: { face: METRICS.pen, px: 24, line: 24 },
569
+ reach: { face: METRICS.sans, px: 15, line: 24 },
570
+ step: { face: METRICS.sans, px: 15, line: 26 },
571
+ foot: { face: METRICS.sans, px: 13, line: 20 },
572
+ stub: { face: METRICS.sansBold, px: 14, line: 22 },
573
+ }
574
+ type Style = (typeof T)[keyof typeof T]
575
+
576
+ type State = 'red' | 'green' | 'plain'
577
+ const DOT: Record<Mark, string> = { '\u{1F534}': 'r', '\u{1F7E2}': 'g', '\u{1F7E1}': 'y', '\u26AA': 'w', '\u{1F7E0}': 'o', '\u23F3': 'run' }
578
+ const dotOf = (mark: Mark | null): string => (mark === null ? 'w' : DOT[mark])
579
+
580
+ /** The state a report is in, from its pips: something broke, everything held, or neither. */
581
+ const stateOf = (score: Score | null): State => (score?.pips.includes('\u{1F534}') ? 'red' : score?.pips.includes('\u{1F7E2}') ? 'green' : 'plain')
582
+
583
+ /** Rows with the same status, under it once, in the order the report lists them. */
584
+ interface Group {
585
+ mark: Mark | null
586
+ status: string
587
+ rows: { what: string; how: string }[]
588
+ }
589
+
590
+ export function inkedReport(report: Report, width: number): Drawing {
591
+ const card = cardOf(report, width)
592
+ const height = Math.ceil(card.height + 2 * MARGIN + 8)
593
+ const source = [
594
+ \`<svg xmlns="http://www.w3.org/2000/svg" width="\${width}" height="\${height}" viewBox="0 0 \${width} \${height}">\`,
595
+ \`<foreignObject x="0" y="0" width="\${width}" height="\${height}">\`,
596
+ \`<div xmlns="http://www.w3.org/1999/xhtml" class="root" style="width:\${width}px;height:\${height}px">\`,
597
+ \`<style>\${card.style}</style>\`,
598
+ card.html,
599
+ '</div></foreignObject></svg>',
600
+ ].join('')
601
+ return { source, width, height, alt: card.alt }
602
+ }
603
+
604
+ export function cardOf(report: Report, width: number): Card {
605
+ const inner = width - 2 * MARGIN - 2 - 2 * PAD.x
606
+ const score = report.score
607
+ const state = stateOf(score)
608
+ const of = <K extends Block['kind']>(kind: K) => report.blocks.filter((block): block is Extract<Block, { kind: K }> => block.kind === kind)
609
+
610
+ const groups: Group[] = []
611
+ for (const block of of('findings')) {
612
+ for (const row of block.rows) {
613
+ const group = groups.find(held => held.status === row.status.text && held.mark === row.status.mark)
614
+ if (group === undefined) groups.push({ mark: row.status.mark, status: row.status.text, rows: [{ what: row.what, how: row.how }] })
615
+ else group.rows.push({ what: row.what, how: row.how })
616
+ }
617
+ }
618
+
619
+ // The note's short first piece is the report's own word on this run ("You'd have pushed this", "Fixed on the first
620
+ // try"): it goes in pen beside what it is about, the first must-fix or the first re-checked row.
621
+ const notePieces = of('note').flatMap(note => note.pieces)
622
+ const said = notePieces[0] !== undefined && !notePieces[0].includes('\`') && notePieces[0].split(' ').length <= 6 ? notePieces[0] : null
623
+ const saidOn = said === null ? null : of('recheck').length > 0 ? 'recheck' : groups.some(group => group.mark === '\u{1F534}') ? 'mustfix' : null
624
+ const restOfNote = saidOn === null ? notePieces : notePieces.slice(1)
625
+ const runId = /canary show ([0-9a-f]{6,})/.exec(JSON.stringify(report.blocks))?.[1] ?? null
626
+
627
+ const html: string[] = []
628
+ let height = PAD.top + 2
629
+
630
+ // The id and the verdict, its "yet" in pen.
631
+ html.push(\`<div class="row"><span class="kick">Canary report</span>\${runId === null ? '' : \`<span class="kick id">\${esc(runId)}</span>\`}</div>\`)
632
+ height += T.kicker.line
633
+ const yet = /^(.*\\s)(yet)$/.exec(report.verdict)
634
+ const verdictTokens = yet === null ? words(report.verdict, T.verdict.face, T.verdict.px) : [...words(yet[1]!, T.verdict.face, T.verdict.px), piece(yet[2]!, METRICS.pen, T.verdict.px * 1.25, 4)]
635
+ height += 12 + linesOf(verdictTokens, inner) * T.verdict.line
636
+ html.push(\`<h1 class="verdict">\${yet === null ? esc(report.verdict) : \`\${esc(yet[1]!)}<span class="pen \${state}">\${esc(yet[2]!)}</span>\`}</h1>\`)
637
+
638
+ // The score as a bar stopped where it stops, what capped it hung from the stop.
639
+ if (score !== null) {
640
+ const cap = capOf(score, state, reachOf(of('list')), inner)
641
+ height += 14 + cap.height
642
+ html.push(cap.html)
643
+ }
644
+
645
+ // What Canary did.
646
+ for (const block of of('stats')) {
647
+ let lines = 1
648
+ let used = 0
649
+ for (const item of block.items) {
650
+ const w = measure(item.value, T.count.face, T.count.px) * 1.06 + measure(\` \${wordsOf(item.label)}\`, T.count.face, T.count.px)
651
+ if (used > 0 && used + 24 + w > inner * SLACK) {
652
+ lines += 1
653
+ used = w
654
+ } else used += (used > 0 ? 24 : 0) + w
655
+ }
656
+ height += 14 + lines * T.count.line + (lines - 1) * 4 + 22 + 2
657
+ html.push(\`<div class="counts">\${block.items.map(item => \`<span><b>\${esc(item.value)}</b> \${inlineHtml(runs(item.label))}</span>\`).join('')}</div>\`)
658
+ }
659
+
660
+ // What broke and what held, each under its status; the re-checked rows with their before and now.
661
+ const children: { html: string; height: number }[] = []
662
+ const noteWidth = said === null ? 0 : measure(said, T.note.face, T.note.px) + 12
663
+ for (const block of of('recheck')) {
664
+ children.push({ html: \`<div class="status \${dotOf(block.rows[0]?.now.mark ?? null)}">\${inlineHtml(runs(block.header[0] ?? ''))}</div>\`, height: T.status.line })
665
+ block.rows.forEach((row, at) => {
666
+ const pen = saidOn === 'recheck' && at === 0
667
+ const room = inner - 26 - (pen ? noteWidth : 0)
668
+ const change = [...runs(row.before.text), { text: ' \u2192 ' }, ...runs(row.now.text).map(run => ({ ...run, bold: true as const }))]
669
+ children.push({
670
+ html: \`<div class="it"><i class="d \${dotOf(row.now.mark)}"></i><div><div class="t">\${inlineHtml(runs(row.what))}</div><div class="h"><span class="struck">\${inlineHtml(runs(row.before.text))}</span> \u2192 <span class="now \${dotOf(row.now.mark)}">\${inlineHtml(runs(row.now.text))}</span></div></div>\${pen ? \`<span class="pen note \${dotOf(row.now.mark) === 'g' ? 'green' : state}">\${esc(said!)}</span>\` : ''}</div>\`,
671
+ height: linesOf(tokens(runs(row.what), T.title), room) * T.title.line + 2 + linesOf(tokens(change, T.how), room) * T.how.line,
672
+ })
673
+ })
674
+ }
675
+ let circled = false
676
+ for (const group of groups) {
677
+ const cls = dotOf(group.mark)
678
+ children.push({ html: \`<div class="status \${cls}">\${inlineHtml(runs(group.status))}</div>\`, height: T.status.line })
679
+ for (const row of group.rows) {
680
+ // The first must-fix is circled by hand, and the report's last word sits beside it in pen.
681
+ const ring: boolean = !circled && group.mark === '\u{1F534}'
682
+ circled ||= ring
683
+ const pen = ring && saidOn === 'mustfix'
684
+ const room = inner - 26 - (pen ? noteWidth : 0)
685
+ const titleLines = linesOf(tokens(runs(row.what), T.title), room)
686
+ const title = ring && titleLines === 1 ? \`<span class="circ">\${inlineHtml(runs(row.what))}\${HAND_RING}</span>\` : inlineHtml(runs(row.what))
687
+ children.push({
688
+ html: \`<div class="it"><i class="d \${cls}"></i><div><div class="t">\${title}</div><div class="h">\${inlineHtml(runs(row.how))}</div></div>\${pen ? \`<span class="pen note red">\${esc(said!)}</span>\` : ''}</div>\`,
689
+ height: titleLines * T.title.line + 2 + linesOf(tokens(runs(row.how), T.how), room) * T.how.line,
690
+ })
691
+ }
692
+ }
693
+ if (children.length > 0) {
694
+ height += 16 + children.reduce((sum, child) => sum + child.height, 0) + (children.length - 1) * 12
695
+ html.push(\`<div class="items">\${children.map(child => child.html).join('')}</div>\`)
696
+ }
697
+
698
+ // What a first result leaves open, in the server's own line, under what it found.
699
+ for (const open of of('open')) {
700
+ height += 12 + linesOf(tokens(runs(open.text), T.how), inner) * T.how.line
701
+ html.push(\`<div class="open-line">\${inlineHtml(runs(open.text))}</div>\`)
702
+ }
703
+
704
+ // The way to 5/5 a line a step, each cut where its line ends however long the server's words run (all of them stay in
705
+ // the alt text), what it earns at the end, the first on the highlighter; any other list as one paragraph.
706
+ for (const list of of('list')) {
707
+ if (list.label.startsWith('To reach')) {
708
+ height += 18 + T.status.line + 6 + list.items.length * T.step.line
709
+ html.push(\`<div class="steps"><div class="status y">\${esc(list.label)}:</div>\${list.items.map((item, at) => stepHtml(item, at === 0)).join('')}</div>\`)
710
+ continue
711
+ }
712
+ const line: Run[] = [{ text: \`\${list.label}: \`, bold: true }, ...list.items.flatMap((item, at) => [...(at > 0 ? [{ text: ' \xB7 ' }] : []), ...runs(item)])]
713
+ height += 16 + linesOf(tokens(line, T.reach), inner) * T.reach.line
714
+ html.push(\`<div class="reach"><b>\${esc(list.label)}:</b> \${list.items.map(item => inlineHtml(runs(item))).join(' \xB7 ')}</div>\`)
715
+ }
716
+
717
+ // The rest of the note.
718
+ const foot: string[] = []
719
+ let footHeight = 0
720
+ if (restOfNote.length > 0 || (said !== null && saidOn === null)) {
721
+ const pieces = saidOn === null ? notePieces : restOfNote
722
+ footHeight += linesOf(tokens(runs(pieces.join(' \xB7 ')), T.foot), inner) * T.foot.line
723
+ foot.push(\`<div class="note-line">\${pieces.map(piece => inlineHtml(runs(piece))).join(' \xB7 ')}</div>\`)
724
+ }
725
+ if (foot.length > 0) {
726
+ height += 16 + 12 + 1 + footHeight
727
+ html.push(\`<div class="foot">\${foot.join('')}</div>\`)
728
+ }
729
+
730
+ // The receipt, as a stub to tear off at the card's foot. Its own padding stands in for the card's bottom padding, and
731
+ // the card is cut out where its perforation meets the edges.
732
+ const receipts = of('share').map(share => receiptOf(share.text, state, inner))
733
+ if (receipts.length === 0) height += PAD.bottom
734
+ const stub = receipts.reduce((sum, receipt) => sum + receipt.height, 16 + 18)
735
+ if (receipts.length > 0) {
736
+ height += 18 + stub
737
+ html.push(\`<div class="stub"><div class="perf"></div>\${receipts.map(receipt => receipt.html).join('')}</div>\`)
738
+ }
739
+
740
+ const open = receipts.length > 0 ? \`<div class="card stubbed" style="--notch:\${stub}px">\` : '<div class="card">'
741
+ return { html: \`\${open}\${html.join('')}</div>\`, style: STYLE, height, alt: altOf(report, groups, said, saidOn !== null, runId) }
742
+ }
743
+
744
+ /**
745
+ * A receipt's pieces ("Canary \xB7 2/5 \xB7 caught 1 must-fix before push \xB7 5 checks run \xB7 runcanary.ai"): Canary's name, the
746
+ * score when it gives one, and what Canary did. The address it closes on stays off the card (founder 11-03), as the card
747
+ * is already Canary's; a receipt without a score or an address keeps whichever pieces it has.
748
+ */
749
+ function receiptPieces(text: string): { brand: string | null; score: string | null; done: string } {
750
+ const pieces = text.split(' \xB7 ')
751
+ const brand = pieces.length > 1 ? pieces.shift()! : null
752
+ if (pieces.length > 1 && /^[\\w-]+(\\.[\\w-]+)+$/.test(pieces[pieces.length - 1]!)) pieces.pop()
753
+ const score = pieces.length > 1 && /\\/5$/.test(pieces[0]!) ? pieces.shift()! : null
754
+ return { brand, score, done: pieces.join(' \xB7 ') }
755
+ }
756
+
757
+ /** The receipt in the stub: the name and score small, what Canary did in ink. */
758
+ function receiptOf(text: string, state: State, inner: number): { html: string; height: number } {
759
+ const { brand, score, done } = receiptPieces(text)
760
+ const space: Token = { text: ' ', face: METRICS.sans, px: T.stub.px, extra: 0, breakable: true }
761
+ // The name is set in spaced capitals, and the name and score each keep 8px before what follows.
762
+ const lead: Token[] = [
763
+ ...(brand === null ? [] : [piece(brand.toUpperCase(), METRICS.mono, 12, brand.length * 0.14 * 12 + 8), space]),
764
+ ...(score === null ? [] : [piece(score, METRICS.mono, 12, 8), space]),
765
+ ...words(done, T.stub.face, T.stub.px),
766
+ ]
767
+ const html = [
768
+ '<div class="stub-row">',
769
+ brand === null ? '' : \`<span class="brand">\${esc(brand)}</span> \`,
770
+ score === null ? '' : \`<span class="sc \${state}">\${esc(score)}</span> \`,
771
+ \`<span class="val">\${esc(done)}</span></div>\`,
772
+ ].join('')
773
+ return { html, height: linesOf(lead, inner) * T.stub.line }
774
+ }
775
+
776
+ /** A step to 5/5 on a line of its own: its words, cut where the line ends, then what it earns ("\u2192 4/5", "(can reach 5/5)"). */
777
+ function stepHtml(item: string, first: boolean): string {
778
+ const gain = /\\s*(\u2192\\s*\\d\\/5|\\(can reach \\d\\/5\\))\\s*$/.exec(item)
779
+ const words = inlineHtml(runs(gain === null ? item : item.slice(0, gain.index)))
780
+ return \`<div class="step"><span class="what">\${first ? \`<span class="hl">\${words}</span>\` : words}</span>\${gain === null ? '' : \` <b class="gain">\${esc(gain[1]!)}</b>\`}</div>\`
781
+ }
782
+
783
+ /** Where the report's first step to 5/5 takes the score ("fix \u2026 \u2192 4/5", "run \u2026 (can reach 5/5)"), when it says. */
784
+ function reachOf(lists: { label: string; items: string[] }[]): number | null {
785
+ const first = lists.find(list => list.label.startsWith('To reach'))?.items[0]
786
+ if (first === undefined) return null
787
+ const words = wordsOf(first)
788
+ const reach = /\u2192\\s*(\\d)\\/5/.exec(words) ?? /can reach (\\d)\\/5/.exec(words)
789
+ return reach === null ? null : Number(reach[1])
790
+ }
791
+
792
+ /** A soft light around the filled cells, which only the dark card turns on. */
793
+ const GLOW =
794
+ '<defs><filter id="glow" x="-20%" y="-80%" width="140%" height="260%"><feGaussianBlur stdDeviation="3" result="blur"/>' +
795
+ '<feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge></filter></defs>'
796
+
797
+ /**
798
+ * The score as a bar of cells that stops where the score stops: each scored pip filled in its color (one joined bar
799
+ * when all are filled alike), the gain the report's next step names as slots outlined in the highlighter's yellow, the
800
+ * rest open (dashed when there is no score yet). Where the caption says what capped the score, a red line crosses the
801
+ * bar at the stop and the caption hangs from it; a re-check's old stop stays as a broken line the bar has passed. The
802
+ * score's own text sits beside the bar, its number large.
803
+ */
804
+ function capOf(score: Score, state: State, reach: number | null, inner: number): { html: string; height: number } {
805
+ const [top, bottom] = score.value.split('/')
806
+ const count = score.pips.length
807
+ const scored = score.pips.filter(pip => pip !== '\u26AA').length
808
+ const unscored = scored === 0 && !/\\d/.test(top ?? '')
809
+ const gainTo = reach === null ? scored : Math.max(scored, Math.min(count, reach))
810
+ // Only a red score was held down by something, so only a red one leaves its stop behind on a re-check.
811
+ const before = score.before === null || !score.before.includes('\u{1F534}') ? null : score.before.filter(pip => pip !== '\u26AA').length
812
+ const labeled = score.caption === null ? null : /^([^:*\`]{1,24}):\\s+(.+)$/.exec(score.caption)
813
+ const capped = labeled?.[1] === 'capped by' && scored < count
814
+ const width = inner - NUMBER - 14
815
+ const cell = (width - (count - 1) * BAR.gap) / count
816
+ const x = (index: number) => index * (cell + BAR.gap)
817
+ const stopAt = (filled: number) => (filled === 0 ? -BAR.gap / 2 - 3 : x(filled) - BAR.gap / 2)
818
+ const px = (value: number) => value.toFixed(1)
819
+ const rect = (kind: string, left: number, span: number, inset = 0) =>
820
+ \`<rect class="cell \${kind}" x="\${px(left + inset)}" y="\${BAR.top + inset}" width="\${px(span - 2 * inset)}" height="\${BAR.cell - 2 * inset}" rx="3"/>\`
821
+
822
+ const parts: string[] = []
823
+ const first = score.pips[0]
824
+ if (first !== undefined && scored === count && score.pips.every(pip => pip === first)) parts.push(rect(DOT[first], 0, width))
825
+ else
826
+ score.pips.forEach((pip, index) => {
827
+ if (pip !== '\u26AA') parts.push(rect(DOT[pip], x(index), cell))
828
+ // An outline straddles its edge, so the slot is set in by half the stroke to line up with the filled cells.
829
+ else if (index < gainTo) parts.push(rect('gain', x(index), cell, 0.75))
830
+ else parts.push(rect(unscored ? 'open dash' : 'open', x(index), cell))
831
+ })
832
+ // Drawn a little crooked, as a hand would, over a cut in the card's own color so it reads apart from the cells.
833
+ const line = (d: string, kind: string) => \`<path class="stop halo\${kind}" d="\${d}"/><path class="stop\${kind}" d="\${d}"/>\`
834
+ if (capped) {
835
+ const at = stopAt(scored)
836
+ parts.push(line(\`M\${px(at + 2)} -4C\${px(at + 3)} 14 \${px(at - 2)} 32 \${px(at - 0.5)} \${BAR.row + 3}\`, ''))
837
+ }
838
+ if (before !== null && before < scored) {
839
+ const at = stopAt(before)
840
+ parts.push(
841
+ line(\`M\${px(at + 3)} -2C\${px(at + 3.5)} 5 \${px(at + 1)} 11 \${px(at + 1.6)} 17\`, ' old'),
842
+ line(\`M\${px(at - 0.5)} 32C\${px(at - 1)} 38 \${px(at - 3)} 43 \${px(at - 4)} \${BAR.row + 1}\`, ' old'),
843
+ )
844
+ }
845
+
846
+ let below = 0
847
+ let caption = ''
848
+ if (score.caption !== null) {
849
+ const hung = capped ? Math.max(0, Math.min(stopAt(scored) - 2, width - HANG_ROOM)) : 0
850
+ // Hung from its line while it reads in two lines there; a longer one starts under the bar's start instead.
851
+ const hang = labeled !== null && hung > 0 && linesOf(tokens(runs(labeled[2]!), T.whyBold), width - hung) > 2 ? 0 : hung
852
+ const room = width - hang
853
+ if (labeled !== null) {
854
+ const tone = state === 'red' ? 'r' : state === 'green' ? 'g' : 'y'
855
+ below += 3 + T.status.line + 2 + linesOf(tokens(runs(labeled[2]!), T.whyBold), room) * T.whyBold.line
856
+ caption = \`<div class="why" style="padding-left:\${px(hang)}px"><span class="status \${tone}">\${esc(labeled[1]!)}:</span> <span class="what">\${inlineHtml(runs(labeled[2]!))}</span></div>\`
857
+ } else {
858
+ const style = state === 'green' ? T.whyBold : T.why
859
+ below += 3 + linesOf(tokens(runs(score.caption), style), room) * style.line
860
+ caption = \`<div class="why plain \${state}" style="padding-left:\${px(hang)}px">\${inlineHtml(runs(score.caption))}</div>\`
861
+ }
862
+ }
863
+ let reading = ''
864
+ if (score.reading !== null) {
865
+ // Under the slots it is about ("one proof from 5/5"), when the next step's gain is drawn.
866
+ const end = gainTo > scored ? width - (x(gainTo - 1) + cell) : null
867
+ below += 4 + linesOf(tokens(runs(score.reading), T.reading), width - (end ?? 0)) * T.reading.line
868
+ reading = \`<div class="pen reading"\${end === null ? '' : \` style="text-align:right;padding-right:\${px(end)}px"\`}>\${inlineHtml(runs(score.reading))}</div>\`
869
+ }
870
+
871
+ // 40 is the baseline that centers the 44px digits on the cells.
872
+ const number = \`<svg xmlns="http://www.w3.org/2000/svg" class="num \${state}" width="\${NUMBER}" height="\${BAR.row}" viewBox="0 0 \${NUMBER} \${BAR.row}"><text x="0" y="40">\${esc(top ?? score.value)}\${bottom === undefined ? '' : \`<tspan class="den">/\${esc(bottom)}</tspan>\`}</text></svg>\`
873
+ const bar = \`<svg xmlns="http://www.w3.org/2000/svg" width="\${px(width)}" height="\${BAR.row}" viewBox="0 0 \${px(width)} \${BAR.row}">\${GLOW}\${parts.join('')}</svg>\`
874
+ return { html: \`<div class="score">\${number}<div class="bar" style="width:\${px(width)}px">\${bar}\${caption}\${reading}</div></div>\`, height: BAR.row + below }
875
+ }
876
+
877
+ /** What a reader who can't see the card hears: the card's words, in its order. */
878
+ function altOf(report: Report, groups: Group[], said: string | null, placed: boolean, runId: string | null): string {
879
+ const lines = [\`Canary report\${runId === null ? '' : \` \${runId}\`}: \${report.verdict}\`]
880
+ const score = report.score
881
+ if (score !== null) lines.push([score.value, score.caption === null ? null : wordsOf(score.caption), score.reading === null ? null : wordsOf(score.reading)].filter(Boolean).join(' \xB7 '))
882
+ for (const block of report.blocks) if (block.kind === 'stats') lines.push(block.items.map(item => \`\${item.value} \${wordsOf(item.label)}\`).join(' \xB7 '))
883
+ for (const block of report.blocks) {
884
+ if (block.kind !== 'recheck') continue
885
+ lines.push(wordsOf(block.header[0] ?? ''))
886
+ for (const row of block.rows) lines.push(\`\${wordsOf(row.what)}: \${wordsOf(row.before.text)} \u2192 \${wordsOf(row.now.text)}\`)
887
+ }
888
+ for (const group of groups) lines.push(\`\${wordsOf(group.status)}: \${group.rows.map(row => \`\${wordsOf(row.what)} (\${wordsOf(row.how)})\`).join(' \xB7 ')}\`)
889
+ if (said !== null && placed) lines.push(wordsOf(said))
890
+ for (const block of report.blocks) if (block.kind === 'open') lines.push(wordsOf(block.text))
891
+ for (const block of report.blocks) if (block.kind === 'list') lines.push(\`\${block.label}: \${block.items.map(wordsOf).join(' \xB7 ')}\`)
892
+ for (const block of report.blocks) {
893
+ if (block.kind === 'note') {
894
+ const rest = said !== null && placed && block.pieces[0] === said ? block.pieces.slice(1) : block.pieces
895
+ if (rest.length > 0) lines.push(rest.map(wordsOf).join(' \xB7 '))
896
+ }
897
+ if (block.kind === 'share') {
898
+ const { brand, score, done } = receiptPieces(block.text)
899
+ lines.push([brand, score, done].filter(piece => piece !== null).join(' \xB7 '))
900
+ }
901
+ }
902
+ return lines.join('. ')
903
+ }
904
+
905
+ /** HTML for one line's runs: code as a chip, emphasis as the server wrote it. */
906
+ function inlineHtml(line: Run[]): string {
907
+ return line
908
+ .map(run => {
909
+ const text = esc(run.text)
910
+ if (run.code === true) return \`<code>\${text}</code>\`
911
+ if (run.bold === true && run.italic === true) return \`<b><em>\${text}</em></b>\`
912
+ if (run.bold === true) return \`<b>\${text}</b>\`
913
+ if (run.italic === true) return \`<em>\${text}</em>\`
914
+ return text
915
+ })
916
+ .join('')
917
+ }
918
+
919
+ /** A word, a space, or a chip, in the face it is set in. */
920
+ interface Token {
921
+ text: string
922
+ face: Metrics
923
+ px: number
924
+ extra: number
925
+ breakable: boolean
926
+ }
927
+
928
+ const piece = (text: string, face: Metrics, px: number, extra = 0): Token => ({ text, face, px, extra, breakable: false })
929
+
930
+ function words(text: string, face: Metrics, px: number): Token[] {
931
+ return text
932
+ .split(/( )/)
933
+ .filter(part => part !== '')
934
+ .map(part => ({ text: part, face, px, extra: 0, breakable: part === ' ' }))
935
+ }
936
+
937
+ function tokens(line: Run[], style: Style): Token[] {
938
+ return line.flatMap(run =>
939
+ run.code === true ? chip(run.text, style.px) : words(run.text, run.bold === true && style.face === METRICS.sans ? METRICS.sansBold : style.face, style.px),
940
+ )
941
+ }
942
+
943
+ /** A code chip breaks at its spaces like the words around it (a command can be longer than the card), its padding on its first and last word. */
944
+ function chip(text: string, px: number): Token[] {
945
+ const parts = words(text, METRICS.mono, px * 0.88)
946
+ const solid = parts.filter(part => !part.breakable)
947
+ const first = solid[0]
948
+ const last = solid[solid.length - 1]
949
+ if (first !== undefined) first.extra += 5
950
+ if (last !== undefined) last.extra += 5
951
+ return parts
952
+ }
953
+
954
+ /** How many lines tokens take at \`room\`, breaking at spaces as the browser does, and inside a word longer than a line. */
955
+ function linesOf(line: Token[], room: number): number {
956
+ const full = room * SLACK
957
+ let lines = 1
958
+ let used = 0
959
+ for (const token of line) {
960
+ const width = measure(token.text, token.face, token.px) + token.extra
961
+ if (token.breakable) used += width
962
+ else if (used + width > full && used > 0) {
963
+ lines += 1
964
+ used = width
965
+ } else used += width
966
+ if (!token.breakable && width > full) {
967
+ lines += Math.ceil(width / full) - 1
968
+ used = width % full
969
+ }
970
+ }
971
+ return lines
972
+ }
973
+
974
+ function measure(text: string, face: Metrics, px: number): number {
975
+ let units = 0
976
+ let previous = ''
977
+ const fallback = face.adv['n'] ?? face.upm / 2
978
+ for (const char of text) {
979
+ units += (face.kern[previous + char] ?? 0) + (face.adv[char] ?? fallback)
980
+ previous = char
981
+ }
982
+ return (units / face.upm) * px
983
+ }
984
+
985
+ const esc = (text: string): string => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
986
+
987
+ /** The landing page's hand-drawn circle (lp-marks.tsx). */
988
+ const HAND_RING =
989
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 120" preserveAspectRatio="none"><path d="M60 22C120 6 300 4 370 26S398 88 300 104 40 110 14 74 40 16 150 12 330 18 352 30"/></svg>'
990
+
991
+ const face = (family: string, data: string, weight = 400) =>
992
+ \`@font-face{font-family:\${family};font-weight:\${weight};src:url(data:font/woff2;base64,\${data}) format('woff2')}\`
993
+
994
+ /** The lab's inked report in the landing page's bone and ink, its dark values when the app is dark. */
995
+ const STYLE = [
996
+ face('CanaryDisplay', FONTS.display),
997
+ face('CanarySans', FONTS.sans, 400),
998
+ face('CanarySans', FONTS.sansBold, 600),
999
+ face('CanaryMono', FONTS.mono),
1000
+ face('CanaryPen', FONTS.pen, 700),
1001
+ \`.root{box-sizing:border-box;padding:\${MARGIN}px;font-family:CanarySans,system-ui,sans-serif;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}\`,
1002
+ \`.card{--ink:#14120B;--muted:rgba(20,18,11,.62);--faint:rgba(20,18,11,.42);--line:rgba(20,18,11,.13);--panel:#ECE8DC;--red:#C8281C;--green:#12804A;--ochre:#A87400;--orange:#B85409;--gain-line:#E8B400;--gain-fill:rgba(255,212,0,.34);--track:rgba(20,18,11,.11);--hl:rgba(255,212,0,.62);--code:rgba(20,18,11,.07)}\`,
1003
+ \`@media (prefers-color-scheme:dark){.card{--ink:#E8E6E1;--muted:rgba(232,230,225,.64);--faint:rgba(232,230,225,.42);--line:rgba(255,232,178,.13);--panel:#1A1811;--red:#FF4D3D;--green:#34D374;--ochre:#FFD400;--orange:#FF8F40;--gain-line:#FFD400;--gain-fill:rgba(255,212,0,.09);--track:rgba(232,230,225,.14);--hl:rgba(255,212,0,.26);--code:rgba(255,255,255,.08)}}\`,
1004
+ \`.card{box-sizing:border-box;background:var(--panel);color:var(--ink);border:1px solid var(--line);border-radius:12px;padding:\${PAD.top}px \${PAD.x}px \${PAD.bottom}px;overflow-wrap:anywhere}\`,
1005
+ \`.row{display:flex;justify-content:space-between;height:\${T.kicker.line}px}\`,
1006
+ \`.kick{font-family:CanaryMono,ui-monospace,monospace;font-size:11px;line-height:\${T.kicker.line}px;letter-spacing:.12em;text-transform:uppercase;color:var(--muted)}\`,
1007
+ \`.verdict{font-family:CanaryDisplay,sans-serif;font-weight:400;font-size:26px;line-height:\${T.verdict.line}px;margin:12px 0 0}\`,
1008
+ \`.verdict::first-letter{text-transform:uppercase}\`,
1009
+ \`.pen{font-family:CanaryPen,cursive;font-weight:700}.pen.red{color:var(--red)}.pen.green{color:var(--green)}.pen.plain{color:var(--ochre)}\`,
1010
+ \`.verdict .pen{font-size:1.25em;line-height:\${T.verdict.line}px;margin-left:4px;display:inline-block;transform:rotate(-3deg)}\`,
1011
+ \`.score{display:flex;gap:14px;margin-top:14px;align-items:flex-start}.bar{flex:none}.bar svg{display:block;overflow:visible}\`,
1012
+ \`.num{display:block;flex:none;overflow:visible}.num text{font-family:CanaryDisplay,sans-serif;font-size:44px;letter-spacing:-.02em;fill:var(--muted)}.num.red text{fill:var(--red)}.num.green text{fill:var(--green)}\`,
1013
+ \`.num .den{fill:var(--faint)}\`,
1014
+ \`.cell.r{fill:var(--red)}.cell.g{fill:var(--green)}.cell.y{fill:#E8A800}.cell.open{fill:var(--track)}.cell.dash{fill:none;stroke:var(--faint);stroke-width:1.3;stroke-dasharray:4 3}\`,
1015
+ \`.cell.gain{fill:var(--gain-fill);stroke:var(--gain-line);stroke-width:1.5}@media (prefers-color-scheme:dark){.cell.r,.cell.g,.cell.y{filter:url(#glow)}}\`,
1016
+ \`.stop{fill:none;stroke:var(--red);stroke-width:5;stroke-linecap:round}.stop.halo{stroke:var(--panel);stroke-width:11}.stop.old{stroke-width:3.4;opacity:.7}.stop.halo.old{stroke-width:9;opacity:1}\`,
1017
+ \`.why{margin-top:3px;font-size:16px;line-height:\${T.why.line}px}.why .status{display:block;margin-bottom:2px}.why .what{font-weight:600}.why.plain{color:var(--muted)}.why.plain.green{color:var(--green);font-weight:600}.why em{font-style:normal}\`,
1018
+ \`.reading{font-size:22px;line-height:\${T.reading.line}px;color:var(--ochre);margin-top:4px}.reading:first-child{margin-top:0}.reading em{font-style:normal}\`,
1019
+ \`.counts{display:flex;flex-wrap:wrap;gap:4px 24px;font-family:CanaryMono,ui-monospace,monospace;font-size:13px;line-height:\${T.count.line}px;color:var(--muted);padding:11px 0;margin-top:14px;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}\`,
1020
+ \`.counts b{color:var(--ink);font-weight:600}\`,
1021
+ \`.items{display:grid;gap:12px;margin-top:16px}\`,
1022
+ \`.status{font-family:CanaryMono,ui-monospace,monospace;font-size:10.5px;line-height:\${T.status.line}px;letter-spacing:.12em;text-transform:uppercase}\`,
1023
+ \`.status.r{color:var(--red)}.status.g{color:var(--green)}.status.y{color:var(--ochre)}.status.w{color:var(--faint)}.status.o{color:var(--orange)}.status.run{color:var(--faint)}\`,
1024
+ \`.it{display:grid;grid-template-columns:14px minmax(0,1fr) auto;column-gap:12px;align-items:start}\`,
1025
+ \`.d{width:12px;height:12px;border-radius:50%;margin-top:5px;box-sizing:border-box;display:block}.d.r{background:var(--red)}.d.g{background:var(--green)}.d.y{background:#E8A800}.d.w{border:1.5px solid var(--faint)}.d.o{background:var(--orange)}.d.run{border:1.5px dashed var(--faint)}\`,
1026
+ \`.open-line{margin-top:12px;font-size:14px;line-height:21px;color:var(--muted)}\`,
1027
+ \`.t{font-weight:600;font-size:16px;line-height:\${T.title.line}px}.h{font-size:14px;line-height:\${T.how.line}px;color:var(--muted);margin-top:2px}\`,
1028
+ \`.struck{text-decoration:line-through;text-decoration-color:var(--red);text-decoration-thickness:2px;color:var(--faint)}.now{font-weight:600}.now.g{color:var(--green)}.now.r{color:var(--red)}\`,
1029
+ \`.note{font-size:24px;line-height:\${T.note.line}px;transform:rotate(-6deg);white-space:nowrap;margin-top:-2px}\`,
1030
+ \`.circ{position:relative;display:inline-block}.circ svg{position:absolute;left:-.45em;top:-.32em;width:calc(100% + .9em);height:calc(100% + .64em);overflow:visible}\`,
1031
+ \`.circ path{fill:none;stroke:var(--red);stroke-width:2.2;stroke-linecap:round;vector-effect:non-scaling-stroke}\`,
1032
+ \`.reach{margin-top:16px;font-size:15px;line-height:\${T.reach.line}px}.reach b{font-weight:600}.reach em{font-style:italic}\`,
1033
+ \`.hl{background:linear-gradient(100deg,transparent 0 .5%,var(--hl) 1% 98%,transparent 99%) 0 85%/100% 58% no-repeat;padding:0 2px;-webkit-box-decoration-break:clone;box-decoration-break:clone}\`,
1034
+ \`.steps{margin-top:18px}.steps .status{margin-bottom:6px}\`,
1035
+ \`.step{display:flex;gap:14px;align-items:baseline;font-size:15px;line-height:\${T.step.line}px}.step em{font-style:italic}\`,
1036
+ \`.step .what{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.step .gain{flex:none;font-weight:600}\`,
1037
+ \`.foot{margin-top:16px;padding-top:12px;border-top:1px solid var(--line)}\`,
1038
+ \`.note-line{font-size:13px;line-height:\${T.foot.line}px;color:var(--muted)}\`,
1039
+ \`.stub{position:relative;margin:18px -\${PAD.x}px -\${PAD.bottom}px;padding:16px \${PAD.x}px 18px}.perf{position:absolute;left:14px;right:14px;top:0;border-top:2px dashed var(--line)}\`,
1040
+ // A cut-out alone vanishes on a chat as dark as the card: the card's border runs on around each notch, as a ticket's does.
1041
+ \`.stub::before,.stub::after{content:"";position:absolute;top:-12px;width:24px;height:24px;border-radius:50%;box-sizing:border-box;border:1.5px solid var(--line)}.stub::before{left:-13px}.stub::after{right:-13px}\`,
1042
+ \`.card.stubbed{-webkit-mask:radial-gradient(circle 10px at 0 calc(100% - var(--notch)),#0000 96%,#000),radial-gradient(circle 10px at 100% calc(100% - var(--notch)),#0000 96%,#000);-webkit-mask-composite:source-in;mask-composite:intersect}\`,
1043
+ \`.stub-row{line-height:\${T.stub.line}px}\`,
1044
+ \`.stub .brand{font-family:CanaryMono,ui-monospace,monospace;font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted);margin-right:8px}\`,
1045
+ \`.stub .sc{font-family:CanaryMono,ui-monospace,monospace;font-size:12px;font-weight:600;color:var(--faint);margin-right:8px}.stub .sc.red{color:var(--red)}.stub .sc.green{color:var(--green)}\`,
1046
+ \`.stub .val{font-size:\${T.stub.px}px;font-weight:600}\`,
1047
+ \`code{font-family:CanaryMono,ui-monospace,monospace;font-size:.88em;background:var(--code);border-radius:4px;padding:1px 5px;-webkit-box-decoration-break:clone;box-decoration-break:clone}\`,
1048
+ \`em{font-style:italic}b{font-weight:600}\`,
1049
+ ].join('')
1050
+ `,"canary/hooks/register.tsx":`import type { Register } from 'claude-code'
1051
+
1052
+ import { inkedReport } from './inked'
1053
+ import { splitReport } from './report'
1054
+
1055
+ /**
1056
+ * One moment, redrawn: Canary's final report becomes a report card in the desktop app. Every other card, the agent's
1057
+ * own words, and every other surface (the terminal, the editor, mobile) are drawn as the app always draws them.
1058
+ */
1059
+
1060
+ /**
1061
+ * The card's width: the room the surface reports, in cells, read low (a cell is wider than 7px), so the card never
1062
+ * runs past the transcript; 620px where the surface hasn't measured.
1063
+ */
1064
+ const widthOf = (columns: number | undefined): number => (columns === undefined ? 620 : Math.min(680, Math.max(480, Math.floor(columns * 7))))
1065
+
1066
+ /** The most an Svg's markup may hold. */
1067
+ const SVG_LIMIT = 131072
1068
+
1069
+ export const register: Register = on => {
1070
+ on('ui.render', { component: 'AssistantMessage' }, ($, e, next) => {
1071
+ if (e.props.isSummary || e.surface !== 'desktop') return next(e)
1072
+ const split = splitReport(e.props.text)
1073
+ if (split === null) return next(e)
1074
+ const ui = $.ui.resolve(e)
1075
+ if (!('Svg' in ui)) return next(e)
1076
+ const drawn = inkedReport(split.report, widthOf(e.viewport?.columns))
1077
+ if (drawn.source.length > SVG_LIMIT) return next(e)
1078
+ const { Box, Markdown, Svg } = ui
1079
+ return (
1080
+ <Box flexDirection="column" gap="sm">
1081
+ {split.before !== '' && <Markdown text={split.before} />}
1082
+ <Svg source={drawn.source} alt={drawn.alt} width={drawn.width} height={drawn.height} />
1083
+ {split.after !== '' && <Markdown text={split.after} />}
1084
+ </Box>
1085
+ )
1086
+ })
1087
+ }
1088
+ `,"canary/hooks/report.ts":`/**
1089
+ * Reads the final report Canary's server writes into a reply (services/backend/src/render/agent/report.ts) into its
1090
+ * blocks, without changing a word. The blocks are read in the order the server writes them, each by the shape and the
1091
+ * words the server gives it: a block out of its place, or one the server never writes, ends the report there, and from
1092
+ * that block on the reply is the agent's own text, drawn as the app draws it.
1093
+ *
1094
+ * While the reply streams in, the card grows with it and never loses what it drew: the score's caption is read as far
1095
+ * as it has come, a table's row once all its cells are in, and a block still too short to tell waits under the card.
1096
+ */
1097
+
1098
+ export type Pip = '\u{1F534}' | '\u{1F7E2}' | '\u{1F7E1}' | '\u26AA'
1099
+
1100
+ /** A status's mark in the findings: a pip, or a check still to prove (\u{1F7E0}) or still running (\u23F3). */
1101
+ export type Mark = Pip | '\u{1F7E0}' | '\u23F3'
1102
+
1103
+ export interface Score {
1104
+ /** The pips before a re-check, when there was one. */
1105
+ before: Pip[] | null
1106
+ pips: Pip[]
1107
+ /** "2/5", "\u2013/5". */
1108
+ value: string
1109
+ /** What capped it, or what the score means. */
1110
+ caption: string | null
1111
+ /** A line under the score that reads it out ("one proof from 5/5"). */
1112
+ reading: string | null
1113
+ }
1114
+
1115
+ /** A cell that opens with a mark: "\u{1F534} Must fix", "\u{1F7E2} Refused (403), the workspace stays". */
1116
+ export interface Marked {
1117
+ mark: Mark | null
1118
+ text: string
1119
+ }
1120
+
1121
+ export type Block =
1122
+ | { kind: 'stats'; items: { value: string; label: string }[] }
1123
+ | { kind: 'findings'; header: string[]; rows: { status: Marked; what: string; how: string }[] }
1124
+ | { kind: 'recheck'; header: string[]; rows: { what: string; before: Marked; now: Marked }[] }
1125
+ | { kind: 'open'; text: string }
1126
+ | { kind: 'list'; mark: Pip | null; label: string; items: string[] }
1127
+ | { kind: 'note'; pieces: string[] }
1128
+ | { kind: 'share'; text: string }
1129
+
1130
+ export interface Report {
1131
+ verdict: string
1132
+ score: Score | null
1133
+ blocks: Block[]
1134
+ }
1135
+
1136
+ export interface Split {
1137
+ before: string
1138
+ report: Report
1139
+ after: string
1140
+ }
1141
+
1142
+ const HEADING = /^## Canary report:\\s*(.+?)\\s*$/
1143
+ // 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
1145
+ const ITALIC_LINE = /^\\*(?!\\*)(.+)(?<!\\*)\\*$/
1146
+ const LABELED = /^(?:([\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA])\\s+)?\\*\\*([^*]+?):\\*\\*\\s+(.+)$/u
1147
+ const SHARE = /^\`(Canary \xB7 [^\`]+)\`$/
1148
+ const ALIGN = /^\\|(\\s*:?-+:?\\s*\\|)+\\s*$/
1149
+ const FENCE = /^\\s*(\`\`\`|~~~)/
1150
+
1151
+ /** Where each block sits in the report, in the order the server writes them. */
1152
+ const PLACE = { score: 1, reading: 2, stats: 3, recheck: 4, findings: 5, open: 6, outside: 7, steps: 8, footer: 9, share: 10 }
1153
+
1154
+ /** 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 }
1156
+
1157
+ /** The line under a score one proof from 5. */
1158
+ const READING = /^one proof from \\d\\/5$/
1159
+
1160
+ /** What a first result leaves open, in its own line: ways not tried yet, things the agent said, checks still running. */
1161
+ const OPEN = /^(?:Canary also found \\d|\\d+ things? your agent said|\\d+ checks? still running)/
1162
+
1163
+ /** What the footer can say, each piece: the near miss, the first try, and the smaller findings in \`canary show\`. */
1164
+ const FOOTER = /^(?:You'd have pushed this|Fixed on the first try|\\d+ smaller findings?, none blocking: \`canary show [\\w-]+\`)$/
1165
+
1166
+ const pipsOf = (text: string): Pip[] => [...text].filter((char): char is Pip => '\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA'.includes(char))
1167
+
1168
+ /** Table cells, split on the pipes that aren't escaped; the escapes stay for the runs to undo. */
1169
+ const cellsOf = (line: string): string[] =>
1170
+ line
1171
+ .trim()
1172
+ .replace(/^\\|/, '')
1173
+ .replace(/(?<!\\\\)\\|\\s*$/, '')
1174
+ .split(/(?<!\\\\)\\|/)
1175
+ .map(cell => cell.trim())
1176
+
1177
+ /** A table's last line as far as its cells are whole: up to its last pipe, as the cell after it may still be arriving. */
1178
+ const toLastPipe = (line: string): string => {
1179
+ for (let at = line.length - 1; at >= 0; at--) if (line[at] === '|' && line[at - 1] !== '\\\\') return line.slice(0, at + 1)
1180
+ return ''
1181
+ }
1182
+
1183
+ const markedOf = (cell: string): Marked => {
1184
+ const found = /^([\u{1F534}\u{1F7E2}\u{1F7E1}\u26AA\u{1F7E0}\u23F3])\\s+(.*)$/u.exec(cell)
1185
+ return found === null ? { mark: null, text: cell } : { mark: found[1] as Mark, text: found[2]! }
1186
+ }
1187
+
1188
+ /**
1189
+ * Finds the report in a reply: its own text before it, the report, and the agent's text after. Null when it has none,
1190
+ * and when the heading isn't followed by the score line every report the server writes has under it: the heading alone
1191
+ * could be an agent's own words, or a report still arriving.
1192
+ */
1193
+ export function splitReport(text: string): Split | null {
1194
+ const lines = text.split('\\n')
1195
+ let fenced = false
1196
+ let start = -1
1197
+ for (let i = 0; i < lines.length; i++) {
1198
+ if (FENCE.test(lines[i]!)) fenced = !fenced
1199
+ if (!fenced && HEADING.test(lines[i]!)) {
1200
+ start = i
1201
+ break
1202
+ }
1203
+ }
1204
+ if (start < 0) return null
1205
+
1206
+ const report: Report = { verdict: HEADING.exec(lines[start]!)![1]!, score: null, blocks: [] }
1207
+ let place = 0
1208
+ let i = start + 1
1209
+ let end = i
1210
+ while (i < lines.length) {
1211
+ while (i < lines.length && lines[i]!.trim() === '') i++
1212
+ if (i >= lines.length) break
1213
+ let j = i
1214
+ while (j < lines.length && lines[j]!.trim() !== '') j++
1215
+ const took = read(lines.slice(i, j), report, place)
1216
+ if (took === null) break
1217
+ place = took
1218
+ i = j
1219
+ end = j
1220
+ }
1221
+ if (report.score === null) return null
1222
+ return { before: lines.slice(0, start).join('\\n').trim(), report, after: lines.slice(end).join('\\n').trim() }
1223
+ }
1224
+
1225
+ /** Takes one block into the report when it is the report's, after the last one read: the place it took, else null. */
1226
+ function read(block: string[], report: Report, place: number): number | null {
1227
+ const first = block[0]!.trim()
1228
+ const score = SCORE.exec(first)
1229
+ if (block.length === 1 && score !== null && place === 0) {
1230
+ report.score = {
1231
+ before: score[2] === undefined ? null : pipsOf(score[1]!),
1232
+ pips: pipsOf(score[2] ?? score[1]!),
1233
+ value: score[3]!,
1234
+ caption: score[4] || null,
1235
+ reading: null,
1236
+ }
1237
+ return PLACE.score
1238
+ }
1239
+ if (block.every(line => line.trim().startsWith('|'))) {
1240
+ const lines = [...block.slice(0, -1), toLastPipe(block[block.length - 1]!.trim())]
1241
+ const table = tableOf(lines.filter(line => !ALIGN.test(line.trim())).map(cellsOf))
1242
+ if (table === null || PLACE[table.kind] <= place) return null
1243
+ report.blocks.push(table)
1244
+ return PLACE[table.kind]
1245
+ }
1246
+ if (block.length !== 1) return null
1247
+ const italic = ITALIC_LINE.exec(first)
1248
+ if (italic !== null) {
1249
+ if (place === PLACE.score && READING.test(italic[1]!)) {
1250
+ report.score!.reading = italic[1]!
1251
+ return PLACE.reading
1252
+ }
1253
+ const pieces = italic[1]!.split(' \xB7 ')
1254
+ if (place >= PLACE.footer || !pieces.every(piece => FOOTER.test(piece))) return null
1255
+ report.blocks.push({ kind: 'note', pieces })
1256
+ return PLACE.footer
1257
+ }
1258
+ const labeled = LABELED.exec(first)
1259
+ if (labeled !== null) {
1260
+ const at = LISTS[labeled[2]!]
1261
+ if (at === undefined || at <= place) return null
1262
+ report.blocks.push({ kind: 'list', mark: (labeled[1] as Pip | undefined) ?? null, label: labeled[2]!, items: labeled[3]!.split(' \xB7 ') })
1263
+ return at
1264
+ }
1265
+ const share = SHARE.exec(first)
1266
+ if (share !== null && place < PLACE.share) {
1267
+ report.blocks.push({ kind: 'share', text: share[1]! })
1268
+ return PLACE.share
1269
+ }
1270
+ if (OPEN.test(first) && place < PLACE.open) {
1271
+ report.blocks.push({ kind: 'open', text: first })
1272
+ return PLACE.open
1273
+ }
1274
+ return null
1275
+ }
1276
+
1277
+ /** The table as one of the report's blocks; null when it is none of them. */
1278
+ function tableOf(rows: string[][]): Extract<Block, { kind: 'stats' | 'findings' | 'recheck' }> | null {
1279
+ const [head, ...body] = rows
1280
+ if (head === undefined) return null
1281
+ // A last row with fewer cells than the head is one still arriving.
1282
+ if (body.length > 0 && body[body.length - 1]!.length < head.length) body.pop()
1283
+ // The counts: a row of bold numbers over a row of what each counts, which may still be on its way.
1284
+ if (body.length <= 1 && head.every(cell => /^\\*\\*[^*]+\\*\\*$/.test(cell)) && (body[0] === undefined || body[0].length === head.length)) {
1285
+ return { kind: 'stats', items: head.map((cell, at) => ({ value: cell.slice(2, -2), label: body[0]?.[at] ?? '' })) }
1286
+ }
1287
+ if (head.length === 3 && head[0] === '' && body.every(row => row.length === 3)) {
1288
+ return { kind: 'findings', header: head.filter(cell => cell !== ''), rows: body.map(([status, what, how]) => ({ status: markedOf(status!), what: what!, how: how! })) }
1289
+ }
1290
+ if (head.length === 3 && head[0] !== '' && body.length > 0 && body.every(row => row.length === 3 && markedOf(row[1]!).mark !== null && markedOf(row[2]!).mark !== null)) {
1291
+ return { kind: 'recheck', header: head, rows: body.map(([what, before, now]) => ({ what: what!, before: markedOf(before!), now: markedOf(now!) })) }
1292
+ }
1293
+ return null
1294
+ }
255
1295
  `,"canary/scripts/verifier-hook.sh":`#!/bin/sh
256
1296
  # Hands the Canary CLI the hook events it acts on: a Canary verifier's tool calls and the call that starts
257
1297
  # one, the user answering a question dialog or typing a message, and a permission prompt about one of
@@ -388,52 +1428,52 @@ When the final report arrives, close with one short message, and write nothing a
388
1428
  - Don't stop processes or remove containers a verifier started; \`canary jobs finish\` does that.
389
1429
  - 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.
390
1430
  - 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.
391
- `}});var Nr=dn(Ni=>{w();var Us=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 Us{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ni.CommanderError=Us;Ni.InvalidArgumentError=ji});var qs=dn(Mi=>{w();var{InvalidArgumentError:jy}=Nr(),Pi=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 Ny(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Mi.Argument=Pi;Mi.humanReadableArgName=Ny});var Di=dn(Jl=>{w();var{humanReadableArgName:Py}=qs(),Li=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=>Py(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(`
1431
+ `}});var jr=dn(ji=>{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}},_i=class extends Bs{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ji.CommanderError=Bs;ji.InvalidArgumentError=_i});var Us=dn(Mi=>{w();var{InvalidArgumentError:_y}=jr(),Pi=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 _y(`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 jy(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Mi.Argument=Pi;Mi.humanReadableArgName=jy});var Fi=dn(Gl=>{w();var{humanReadableArgName:Py}=Us(),Li=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=>Py(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(`
392
1432
  `).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(`
393
1433
  `)}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
394
1434
  `,`
395
1435
  `),d=" ".repeat(r),h="\\s\u200B",p=new RegExp(`
396
1436
  |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=l.match(p)||[];return c+f.map((g,m)=>g===`
397
1437
  `?"":(m>0?d:"")+g.trimEnd()).join(`
398
- `)}};Jl.Help=Li});var qi=dn(Ui=>{w();var{InvalidArgumentError:My}=Nr(),Fi=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 My(`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 Ly(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Hi=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 Ly(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=Fi;Ui.DualOptions=Hi});var Vl=dn(Gl=>{w();function Fy(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 Hy(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=Fy(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?`
1438
+ `)}};Gl.Help=Li});var Ui=dn(Bi=>{w();var{InvalidArgumentError:My}=jr(),Di=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=Fy(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 My(`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 Ly(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Wi=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 Ly(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function Fy(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}}Bi.Option=Di;Bi.DualOptions=Wi});var Yl=dn(Jl=>{w();function Dy(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 Wy(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=Dy(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?`
399
1439
  (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
400
- (Did you mean ${r[0]}?)`:""}Gl.suggestSimilar=Hy});var Xl=dn(Ql=>{w();var Uy=jr("node:events").EventEmitter,Bi=jr("node:child_process"),$t=jr("node:path"),Wi=jr("node:fs"),he=jr("node:process"),{Argument:qy,humanReadableArgName:By}=qs(),{CommanderError:Ji}=Nr(),{Help:Wy}=Di(),{Option:Kl,DualOptions:Jy}=qi(),{suggestSimilar:Yl}=Vl(),Gi=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 Wy,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
401
- - 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}'.
402
- 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}'
403
- - 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=$t.resolve(d,u);if(Wi.existsSync(h))return h;if(s.includes($t.extname(u)))return;let p=s.find(f=>Wi.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=Wi.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=$t.resolve($t.dirname(d),a)}if(a){let d=o(a,i);if(!d&&!t._executableFile&&this._scriptPath){let u=$t.basename(this._scriptPath,$t.extname(this._scriptPath));u!==this._name&&(d=o(a,`${u}-${t._name}`))}i=d||i}r=s.includes($t.extname(i));let c;he.platform!=="win32"?r?(n.unshift(i),n=zl(he.execArgv).concat(n),c=Bi.spawn(he.argv[0],n,{stdio:"inherit"})):c=Bi.spawn(i,n,{stdio:"inherit"}):(n.unshift(i),n=zl(he.execArgv).concat(n),c=Bi.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
1440
+ (Did you mean ${r[0]}?)`:""}Jl.suggestSimilar=Wy});var Zl=dn(Xl=>{w();var By=_r("node:events").EventEmitter,Hi=_r("node:child_process"),It=_r("node:path"),qi=_r("node:fs"),he=_r("node:process"),{Argument:Uy,humanReadableArgName:Hy}=Us(),{CommanderError:Gi}=jr(),{Help:qy}=Fi(),{Option:Vl,DualOptions:Gy}=Ui(),{suggestSimilar:Kl}=Yl(),Ji=class e extends By{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 qy,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
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 Uy(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}'.
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 Gi(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 Vl(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}'
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 Vl)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(qi.existsSync(h))return h;if(s.includes(It.extname(u)))return;let p=s.find(f=>qi.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=qi.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=zl(he.execArgv).concat(n),c=Hi.spawn(he.argv[0],n,{stdio:"inherit"})):c=Hi.spawn(i,n,{stdio:"inherit"}):(n.unshift(i),n=zl(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 Gi(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
404
1444
  - if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
405
1445
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
406
- - ${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}
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 Gi(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}
407
1447
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
408
1448
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
409
- `),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=Yl(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=Yl(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}
410
- `),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=>By(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=$t.basename(t,$t.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.
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 Gy(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=Kl(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=Kl(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
+ `),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.
411
1451
  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}
412
- `)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function zl(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})}Ql.Command=Gi});var nu=dn(et=>{w();var{Argument:Zl}=qs(),{Command:Vi}=Xl(),{CommanderError:Gy,InvalidArgumentError:eu}=Nr(),{Help:Vy}=Di(),{Option:tu}=qi();et.program=new Vi;et.createCommand=e=>new Vi(e);et.createOption=(e,t)=>new tu(e,t);et.createArgument=(e,t)=>new Zl(e,t);et.Command=Vi;et.Option=tu;et.Argument=Zl;et.Help=Vy;et.CommanderError=Gy;et.InvalidArgumentError=eu;et.InvalidOptionArgumentError=eu});import{execFileSync as Ky}from"node:child_process";import{randomUUID as Yy}from"node:crypto";import{chmodSync as zy,mkdirSync as zi,readFileSync as Qi,renameSync as Qy,rmSync as au,statSync as Xy,writeFileSync as cu}from"node:fs";import{homedir as Zy}from"node:os";import{dirname as lu,join as Xi}from"node:path";function Y(){return process.env.CANARY_HOME||Xi(Zy(),".canary")}function Zi(){return Xi(Y(),"config.json")}function uu(){let{config:e}=ta();if(e.installId&&ou.test(e.installId))return e.installId;iu??=Yy();let t=iu;try{Te(n=>n.installId&&ou.test(n.installId)?n:{...n,installId:t})}catch{}return t}function K(){return ta().config}function du(e){return K().repoFingerprints?.[e]}function hu(e,t){try{Te(n=>({...n,repoFingerprints:{...n.repoFingerprints,[e]:t}}))}catch{}}function pu(e){fu=e}function gu(){return`${Zi()}.lock`}function iw(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function It(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 lw(e){let t;try{t=Qi(ea(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=It(n);return s===null?!0:Math.abs(s-r)<=cw}function yu(e){try{return Qi(ea(e),"utf8").trim()===mu}catch{return!1}}function Ki(e){try{au(e,{recursive:!0,force:!0})}catch{}}function wu(e=gu(),t="the config lock"){let n=Date.now()+ow();for(;;)try{return zi(lu(e),{recursive:!0,mode:448}),zi(e),cu(ea(e),`${mu}
413
- `,{flag:"wx"}),()=>{yu(e)&&Ki(e)}}catch(r){if(r.code!=="EEXIST")throw r;let s=lw(e);if(s===!1){Ki(e);continue}if(s==="unknown")try{if(Date.now()-Xy(e).mtimeMs>rw){Ki(e);continue}}catch{}if(Date.now()>=n)throw new hn(`another canary process is holding ${t}`);iw(sw)}}function Pr(e,t,n){let r=wu(e,t);try{return n()}finally{r()}}function Te(e,t={}){let n=()=>{let{config:s,unreadable:o}=ta();if(o&&!t.overwriteUnreadable)return!1;let i=e(o?{}:s);if(!yu(gu()))throw new hn("the config lock changed hands during the write");return uw(i),!0};if(Yi>0)return n();let r=wu();Yi+=1;try{return n()}finally{Yi-=1,r()}}function ta(){let e;try{e=Qi(Zi(),"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 uw(e){let t=Zi();zi(lu(t),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;try{cu(n,JSON.stringify(e,null,2)+`
414
- `,{mode:384}),zy(n,384),Qy(n,t)}catch(r){throw au(n,{force:!0}),r}}function bu(){Te(({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 ne(){return process.env.CANARY_TOKEN||K().token}function ue(){return process.env.CANARY_API_URL||K().apiUrl||ew}function At(){let e=process.env.CANARY_WEB_URL||K().webUrl;if(e)return e;let t=process.env.CANARY_API_URL||K().apiUrl;return t?t.replace("//api.","//www."):tw}var ew,tw,ou,iu,hn,nw,rw,sw,fu,ow,ea,aw,mu,cw,Yi,Z=X(()=>{"use strict";w();ew="https://api.runcanary.ai",tw="https://www.runcanary.ai";ou=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,iu=null;hn=class extends Error{constructor(t="another canary process is holding the config lock"){super(`${t}; run the command again`),this.name="ConfigLockError"}},nw=15e3,rw=1e4,sw=20;ow=()=>fu??(Number(process.env.CANARY_CONFIG_LOCK_WAIT_MS)||nw);ea=e=>Xi(e,"owner");aw=Math.round(Date.now()-process.uptime()*1e3),mu=`${process.pid} ${aw}`,cw=3e3;Yi=0});function dw(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function hw(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+=`
1452
+ `)}),this}_outputHelpIfRequested(t){let n=this._getHelpOption();n&&t.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function zl(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})}Xl.Command=Ji});var nu=dn(et=>{w();var{Argument:Ql}=Us(),{Command:Yi}=Zl(),{CommanderError:Jy,InvalidArgumentError:eu}=jr(),{Help:Yy}=Fi(),{Option:tu}=Ui();et.program=new Yi;et.createCommand=e=>new Yi(e);et.createOption=(e,t)=>new tu(e,t);et.createArgument=(e,t)=>new Ql(e,t);et.Command=Yi;et.Option=tu;et.Argument=Ql;et.Help=Yy;et.CommanderError=Jy;et.InvalidArgumentError=eu;et.InvalidOptionArgumentError=eu});import{execFileSync as Vy}from"node:child_process";import{randomUUID as Ky}from"node:crypto";import{chmodSync as zy,mkdirSync as zi,readFileSync as Xi,renameSync as Xy,rmSync as au,statSync as Zy,writeFileSync as cu}from"node:fs";import{homedir as Qy}from"node:os";import{dirname as lu,join as Zi}from"node:path";function K(){return process.env.CANARY_HOME||Zi(Qy(),".canary")}function Qi(){return Zi(K(),"config.json")}function uu(){let{config:e}=ta();if(e.installId&&ou.test(e.installId))return e.installId;iu??=Ky();let t=iu;try{Ne(n=>n.installId&&ou.test(n.installId)?n:{...n,installId:t})}catch{}return t}function V(){return ta().config}function du(e){return V().repoFingerprints?.[e]}function hu(e,t){try{Ne(n=>({...n,repoFingerprints:{...n.repoFingerprints,[e]:t}}))}catch{}}function pu(e){fu=e}function gu(){return`${Qi()}.lock`}function iw(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Rt(e){try{let t=Vy("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 lw(e){let t;try{t=Xi(ea(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)<=cw}function yu(e){try{return Xi(ea(e),"utf8").trim()===mu}catch{return!1}}function Vi(e){try{au(e,{recursive:!0,force:!0})}catch{}}function wu(e=gu(),t="the config lock"){let n=Date.now()+ow();for(;;)try{return zi(lu(e),{recursive:!0,mode:448}),zi(e),cu(ea(e),`${mu}
1453
+ `,{flag:"wx"}),()=>{yu(e)&&Vi(e)}}catch(r){if(r.code!=="EEXIST")throw r;let s=lw(e);if(s===!1){Vi(e);continue}if(s==="unknown")try{if(Date.now()-Zy(e).mtimeMs>rw){Vi(e);continue}}catch{}if(Date.now()>=n)throw new hn(`another canary process is holding ${t}`);iw(sw)}}function Pr(e,t,n){let r=wu(e,t);try{return n()}finally{r()}}function Ne(e,t={}){let n=()=>{let{config:s,unreadable:o}=ta();if(o&&!t.overwriteUnreadable)return!1;let i=e(o?{}:s);if(!yu(gu()))throw new hn("the config lock changed hands during the write");return uw(i),!0};if(Ki>0)return n();let r=wu();Ki+=1;try{return n()}finally{Ki-=1,r()}}function ta(){let e;try{e=Xi(Qi(),"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 uw(e){let t=Qi();zi(lu(t),{recursive:!0,mode:448});let n=`${t}.${process.pid}.tmp`;try{cu(n,JSON.stringify(e,null,2)+`
1454
+ `,{mode:384}),zy(n,384),Xy(n,t)}catch(r){throw au(n,{force:!0}),r}}function bu(){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 ne(){return process.env.CANARY_TOKEN||V().token}function ue(){return process.env.CANARY_API_URL||V().apiUrl||ew}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."):tw}var ew,tw,ou,iu,hn,nw,rw,sw,fu,ow,ea,aw,mu,cw,Ki,Q=Z(()=>{"use strict";w();ew="https://api.runcanary.ai",tw="https://www.runcanary.ai";ou=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,iu=null;hn=class extends Error{constructor(t="another canary process is holding the config lock"){super(`${t}; run the command again`),this.name="ConfigLockError"}},nw=15e3,rw=1e4,sw=20;ow=()=>fu??(Number(process.env.CANARY_CONFIG_LOCK_WAIT_MS)||nw);ea=e=>Zi(e,"owner");aw=Math.round(Date.now()-process.uptime()*1e3),mu=`${process.pid} ${aw}`,cw=3e3;Ki=0});function dw(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function hw(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+=`
415
1455
  `,i===t&&(s+=" ".repeat(o+n+2),s+=`^
416
- `))}return s}var H,fn=X(()=>{w();H=class e extends Error{line;column;codeblock;constructor(t,n){let[r,s]=dw(n.toml,n.ptr),o=hw(n.toml,r,s);super(`Invalid TOML document: ${t}
1456
+ `))}return s}var W,fn=Z(()=>{w();W=class e extends Error{line;column;codeblock;constructor(t,n){let[r,s]=dw(n.toml,n.ptr),o=hw(n.toml,r,s);super(`Invalid TOML document: ${t}
417
1457
 
418
- ${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 Bs(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)H.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&&H.x("invalid non-hex character in unicode escape",e),d=d<<4|f}(d<0||d>1114111||d>=55296&&d<=57343)&&H.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+=`
419
- `:n===102?i+="\f":n===114?i+="\r":n===101?i+="\x1B":n===34?i+='"':n===92?i+="\\":H.x("unrecognised escape sequence",e),a=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&H.x("invalid escape: only line-ending whitespace may be escaped",e,a),c=!s&&n===92?1:0,a=e.p);H.x("unfinished string",e,t)}var na=X(()=>{w();fn();});var fw,Mr,ra=X(()=>{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 Ke(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 Dr(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||H.x("document contains excessively nested structures. aborting.",e);let s=r===91?Su(e):vu(e);return e.d++,s}return r===34||r===39?Bs(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&H.x("invalid value",e,n),e.p++,!0):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)&&H.x("invalid value",e,n),e.p++,!1):r===43||r===45?Ws(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):Ws(e,e.p,r,0,t)}function Ws(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)&&H.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)&&H.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:H.x("illegal leading zero",e,t)}else Ke(o)||H.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||H.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)||(Ke(o)?i>9?i-=11:i&1||i++:H.x("illegal character in numeric literal",e));if(!i){let l=(n-48)*(r||1);return e.bi===!0?BigInt(l):l}i&1||H.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&&H.x("illegal underscore",e),o=3):Ke(s,n)?o&1&&o--:H.x("illegal character in numeric literal",e);o&1&&H.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;H.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(!Ke(t)||!Ke(e.s.charCodeAt(e.p++))||!Ke(e.s.charCodeAt(e.p++))||!Ke(e.s.charCodeAt(e.p++)))return Ws(e,e.p=r,t,0,n);if(e.p+=5,Ke(e.s.charCodeAt(e.p++))||H.x("invalid date-time: date part is malformed",e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(s=!0,!Ke(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&&H.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(;Ke(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(!Ke(t)||!Ke(e.s.charCodeAt(++e.p)))return Ws(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;Ke(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()||H.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){H.x(i instanceof Error?i.message:""+i,e,s)}}var ia=X(()=>{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)&&H.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=X(()=>{w();fn();});function Js(e,t=61){let n,r=0,s=[],o,i=e.s.charCodeAt(n=e.p);do{if(i===t)return r||H.x("unexpected end of key",e),r===1&&s.push(e.s.slice(o,e.p)),e.p++,s;i===46?(r||H.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)&&H.x("illegal quoted key: multiline strings are not allowed",e),s.push(Bs(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?H.x("illegal character in key",e):r||(r=1,o=e.p)}while(i=e.s.charCodeAt(++e.p));H.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=Js(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]))&&H.x("trying to redefine an already defined value",e,c);let h=o==="__proto__";if(e.uk&&(h||o==="constructor")){i=e.uk!==1&&H.x("document contains an unsafe property",e,c);break}!a&&h&&Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0})}a&&H.x("trying to redefine an already defined value",e,c),lt(e,!0,!0);let d=Dr(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&&H.x("expected comma or end of structure",e,e.p-1)}H.x("unfinished table",e,t)}function Su(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(Dr(e,93)),lt(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&H.x("expected comma or end of structure",e,e.p-1)}H.x("unfinished array",e,t)}var aa=X(()=>{w();na();ia();ca();fn();});function xu(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)&&H.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=Js(n,93);l&&(e.charCodeAt(n.p)!==93&&H.x("expected end of table array declaration",n),n.p++);let u=xu(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=Js(n),d=xu(n,l,a,c,0);!d&&!i&&Cu(n,d,o),lt(n,!0,!0);let u=Dr(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)&&H.x("each key-value declaration must be followed by an end-of-line",n),lt(n)}return r}var _u=X(()=>{w();aa();ia();ca();fn();});var XA,$u=X(()=>{w();XA=!!"".isWellFormed});var Iu=X(()=>{w();_u();$u();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 Sw,closeSync as xw,constants as ha,existsSync as Cw,fstatSync as _w,lstatSync as Tu,mkdirSync as $w,mkdtempSync as Iw,openSync as Aw,readFileSync as ju,readlinkSync as Rw,realpathSync as Au,renameSync as Ew,rmSync as Mt,statSync as Gs,writeFileSync as fa}from"node:fs";import{tmpdir as Ow}from"node:os";import{basename as Tw,delimiter as jw,dirname as Vs,join as Bn,resolve as Nw}from"node:path";function Wn(e){try{return{doc:la(e,{integersAsBigInt:"asNeeded"})}}catch(t){let n=(t instanceof Error?t.message:String(t)).split(`
420
- `)[0].replace(/^Invalid TOML document:\s*/,"");return{problem:{line:t instanceof H?t.line:0,message:n}}}}function Mw(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!Tu(t).isSymbolicLink())return t;r=Rw(t)}catch{return t}t=Nw(Vs(t),r)}throw new Error("its symlinks do not end anywhere")}function Ks(e){let t;try{t=Mw(e)}catch(d){return{unreadable:d.message}}let n=null,r=null;try{let d=Aw(t,"r");try{r=Pw(_w(d,{bigint:!0})),n=ju(d)}finally{xw(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=Lw.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(`
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 Hs(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)W.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&&W.x("invalid non-hex character in unicode escape",e),d=d<<4|f}(d<0||d>1114111||d>=55296&&d<=57343)&&W.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+=`
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 W?t.line:0,message:n}}}}function Mw(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!Nu(t).isSymbolicLink())return t;r=Ew(t)}catch{return t}t=jw(Ys(t),r)}throw new Error("its symlinks do not end anywhere")}function Vs(e){let t;try{t=Mw(e)}catch(d){return{unreadable:d.message}}let n=null,r=null;try{let d=Tw(t,"r");try{r=Pw(Aw(d,{bigint:!0})),n=_u(d)}finally{Sw(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=Lw.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(`
421
1461
  `),c=a>0&&i[a-1]==="\r"?`\r
422
1462
  `:`
423
- `,l=n?Wn(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 ut(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(ut).join(",")}]`:Ee(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ut(e[t])}`).join(",")}}`:JSON.stringify(e)}function Pu(e,t,n=[]){return Ee(e)&&Ee(t)?[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Pu(e[r],t[r],[...n,r])):ut(e)===ut(t)?[]:[{path:n,a:e,b:t}]}function Fr(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
1463
+ `,l=n?qn(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 ut(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(ut).join(",")}]`:Oe(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ut(e[t])}`).join(",")}}`:JSON.stringify(e)}function Pu(e,t,n=[]){return Oe(e)&&Oe(t)?[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Pu(e[r],t[r],[...n,r])):ut(e)===ut(t)?[]:[{path:n,a:e,b:t}]}function Dr(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`
424
1464
  `,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
425
1465
  `:`
426
- `}),n=r+1}return t}function Mu(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:""}),pa(n)}function Bw(e,t){if(!e.doc)return null;let n=t[t.length-1],r=new RegExp(`(?:^|[\\s.{,])${Ys(n)}[ \\t]*=`),s=ut(Ru(e.doc,t)),o=Fr(e.text);for(let[i,a]of o.entries()){if(!r.test(a.content))continue;let c=Wn(Mu(o,i));if("doc"in c&&ut(Ru(c.doc,t))!==s)return i+1}return null}function Ru(e,t){let n=e;for(let r of t){if(!Ee(n))return;n=n[r]}return n}function Ww(e){let t=e.doc;if(!t)return[];let n=[],r=(s,o,i)=>{if(Ee(s))for(let a of["hooks","codex_hooks"])a in s&&n.push({key:a,value:s[a],profile:i,line:Bw(e,[...o,a])})};if(r(t.features,["features"],null),Ee(t.profiles))for(let[s,o]of Object.entries(t.profiles))Ee(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]
427
- ${je}
1466
+ `}),n=r+1}return t}function Mu(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:""}),pa(n)}function Hw(e,t){if(!e.doc)return null;let n=t[t.length-1],r=new RegExp(`(?:^|[\\s.{,])${Ks(n)}[ \\t]*=`),s=ut(Eu(e.doc,t)),o=Dr(e.text);for(let[i,a]of o.entries()){if(!r.test(a.content))continue;let c=qn(Mu(o,i));if("doc"in c&&ut(Eu(c.doc,t))!==s)return i+1}return null}function Eu(e,t){let n=e;for(let r of t){if(!Oe(n))return;n=n[r]}return n}function qw(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 Gw(e){if(!e.doc)return{refused:"it does not parse as TOML"};if(!e.raw)return{text:`[features]
1467
+ ${_e}
428
1468
  `,line:2,added:`[features]
429
- ${je}
430
- `,shape:"new_file"};let t=ut(Dw(e.doc)),n=d=>{let u=Wn(d);return"doc"in u&&ut(u.doc)===t},r=Fr(e.text),s=(d,u,h)=>{let p=pa(r.slice(0,d+1)),f=pa(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(Ee(e.doc.features)){for(let[d,u]of r.entries())Hw.test(u.content)&&o.push(s(d,je,"under_header"));for(let[d,u]of r.entries())Uw.test(u.content)&&o.push(s(d,Hr,"dotted"))}let i=e.text,a=e.eol,c=i?/\n\s*\n$/.test(i)?`[features]${a}${je}${a}`:i.endsWith(`
431
- `)?`${a}[features]${a}${je}${a}`:`${a}${a}[features]${a}${je}`:`[features]${a}${je}${a}`;o.push({text:i+c,line:Fw(i+c.slice(0,c.indexOf(je)))+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 Lu(e,t){if(!e.raw)return null;if(!e.doc)return Fr(e.text).some(c=>[je,Hr].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=Fr(r),i=[];for(let c=o.length-1;c>=0;c--){let l=o[c].content.trim();if(l!==je&&l!==Hr)continue;let d=Mu(o,c),u=Wn(d);if(!("doc"in u))continue;let h=Pu(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=Fr(r))}if(!i.length)return null;let a=!1;if(n?.added.includes("[features]")&&Ee(s.features)){let c=new Set([ut(s),...Object.keys(s.features).length?[]:[ut(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:Wn(d);d!==null&&u&&"doc"in u&&c.has(ut(u.doc))&&(r=d,a=!0)}return{text:n?.created&&!r.trim()?null:r,lines:i.sort((c,l)=>c-l),header:a}}function Fu(e){if(e.dangling)return"it is a symlink to a file that does not exist";if(e.raw){let t;try{t=Gs(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{da(e.target,ha.W_OK)}catch{return"it is read-only"}}try{da(Vs(e.target),ha.W_OK)}catch{return`its folder (${Vs(e.target)}) is read-only`}return null}function Gw(e){let t;try{t=Tu(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 ju(e.target).equals(e.raw)}catch{return!1}}function ga(e,t,n){let r=Fu(e);if(r)return{refused:r};let s=e.identity?e.identity.mode&4095:384,o=null;if(e.raw)try{$w(n,{recursive:!0,mode:448}),o=Bn(n,`codex-config.toml.${new Date().toISOString().replace(/[:.]/g,"-")}.${bw(3).toString("hex")}.bak`),fa(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=Bn(Vs(e.target),`.${Tw(e.target)}.${kw()}.canary.tmp`);try{if(t!==null){if(fa(i,Buffer.from((e.bom?"\uFEFF":"")+t,"utf8"),{flag:"wx",mode:s}),e.identity&&Gs(i).gid!==e.identity.gid)try{Sw(i,-1,e.identity.gid)}catch{}vw(i,s);let a=Gs(i);if(e.identity&&(a.gid!==e.identity.gid||(a.mode&4095)!==s))return Mt(i,{force:!0}),o&&Mt(o,{force:!0}),{refused:"its group or permissions could not be kept on a replacement"}}return Gw(e)?(t===null?Mt(e.target):Ew(i,e.target),{backup:o}):(Mt(i,{force:!0}),o&&Mt(o,{force:!0}),{refused:"it changed while Canary was editing it",changed:!0})}catch(a){Mt(i,{force:!0}),o&&Mt(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 ma(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=Bn(s,o);try{if(da(i,ha.X_OK),Gs(i).isFile()){n.push(i);break e}}catch{}}return t==="darwin"&&Cw(ua)&&!n.some(s=>Vw(s,ua))&&n.push(ua),n}function Vw(e,t){try{return Au(e)===Au(t)}catch{return e===t}}function Ou(e,t,n){let r=`${e}\0${t?ww("sha256").update(t).digest("hex"):"-"}`,s=Eu.get(r);if(s)return s;let o=Iw(Bn(Ow(),"canary-codex-")),i;try{t&&fa(Bn(o,"config.toml"),t,{mode:384});let a=process.platform==="win32"&&/\.(cmd|bat)$/i.test(e),c=yw(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(`
432
- `)[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{Mt(o,{recursive:!0,force:!0})}return Eu.set(r,i),i}function Yw(e,t,n){let r=e,s=n&&typeof n.profile=="string"&&Ee(n.profiles)?n.profiles[n.profile]:void 0;for(let o of[n?.features,Ee(s)?s.features:void 0])Ee(o)&&(typeof o.codex_hooks=="boolean"&&(r=o.codex_hooks),t==="hooks"&&typeof o.hooks=="boolean"&&(r=o.hooks));return r}function Hu(e,t=Kw){return({raw:n,doc:r})=>{let s={answers:[],unanswered:[]};for(let o of e){let i=Ou(o,n,t);if("key"in i){s.answers.push({binary:o,...i,derived:!1});continue}let a=n?Ou(o,null,t):i;"key"in a?s.answers.push({binary:o,key:a.key,on:Yw(a.on,a.key,r),derived:!0}):s.unanswered.push({binary:o,why:i.why})}return s}}function ya(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=Ww(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=Fu(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:Wn(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 Nu,je,Hr,Pw,Ee,Lw,Dw,pa,Fw,Ys,Hw,Uw,qw,zs,Du,ua,Kw,Eu,Uu=X(()=>{"use strict";w();Iu();Nu="# added by canary",je=`codex_hooks = true ${Nu}`,Hr=`features.codex_hooks = true ${Nu}`,Pw=e=>({dev:e.dev,ino:e.ino,mode:Number(e.mode),uid:Number(e.uid),gid:Number(e.gid)}),Ee=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Date);Lw=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Dw=e=>({...e,features:{...Ee(e.features)?e.features:{},codex_hooks:!0}});pa=e=>e.map(t=>t.content+t.eol).join("");Fw=e=>e.split(`
433
- `).length-1,Ys=e=>`(?:${e}|"${e}"|'${e}')`,Hw=new RegExp(`^[ \\t]*\\[[ \\t]*${Ys("features")}[ \\t]*\\][ \\t]*(?:#.*)?$`),Uw=new RegExp(`^[ \\t]*${Ys("features")}[ \\t]*\\.`),qw=new RegExp(`^[ \\t]*${Ys("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}")`:""}`;Du=e=>Bn(e,"backups");ua="/Applications/ChatGPT.app/Contents/Resources/codex";Kw=3e3,Eu=new Map});import{accessSync as zw,constants as Qw,existsSync as Br,lstatSync as Xw,readFileSync as Qs,readlinkSync as Zw,renameSync as eb,rmSync as qu,statSync as Ku,writeFileSync as tb}from"node:fs";import{randomUUID as nb}from"node:crypto";import{homedir as ka}from"node:os";import{delimiter as rb,dirname as wa,join as mt,resolve as sb}from"node:path";function Zs(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(rb).filter(Boolean))for(let o of r)try{if(zw(mt(s,o),Qw.X_OK),Ku(mt(s,o)).isFile())return!0}catch{}return!1}function ob(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!Xw(t).isSymbolicLink())return t;r=Zw(t)}catch{return t}t=sb(wa(t),r)}throw new dt("its symlinks do not end anywhere")}function Jn(e,t){for(let n=0;n<3;n++){let r;try{r=Qs(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 dt)return{result:"refused",detail:c.message};throw c}let o=r?/^([ \t]+)"/m.exec(r)?.[1]??" ":" ",i;try{i=ob(e)}catch(c){return{result:"refused",detail:c.message}}if(i!==e&&!Br(wa(i)))return{result:"refused",detail:"it is a symlink into a folder that does not exist"};let a=mt(wa(i),`.${nb()}.canary.tmp`);try{tb(a,JSON.stringify(s,null,o)+`
434
- `,{flag:"wx",mode:r===null?384:Ku(i).mode&511});let c;try{c=Qs(e,"utf8")}catch{c=null}if(c!==r){qu(a,{force:!0});continue}return eb(a,i),{result:"written"}}catch(c){return qu(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 ab(e,t,n){for(let r of e){if(!yt(r))throw new dt(`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 dt(`its \`hooks.${t}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Lt(e,t,n,r="hooks"){if(e.hooks===void 0){if(!n)return null;e.hooks={}}if(!yt(e.hooks))throw new dt("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 dt(`its \`hooks.${t}\` entry is not a list`);return ab(e.hooks[t],t,r),e.hooks[t]}function Yu(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(Qs(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=ib(e.harness),n=va(e.harness),r=()=>({matcher:e.matcher,hooks:[{type:"command",command:t,timeout:Xs}]}),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=Lt(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&&Yu(c,"PreToolUse"),d},a={harness:e.harness,file:e.file,summary:`a PreToolUse hook that runs \`${t}\` before shell and MCP tool calls (${Xs} s limit)`,snippet:JSON.stringify({hooks:{PreToolUse:[r()]}},null,2)};return{detected:()=>Br(e.dir),plan:()=>[a],install:()=>[{...a,...Jn(e.file,c=>o(Lt(c,"PreToolUse",!0))?!1:(i(c),Lt(c,"PreToolUse",!0).push(r()),!0))}],uninstall:()=>{if(!Br(e.file))return[{...a,result:"unchanged"}];let c=Jn(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=Lt(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 cb(e){let t=mt(e,"hooks.json"),n=va("cursor"),r=()=>({command:"canary hook cursor",timeout:Xs}),s=a=>Ur.every(c=>{let l=(Lt(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=Lt(a,l,!1,null);if(!d)continue;let u=d.filter(h=>!n(h));u.length!==d.length&&(c=!0,a.hooks[l]=u,Yu(a,l))}return c},i={harness:"cursor",file:t,summary:`a command that runs \`canary hook cursor\` before shell commands and MCP tool calls (${Xs} s limit)`,snippet:JSON.stringify({version:1,hooks:Object.fromEntries(Ur.map(a=>[a,[r()]]))},null,2)};return{detected:()=>Br(e),plan:()=>[i],install:()=>[{...i,...Jn(t,a=>{if(a.version!==void 0&&a.version!==1)throw new dt(`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)Lt(a,c,!0,null).push(r());return!0})}],uninstall:()=>{if(!Br(t))return[{...i,result:"unchanged"}];let a=Jn(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=>(Lt(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 ub(e=process.env){let t=e.CLAUDE_CONFIG_DIR||mt(ka(),".claude");return{id:"claude",label:"Claude Code",byDefault:!0,...Qu({harness:"claude",dir:t,file:mt(t,"settings.json"),matcher:lb,disabledKey:"disableAllHooks"})}}function db(e=process.env,t=process.platform){let[n]=ma(e,t);return n===void 0?null:/[\s"']/.test(n)?`"${n}"`:n}function fb(e,t,n){if("unreadable"in e||!e.doc)return null;let r=e.doc.hooks,s=Ee(r)&&Ee(r.state)?r.state[`${t}:pre_tool_use:${n}:0`]:void 0;return Ee(s)&&typeof s.trusted_hash=="string"}function Vu(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)?`${Xu(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 mb(e=process.env,t={}){let n=e.CODEX_HOME||mt(ka(),".codex"),r=mt(n,"hooks.json"),s=Qu({harness:"codex",dir:n,file:r,matcher:".*"}),o=mt(n,"config.toml"),i=hb(db(e)),a=t.ask??Hu(ma(e)),c=va("codex"),l=()=>Du(Y()),d=()=>{try{return JSON.parse(Qs(r,"utf8")).hooks.PreToolUse.findIndex(S=>yt(S)&&Array.isArray(S.hooks)&&S.hooks.some(c))}catch{return-1}},u=()=>{let x=Ks(o);return{read:x,verdict:ya(x,a)}},h=()=>{try{return K().hooks?.codex??null}catch{return null}},p=x=>{try{Te(S=>{let{codex:v,...$}=S.hooks??{};return{...S,hooks:x?{...$,codex:x}:$}})}catch{}},f=(x,S)=>({harness:"codex",file:o,summary:`the line \`${pn(x)}\` ${pb(x)}${S?`, because ${qr(S)}`:""}`,snippet:x.shape==="new_table"||x.shape==="new_file"?`[features]
435
- ${je}`:pn(x)}),g={harness:"codex",file:o,summary:`the line \`${je}\` under \`[features]\``,snippet:`[features]
436
- ${je}`},m={harness:"codex",file:o,summary:"`codex_hooks = true` inside the inline `features = { \u2026 }` table",snippet:"features = { \u2026, codex_hooks = true }"},C=(x,S)=>S.kind==="cannot"?{...S.edit?f(S.edit):S.inline?m:g,result:"refused",detail:`${S.why}; ${qr(S)}`}:S.kind==="broken"?{...g,result:"refused",detail:Gu(x)}:S.kind==="unreadable"?{...g,result:"refused",detail:S.why}:null,_=()=>{for(let x=0;x<3;x++){let{read:S,verdict:v}=u();if(v.kind!=="edit")return C(S,v);let $=v.edit,O=ga(S,$.text,l());if("backup"in O)return p({file:S.target,added:$.added,line:pn($),at:new Date().toISOString(),...$.shape==="new_file"?{created:!0}:{},...O.backup?{backup:O.backup}:{}}),{...f($,v),result:"written",detail:`line ${$.line} now reads \`${pn($)}\`, because ${qr(v)}`,edit:{line:$.line,text:pn($),backup:O.backup,created:$.shape==="new_file"}};if(!O.changed)return{...f($),result:"refused",detail:`${O.refused}; ${qr(v)}`}}return{...g,result:"refused",detail:"it kept changing while Canary was editing it"}},b=()=>{let x=h(),S=x?.line??je;for(let v=0;v<3;v++){let $=Ks(o);if("unreadable"in $)return x?{...g,result:"refused",detail:`${$.unreadable}: if it still holds \`${S}\`, take that line out yourself`}:null;let O=Lu($,x);if(!O)return x&&p(null),null;if("refused"in O)return{...g,result:"refused",detail:`${O.refused}: take \`${S}\` out of it yourself`};let y=ga($,O.text,l());if("backup"in y){p(null);let k=O.text===null,T=k?"deleted it: Canary had created it, and nothing else was in it":`took out line${O.lines.length===1?"":"s"} ${O.lines.join(", ")} (\`${S}\`${O.header?" and the `[features]` header Canary added with it":""})`;return{...g,result:"removed",detail:T,removed:{lines:O.lines,header:O.header,deleted:k,backup:y.backup}}}if(!y.changed)return{...g,result:"refused",detail:`${y.refused}: take \`${S}\` 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:Bu(i),detected:s.detected,plan:()=>{let{verdict:x}=u();return x.kind==="edit"?[...s.plan(),f(x.edit,x)]:s.plan()},install:()=>{let{verdict:x}=u(),[S]=s.install();if(S.result==="refused")return[S];let v=x.kind==="person"?Vu(x):null,$=_();return[v?{...S,detail:S.detail?`${S.detail}; ${v}`:v}:S,...$?[$]:[]]},uninstall:()=>{let[x]=s.uninstall();if(x.result==="refused")return[x];let S=b();return S?[x,S]:[x]},status:()=>{let[x]=s.status();if(x.state!=="registered")return[x];let S=Ks(o),v="unreadable"in S?null:ya(S,a),$=v?v.kind==="broken"?Gu(S):v.kind==="person"?Vu(v):v.kind==="edit"&&Wu(v)?`Codex's hooks feature is off: ${qr(v)} (\`${pn(v.edit)}\` ${ba(v.edit)} in its config.toml); \`canary hooks install\` adds it`:v.kind==="cannot"&&Wu(v)?`Codex's hooks feature is off, and Canary cannot switch it on: ${v.why}${Ju(v)}`:null:null;if($)return[{...x,state:"disabled",detail:$}];let O=v?.kind==="edit"?`Codex before 0.124 also runs no hooks until \`${pn(v.edit)}\` is ${ba(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}${Ju(v)}.`:null,y=d();if(y<0)return[O?{...x,detail:O}:x];let k=fb(S,r,y);if(k===!0)return[O?{...x,detail:O}:x];let T=[k===null?"Codex's config.toml could not be read, so whether the hook is trusted is unknown.":null,Bu(i),O].filter(Boolean).join(" ");return[{...x,state:"untrusted",detail:T,pending:i}]}}}function yb(e=process.env){let t=e.CURSOR_CONFIG_DIR||mt(ka(),".cursor");return{id:"cursor",label:"Cursor",byDefault:!0,...cb(t)}}var yt,dt,Xs,ib,va,Ur,lb,hb,Bu,pn,Xu,qr,Wu,pb,gb,ba,Ju,Gu,Wr,Sa=X(()=>{"use strict";w();Uu();Z();yt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),dt=class extends Error{};Xs=10,ib=(e,t=process.platform)=>t==="win32"?`canary hook ${e}`:`command -v canary >/dev/null 2>&1 || exit 0; canary hook ${e}`,va=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"];lb="^(Bash|PowerShell|Monitor|mcp__.*)$";hb=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.'}),Bu=e=>`${e.why} Run \`${e.command}\` in a terminal. ${e.after}`;pn=e=>e.shape==="dotted"?Hr:je,Xu=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)?`${Xu(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",Wu=e=>e.answers.some(t=>!t.on),pb=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",gb=e=>e.shape==="dotted"?"features.codex_hooks = true":"codex_hooks = true",ba=e=>e.shape==="dotted"?"beside the other `features.` keys":e.shape==="under_header"?"under `[features]`":"in a `[features]` table",Ju=e=>e.edit?`; add \`${gb(e.edit)}\` ${ba(e.edit)} yourself`:"",Gu=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`;Wr=(e=process.env)=>[ub(e),mb(e),yb(e)]});var td={};Ti(td,{installAgentPlugin:()=>Ia});import{existsSync as _a,mkdirSync as wb,readFileSync as bb,renameSync as Zu,rmSync as xa,writeFileSync as kb}from"node:fs";import{homedir as vb}from"node:os";import{dirname as Sb,join as Gn}from"node:path";function Cb(e,t){return Object.entries(t).every(([n,r])=>{try{return bb(Gn(e,n),"utf8")===r}catch{return!1}})}function _b(e,t){let n=`${e}.next`,r=`${e}.old`;xa(n,{recursive:!0,force:!0});for(let[s,o]of Object.entries(t))wb(Sb(Gn(n,s)),{recursive:!0}),kb(Gn(n,s),o);xa(r,{recursive:!0,force:!0}),_a(e)&&Zu(e,r),Zu(n,e),xa(r,{recursive:!0,force:!0})}function $b(e,t){for(let i of["extraKnownMarketplaces","enabledPlugins"])if(e[i]===void 0&&(e[i]={}),!xb(e[i]))throw new dt(`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[$a])!==JSON.stringify(s)&&(n[$a]=s,o=!0),r[ed]===void 0&&(r[ed]=!0,o=!0),o}function Ia(e=process.env){if(!Ca||K().agentSkills===!1)return{result:"skipped"};let t=e.CLAUDE_CONFIG_DIR||Gn(vb(),".claude");if(!_a(t))return{result:"skipped"};let n=Gn(Y(),"plugins"),r=Gn(t,"settings.json");try{let s=!_a(n),o=!Cb(n,Ca);o&&_b(n,Ca);let i=Jn(r,a=>$b(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 Ca,$a,ed,xb,Aa=X(()=>{"use strict";w();Z();Sa();Ca=typeof E=="object"?E:null,$a="runcanary",ed=`canary@${$a}`,xb=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});var Ra,nd=X(()=>{Ra=`---
1469
+ ${_e}
1470
+ `,shape:"new_file"};let t=ut(Fw(e.doc)),n=d=>{let u=qn(d);return"doc"in u&&ut(u.doc)===t},r=Dr(e.text),s=(d,u,h)=>{let p=pa(r.slice(0,d+1)),f=pa(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())Ww.test(u.content)&&o.push(s(d,_e,"under_header"));for(let[d,u]of r.entries())Bw.test(u.content)&&o.push(s(d,Wr,"dotted"))}let i=e.text,a=e.eol,c=i?/\n\s*\n$/.test(i)?`[features]${a}${_e}${a}`:i.endsWith(`
1471
+ `)?`${a}[features]${a}${_e}${a}`:`${a}${a}[features]${a}${_e}`:`[features]${a}${_e}${a}`;o.push({text:i+c,line:Dw(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=>Uw.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 Lu(e,t){if(!e.raw)return null;if(!e.doc)return Dr(e.text).some(c=>[_e,Wr].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=Dr(r),i=[];for(let c=o.length-1;c>=0;c--){let l=o[c].content.trim();if(l!==_e&&l!==Wr)continue;let d=Mu(o,c),u=qn(d);if(!("doc"in u))continue;let h=Pu(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=Dr(r))}if(!i.length)return null;let a=!1;if(n?.added.includes("[features]")&&Oe(s.features)){let c=new Set([ut(s),...Object.keys(s.features).length?[]:[ut(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:qn(d);d!==null&&u&&"doc"in u&&c.has(ut(u.doc))&&(r=d,a=!0)}return{text:n?.created&&!r.trim()?null:r,lines:i.sort((c,l)=>c-l),header:a}}function Du(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{da(e.target,ha.W_OK)}catch{return"it is read-only"}}try{da(Ys(e.target),ha.W_OK)}catch{return`its folder (${Ys(e.target)}) is read-only`}return null}function Jw(e){let t;try{t=Nu(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 _u(e.target).equals(e.raw)}catch{return!1}}function ga(e,t,n){let r=Du(e);if(r)return{refused:r};let s=e.identity?e.identity.mode&4095:384,o=null;if(e.raw)try{Iw(n,{recursive:!0,mode:448}),o=Hn(n,`codex-config.toml.${new Date().toISOString().replace(/[:.]/g,"-")}.${bw(3).toString("hex")}.bak`),fa(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=Hn(Ys(e.target),`.${Nw(e.target)}.${kw()}.canary.tmp`);try{if(t!==null){if(fa(i,Buffer.from((e.bom?"\uFEFF":"")+t,"utf8"),{flag:"wx",mode:s}),e.identity&&Js(i).gid!==e.identity.gid)try{xw(i,-1,e.identity.gid)}catch{}vw(i,s);let a=Js(i);if(e.identity&&(a.gid!==e.identity.gid||(a.mode&4095)!==s))return Mt(i,{force:!0}),o&&Mt(o,{force:!0}),{refused:"its group or permissions could not be kept on a replacement"}}return Jw(e)?(t===null?Mt(e.target):Ow(i,e.target),{backup:o}):(Mt(i,{force:!0}),o&&Mt(o,{force:!0}),{refused:"it changed while Canary was editing it",changed:!0})}catch(a){Mt(i,{force:!0}),o&&Mt(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 ma(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(_w).filter(Boolean))for(let o of r){let i=Hn(s,o);try{if(da(i,ha.X_OK),Js(i).isFile()){n.push(i);break e}}catch{}}return t==="darwin"&&Cw(ua)&&!n.some(s=>Yw(s,ua))&&n.push(ua),n}function Yw(e,t){try{return Tu(e)===Tu(t)}catch{return e===t}}function $u(e,t,n){let r=`${e}\0${t?ww("sha256").update(t).digest("hex"):"-"}`,s=Ou.get(r);if(s)return s;let o=Rw(Hn($w(),"canary-codex-")),i;try{t&&fa(Hn(o,"config.toml"),t,{mode:384});let a=process.platform==="win32"&&/\.(cmd|bat)$/i.test(e),c=yw(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(`
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{Mt(o,{recursive:!0,force:!0})}return Ou.set(r,i),i}function Kw(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 Wu(e,t=Vw){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:Kw(a.on,a.key,r),derived:!0}):s.unanswered.push({binary:o,why:i.why})}return s}}function ya(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=qw(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=Gw(e);if("refused"in o)return{kind:"cannot",why:o.refused,answers:n,unanswered:r,...o.inline?{inline:!0}:{}};let i=Du(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:qn(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 ju,_e,Wr,Pw,Oe,Lw,Fw,pa,Dw,Ks,Ww,Bw,Uw,zs,Fu,ua,Vw,Ou,Bu=Z(()=>{"use strict";w();Ru();ju="# added by canary",_e=`codex_hooks = true ${ju}`,Wr=`features.codex_hooks = true ${ju}`,Pw=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);Lw=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Fw=e=>({...e,features:{...Oe(e.features)?e.features:{},codex_hooks:!0}});pa=e=>e.map(t=>t.content+t.eol).join("");Dw=e=>e.split(`
1473
+ `).length-1,Ks=e=>`(?:${e}|"${e}"|'${e}')`,Ww=new RegExp(`^[ \\t]*\\[[ \\t]*${Ks("features")}[ \\t]*\\][ \\t]*(?:#.*)?$`),Bw=new RegExp(`^[ \\t]*${Ks("features")}[ \\t]*\\.`),Uw=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}")`:""}`;Fu=e=>Hn(e,"backups");ua="/Applications/ChatGPT.app/Contents/Resources/codex";Vw=3e3,Ou=new Map});import{accessSync as zw,constants as Xw,existsSync as Hr,lstatSync as Zw,readFileSync as Xs,readlinkSync as Qw,renameSync as eb,rmSync as Uu,statSync as Vu,writeFileSync as tb}from"node:fs";import{randomUUID as nb}from"node:crypto";import{homedir as ka}from"node:os";import{delimiter as rb,dirname as wa,join as mt,resolve as sb}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(rb).filter(Boolean))for(let o of r)try{if(zw(mt(s,o),Xw.X_OK),Vu(mt(s,o)).isFile())return!0}catch{}return!1}function ob(e){let t=e;for(let n=0;n<16;n++){let r;try{if(!Zw(t).isSymbolicLink())return t;r=Qw(t)}catch{return t}t=sb(wa(t),r)}throw new dt("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 dt)return{result:"refused",detail:c.message};throw c}let o=r?/^([ \t]+)"/m.exec(r)?.[1]??" ":" ",i;try{i=ob(e)}catch(c){return{result:"refused",detail:c.message}}if(i!==e&&!Hr(wa(i)))return{result:"refused",detail:"it is a symlink into a folder that does not exist"};let a=mt(wa(i),`.${nb()}.canary.tmp`);try{tb(a,JSON.stringify(s,null,o)+`
1474
+ `,{flag:"wx",mode:r===null?384:Vu(i).mode&511});let c;try{c=Xs(e,"utf8")}catch{c=null}if(c!==r){Uu(a,{force:!0});continue}return eb(a,i),{result:"written"}}catch(c){return Uu(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 ab(e,t,n){for(let r of e){if(!yt(r))throw new dt(`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 dt(`its \`hooks.${t}\` list holds an entry whose \`${n}\` is not a list of objects`)}}function Lt(e,t,n,r="hooks"){if(e.hooks===void 0){if(!n)return null;e.hooks={}}if(!yt(e.hooks))throw new dt("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 dt(`its \`hooks.${t}\` entry is not a list`);return ab(e.hooks[t],t,r),e.hooks[t]}function Ku(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 Xu(e){let t=ib(e.harness),n=va(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=Lt(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&&Ku(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(Lt(c,"PreToolUse",!0))?!1:(i(c),Lt(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=Lt(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 cb(e){let t=mt(e,"hooks.json"),n=va("cursor"),r=()=>({command:"canary hook cursor",timeout:Zs}),s=a=>Br.every(c=>{let l=(Lt(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 Br){let d=Lt(a,l,!1,null);if(!d)continue;let u=d.filter(h=>!n(h));u.length!==d.length&&(c=!0,a.hooks[l]=u,Ku(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(Br.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 dt(`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 Br)Lt(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 Br.some(c=>(Lt(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 ub(e=process.env){let t=e.CLAUDE_CONFIG_DIR||mt(ka(),".claude");return{id:"claude",label:"Claude Code",byDefault:!0,...Xu({harness:"claude",dir:t,file:mt(t,"settings.json"),matcher:lb,disabledKey:"disableAllHooks"})}}function db(e=process.env,t=process.platform){let[n]=ma(e,t);return n===void 0?null:/[\s"']/.test(n)?`"${n}"`:n}function fb(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 Yu(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)?`${Zu(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 mb(e=process.env,t={}){let n=e.CODEX_HOME||mt(ka(),".codex"),r=mt(n,"hooks.json"),s=Xu({harness:"codex",dir:n,file:r,matcher:".*"}),o=mt(n,"config.toml"),i=hb(db(e)),a=t.ask??Wu(ma(e)),c=va("codex"),l=()=>Fu(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:ya(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)}\` ${pb(S)}${x?`, because ${Ur(x)}`:""}`,snippet:S.shape==="new_table"||S.shape==="new_file"?`[features]
1475
+ ${_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}; ${Ur(x)}`}:x.kind==="broken"?{...g,result:"refused",detail:Ju(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,$=ga(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 ${Ur(v)}`,edit:{line:I.line,text:pn(I),backup:$.backup,created:I.shape==="new_file"}};if(!$.changed)return{...f(I),result:"refused",detail:`${$.refused}; ${Ur(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 $=Lu(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=ga(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:Hu(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"?Yu(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:ya(x,a),I=v?v.kind==="broken"?Ju(x):v.kind==="person"?Yu(v):v.kind==="edit"&&qu(v)?`Codex's hooks feature is off: ${Ur(v)} (\`${pn(v.edit)}\` ${ba(v.edit)} in its config.toml); \`canary hooks install\` adds it`:v.kind==="cannot"&&qu(v)?`Codex's hooks feature is off, and Canary cannot switch it on: ${v.why}${Gu(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 ${ba(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}${Gu(v)}.`:null,y=d();if(y<0)return[$?{...S,detail:$}:S];let k=fb(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,Hu(i),$].filter(Boolean).join(" ");return[{...S,state:"untrusted",detail:N,pending:i}]}}}function yb(e=process.env){let t=e.CURSOR_CONFIG_DIR||mt(ka(),".cursor");return{id:"cursor",label:"Cursor",byDefault:!0,...cb(t)}}var yt,dt,Zs,ib,va,Br,lb,hb,Hu,pn,Zu,Ur,qu,pb,gb,ba,Gu,Ju,qr,xa=Z(()=>{"use strict";w();Bu();Q();yt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),dt=class extends Error{};Zs=10,ib=(e,t=process.platform)=>t==="win32"?`canary hook ${e}`:`command -v canary >/dev/null 2>&1 || exit 0; canary hook ${e}`,va=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);Br=["beforeShellExecution","beforeMCPExecution"];lb="^(Bash|PowerShell|Monitor|mcp__.*)$";hb=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.'}),Hu=e=>`${e.why} Run \`${e.command}\` in a terminal. ${e.after}`;pn=e=>e.shape==="dotted"?Wr:_e,Zu=e=>{let t=e.find(n=>!n.on)??e[0];return t?`your Codex (${t.binary})`:"Codex"},Ur=e=>e.answers.some(t=>!t.on)?`${Zu(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",qu=e=>e.answers.some(t=>!t.on),pb=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",gb=e=>e.shape==="dotted"?"features.codex_hooks = true":"codex_hooks = true",ba=e=>e.shape==="dotted"?"beside the other `features.` keys":e.shape==="under_header"?"under `[features]`":"in a `[features]` table",Gu=e=>e.edit?`; add \`${gb(e.edit)}\` ${ba(e.edit)} yourself`:"",Ju=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`;qr=(e=process.env)=>[ub(e),mb(e),yb(e)]});var td={};Ni(td,{installAgentPlugin:()=>Ra});import{existsSync as Aa,mkdirSync as wb,readFileSync as bb,renameSync as Qu,rmSync as Sa,writeFileSync as kb}from"node:fs";import{homedir as vb}from"node:os";import{dirname as xb,join as Jn}from"node:path";function Cb(e,t){return Object.entries(t).every(([n,r])=>{try{return bb(Jn(e,n),"utf8")===r}catch{return!1}})}function Ab(e,t){let n=`${e}.next`,r=`${e}.old`;Sa(n,{recursive:!0,force:!0});for(let[s,o]of Object.entries(t))wb(xb(Jn(n,s)),{recursive:!0}),kb(Jn(n,s),o);Sa(r,{recursive:!0,force:!0}),Aa(e)&&Qu(e,r),Qu(n,e),Sa(r,{recursive:!0,force:!0})}function Ib(e,t){for(let i of["extraKnownMarketplaces","enabledPlugins"])if(e[i]===void 0&&(e[i]={}),!Sb(e[i]))throw new dt(`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[Ia])!==JSON.stringify(s)&&(n[Ia]=s,o=!0),r[ed]===void 0&&(r[ed]=!0,o=!0),o}function Ra(e=process.env){if(!Ca||V().agentSkills===!1)return{result:"skipped"};let t=e.CLAUDE_CONFIG_DIR||Jn(vb(),".claude");if(!Aa(t))return{result:"skipped"};let n=Jn(K(),"plugins"),r=Jn(t,"settings.json");try{let s=!Aa(n),o=!Cb(n,Ca);o&&Ab(n,Ca);let i=Gn(r,a=>Ib(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 Ca,Ia,ed,Sb,Ta=Z(()=>{"use strict";w();Q();xa();Ca=typeof O=="object"?O:null,Ia="runcanary",ed=`canary@${Ia}`,Sb=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});var Ea,nd=Z(()=>{Ea=`---
437
1477
  name: canary
438
1478
  description: >-
439
1479
  Use whenever you finish a code change and are about to report it done, or whenever a change
@@ -597,88 +1637,88 @@ If \`canary\` is not installed: \`npm i -g @runcanary/cli\`, then start at step
597
1637
  "Getting started" section covers logging in.
598
1638
  Output that begins with \`OFFLINE COPY\` could not be refreshed and may be outdated \u2014 say so if
599
1639
  you act on it.
600
- `});var sd={};Ti(sd,{installAgentSkill:()=>Jr});import{existsSync as Oa,lstatSync as Ab,mkdirSync as Rb,readFileSync as rd,rmSync as Eb,rmdirSync as Ob,writeFileSync as Tb}from"node:fs";import{homedir as Ea}from"node:os";import{join as gn}from"node:path";function Pb(e){let t=gn(e,"skills",Nb),n=gn(t,"SKILL.md");if(eo(t)||eo(n)||!Oa(n))return;let r;try{r=rd(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{Eb(n,{force:!1})}catch{return}try{Ob(t)}catch{}}}function eo(e){try{return Ab(e).isSymbolicLink()}catch{return!1}}function Mb(){return[gn(Ea(),".claude"),gn(Ea(),".agents"),gn(Ea(),".codex")].filter(e=>Oa(e))}function Jr(){let e={installed:[],refreshed:[],current:[],skipped:[]};if(K().agentSkills===!1)return e;for(let t of Mb()){Pb(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=Oa(r)?rd(r,"utf8"):null;if(s===Ra){e.current.push(r);continue}Rb(n,{recursive:!0}),Tb(r,Ra),(s===null?e.installed:e.refreshed).push(r)}catch{}}return e}var jb,Nb,to=X(()=>{"use strict";w();Z();nd();jb="canary",Nb="canary-setup"});import{createHash as Lb,randomUUID as Db}from"node:crypto";import{mkdirSync as Fb,readFileSync as Hb,renameSync as Ub,rmSync as od,writeFileSync as qb}from"node:fs";import{dirname as Ta,join as Bb,resolve as id}from"node:path";function ld(e,t,n=Date.now()){try{let r=cd(e),s=`${r}.${Db()}.tmp`;Fb(Ta(r),{recursive:!0,mode:448});try{qb(s,JSON.stringify({version:1,chat:t,at:n})+`
601
- `,{flag:"wx",mode:384}),Ub(s,r)}catch(o){throw od(s,{force:!0}),o}}catch{}}function ud(e,t=Date.now()){for(let n=id(e);;n=Ta(n)){let r=cd(n),s=null;try{s=JSON.parse(Hb(r,"utf8")),od(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<Wb)return s.chat;if(Ta(n)===n)return null}}var Wb,Jb,ad,cd,ja=X(()=>{"use strict";w();Z();Wb=1e4,Jb=/(?:^|[;&|(]|\$\()\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:[^\s;&|()]*\/)?canary(?=[\s;&|)]|$)/m,ad=e=>e.some(t=>Jb.test(t)),cd=e=>Bb(Y(),"hold",`chat-${Lb("sha256").update(id(e)).digest("hex").slice(0,32)}.json`)});import{mkdirSync as Gb,readFileSync as Vb,writeFileSync as Kb}from"node:fs";import{homedir as Yb}from"node:os";import{dirname as zb,join as dd}from"node:path";function fd(){try{return JSON.parse(Vb(Na(),"utf8"))}catch{return{}}}function Xb(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 pd(){if(wt==="0.0.0-dev")return;let{latest:e}=fd();e&&Xb(e,wt)&&console.error(`A newer Canary CLI is available (${wt} -> ${e}): npm install -g ${hd}`)}function Vn(){if(wt==="0.0.0-dev")return;let e=fd();e.checkedAt&&Date.now()-e.checkedAt<Qb||(async()=>{let t=n=>{try{Gb(zb(Na()),{recursive:!0}),Kb(Na(),JSON.stringify({checkedAt:Date.now(),latest:n??e.latest})+`
602
- `)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${hd}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return t();let{version:r}=await n.json();t(r||void 0)}catch{t()}})()}var wt,hd,Qb,Na,mn=X(()=>{"use strict";w();wt="0.1.16",hd="@runcanary/cli",Qb=1440*60*1e3,Na=()=>dd(process.env.CANARY_HOME||dd(Yb(),".canary"),"update-check.json")});import{createHash as Zb}from"node:crypto";import{execFileSync as ek,spawn as tk}from"node:child_process";function tt(e){Dt={...Dt,...e},Gr=null}function Ma(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:(Pa===void 0&&(Pa=ud(t)),Pa??r??n??null)}function nk(e,t){return Zb("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 gd(e,t){try{let n=no();return ek("git",e,{cwd:t,env:n,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function rk(e,t){let[n,r,s]=(gd(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],e)??"").split(`
603
- `);if(!n)return{};let o={worktreeId:nk(n,t)};if(s!=="true"){let i=du(o.worktreeId);i&&gd(["cat-file","-e",`${i}^{commit}`],n)!==null?o.repoFingerprint=i:sk(n,o.worktreeId)}return o.branch=r&&r!=="HEAD"?r:"HEAD",o}function sk(e,t){md.has(t)||md.set(t,new Promise(n=>{try{let r=no(),s=tk("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(`
604
- `).filter(Boolean).sort()[0]:void 0;a&&hu(t,a),n()}),s.unref(),s.stdout.unref?.()}catch{n()}}))}function ok(){if(Gr)return Gr;let e=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",t=Ma(),n=Dt.harness??t.harness,r=t.harness===n?t.chatId:void 0,s="",o={};try{s=uu(),o=rk(Dt.cwd??process.cwd(),s)}catch{}return Gr={cliVersion:wt,command:e,installId:s,...o,harness:n,...r?{chatId:r}:{},...Dt.agent!==void 0?{agent:Dt.agent}:{},...Dt.mode?{mode:Dt.mode}:{}},Gr}function Ft(){let e=ok(),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,Gr,Pa,md,nt=X(()=>{"use strict";w();Z();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={},Gr=null;md=new Map});async function U(e,t={}){let n=(t.baseUrl||ue()).replace(/\/+$/,""),r={...Ft(),...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=X(()=>{"use strict";w();Z();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 yd(e){return Te(t=>({...t,gate:{...t.gate,mode:e}}))}var wn,ro=X(()=>{"use strict";w();Z();wn=()=>K().gate?.mode==="off"?"off":"on"});var cE,so,ik,lE,wd=X(()=>{"use strict";w();cE=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)}`,ik=[["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"]],lE=ik.flatMap(([e,t])=>["-c",`${e}=${t}`])});import{createHash as ak}from"node:crypto";import{existsSync as ck,mkdirSync as La,readFileSync as Kn,writeFileSync as oo}from"node:fs";import{join as Rt}from"node:path";function Yn(e){return Rt(e,".canary")}function vd(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=Yn(e),n=Rt(t,".gitignore");try{let r=Kn(n,"utf8").split(`
605
- `).map(s=>s.trim()).filter(s=>s.length>0);if(r[r.length-1]==="*")return}catch{}try{La(t,{recursive:!0});let r="";try{r=Kn(n,"utf8"),r&&!r.endsWith(`
1640
+ `});var sd={};Ni(sd,{installAgentSkill:()=>Gr});import{existsSync as $a,lstatSync as Tb,mkdirSync as Eb,readFileSync as rd,rmSync as Ob,rmdirSync as $b,writeFileSync as Nb}from"node:fs";import{homedir as Oa}from"node:os";import{join as gn}from"node:path";function Pb(e){let t=gn(e,"skills",jb),n=gn(t,"SKILL.md");if(eo(t)||eo(n)||!$a(n))return;let r;try{r=rd(n,"utf8")}catch{return}if(!(!/^name:\s*canary-setup\s*$/m.test(r)||!/runcanary\.ai|@runcanary\/cli/.test(r))){try{Ob(n,{force:!1})}catch{return}try{$b(t)}catch{}}}function eo(e){try{return Tb(e).isSymbolicLink()}catch{return!1}}function Mb(){return[gn(Oa(),".claude"),gn(Oa(),".agents"),gn(Oa(),".codex")].filter(e=>$a(e))}function Gr(){let e={installed:[],refreshed:[],current:[],skipped:[]};if(V().agentSkills===!1)return e;for(let t of Mb()){Pb(t);let n=gn(t,"skills",_b),r=gn(n,"SKILL.md");try{if(eo(n)||eo(r)){e.skipped.push(r);continue}let s=$a(r)?rd(r,"utf8"):null;if(s===Ea){e.current.push(r);continue}Eb(n,{recursive:!0}),Nb(r,Ea),(s===null?e.installed:e.refreshed).push(r)}catch{}}return e}var _b,jb,to=Z(()=>{"use strict";w();Q();nd();_b="canary",jb="canary-setup"});import{createHash as Lb,randomUUID as Fb}from"node:crypto";import{mkdirSync as Db,readFileSync as Wb,renameSync as Bb,rmSync as od,writeFileSync as Ub}from"node:fs";import{dirname as Na,join as Hb,resolve as id}from"node:path";function ld(e,t,n=Date.now()){try{let r=cd(e),s=`${r}.${Fb()}.tmp`;Db(Na(r),{recursive:!0,mode:448});try{Ub(s,JSON.stringify({version:1,chat:t,at:n})+`
1641
+ `,{flag:"wx",mode:384}),Bb(s,r)}catch(o){throw od(s,{force:!0}),o}}catch{}}function ud(e,t=Date.now()){for(let n=id(e);;n=Na(n)){let r=cd(n),s=null;try{s=JSON.parse(Wb(r,"utf8")),od(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<qb)return s.chat;if(Na(n)===n)return null}}var qb,Gb,ad,cd,_a=Z(()=>{"use strict";w();Q();qb=1e4,Gb=/(?:^|[;&|(]|\$\()\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:[^\s;&|()]*\/)?canary(?=[\s;&|)]|$)/m,ad=e=>e.some(t=>Gb.test(t)),cd=e=>Hb(K(),"hold",`chat-${Lb("sha256").update(id(e)).digest("hex").slice(0,32)}.json`)});import{mkdirSync as Jb,readFileSync as Yb,writeFileSync as Vb}from"node:fs";import{homedir as Kb}from"node:os";import{dirname as zb,join as dd}from"node:path";function fd(){try{return JSON.parse(Yb(ja(),"utf8"))}catch{return{}}}function Zb(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 pd(){if(wt==="0.0.0-dev")return;let{latest:e}=fd();e&&Zb(e,wt)&&console.error(`A newer Canary CLI is available (${wt} -> ${e}): npm install -g ${hd}`)}function Yn(){if(wt==="0.0.0-dev")return;let e=fd();e.checkedAt&&Date.now()-e.checkedAt<Xb||(async()=>{let t=n=>{try{Jb(zb(ja()),{recursive:!0}),Vb(ja(),JSON.stringify({checkedAt:Date.now(),latest:n??e.latest})+`
1642
+ `)}catch{}};try{let n=await fetch(`https://registry.npmjs.org/${hd}/latest`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return t();let{version:r}=await n.json();t(r||void 0)}catch{t()}})()}var wt,hd,Xb,ja,mn=Z(()=>{"use strict";w();wt="0.1.17",hd="@runcanary/cli",Xb=1440*60*1e3,ja=()=>dd(process.env.CANARY_HOME||dd(Kb(),".canary"),"update-check.json")});import{createHash as Qb}from"node:crypto";import{execFileSync as e0,spawn as t0}from"node:child_process";function tt(e){Ft={...Ft,...e},Jr=null}function Ma(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:(Pa===void 0&&(Pa=ud(t)),Pa??r??n??null)}function n0(e,t){return Qb("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 gd(e,t){try{let n=no();return e0("git",e,{cwd:t,env:n,stdio:["ignore","pipe","ignore"],timeout:5e3}).toString("utf8").trim()}catch{return null}}function r0(e,t){let[n,r,s]=(gd(["rev-parse","--show-toplevel","--abbrev-ref","HEAD","--is-shallow-repository"],e)??"").split(`
1643
+ `);if(!n)return{};let o={worktreeId:n0(n,t)};if(s!=="true"){let i=du(o.worktreeId);i&&gd(["cat-file","-e",`${i}^{commit}`],n)!==null?o.repoFingerprint=i:s0(n,o.worktreeId)}return o.branch=r&&r!=="HEAD"?r:"HEAD",o}function s0(e,t){md.has(t)||md.set(t,new Promise(n=>{try{let r=no(),s=t0("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(`
1644
+ `).filter(Boolean).sort()[0]:void 0;a&&hu(t,a),n()}),s.unref(),s.stdout.unref?.()}catch{n()}}))}function o0(){if(Jr)return Jr;let e=/^[a-z][a-z-]*$/.test(process.argv[2]??"")?process.argv[2]:"",t=Ma(),n=Ft.harness??t.harness,r=t.harness===n?t.chatId:void 0,s="",o={};try{s=uu(),o=r0(Ft.cwd??process.cwd(),s)}catch{}return Jr={cliVersion:wt,command:e,installId:s,...o,harness:n,...r?{chatId:r}:{},...Ft.agent!==void 0?{agent:Ft.agent}:{},...Ft.mode?{mode:Ft.mode}:{}},Jr}function Dt(){let e=o0(),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,Ft,Jr,Pa,md,nt=Z(()=>{"use strict";w();Q();_a();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"},Ft={},Jr=null;md=new Map});async function B(e,t={}){let n=(t.baseUrl||ue()).replace(/\/+$/,""),r={...Dt(),...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();Q();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 yd(e){return Ne(t=>({...t,gate:{...t.gate,mode:e}}))}var wn,ro=Z(()=>{"use strict";w();Q();wn=()=>V().gate?.mode==="off"?"off":"on"});var cE,so,i0,lE,wd=Z(()=>{"use strict";w();cE=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)}`,i0=[["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"]],lE=i0.flatMap(([e,t])=>["-c",`${e}=${t}`])});import{createHash as a0}from"node:crypto";import{existsSync as c0,mkdirSync as La,readFileSync as Vn,writeFileSync as oo}from"node:fs";import{join as Et}from"node:path";function Kn(e){return Et(e,".canary")}function vd(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 Yr(e){let t=Kn(e),n=Et(t,".gitignore");try{let r=Vn(n,"utf8").split(`
1645
+ `).map(s=>s.trim()).filter(s=>s.length>0);if(r[r.length-1]==="*")return}catch{}try{La(t,{recursive:!0});let r="";try{r=Vn(n,"utf8"),r&&!r.endsWith(`
606
1646
  `)&&(r+=`
607
1647
  `)}catch{}oo(n,`${r}*
608
- `)}catch{}}function Ht(e){let t=Yn(e),n;try{n=Kn(Rt(t,"setup.sh"),"utf8")}catch{throw new Ye("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 Ye("recipe_invalid",".canary/setup.sh is empty.");let r;try{r=JSON.parse(Kn(Rt(t,"run.json"),"utf8"))}catch(a){throw new Ye("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let s=[],o={},i=Rt(t,"env.json");if(ck(i)){let a;try{a=JSON.parse(Kn(i,"utf8"))}catch(l){throw new Ye("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 Ye("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let c=a;s=xd(c.manifest),o=Cd(c.values),uk(s)}return{setupSh:n,runJson:r,envManifest:s,envValues:o}}function bn(e){return ak("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 xd(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.name=="string"):[]}function uk(e){for(let t of e){if(!bd.has(String(t.class)))throw new Ye("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has unknown class "${String(t.class)}"`,`use one of: ${[...bd].join(", ")}`);if(!lk.has(String(t.neededAt)))throw new Ye("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has invalid neededAt "${String(t.neededAt)}"`,'use "boot" or "runtime"')}}function Cd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function dk(e){try{let t=JSON.parse(Kn(Rt(Yn(e),"env.json"),"utf8"));return{manifest:xd(t.manifest),values:Cd(t.values)}}catch{return{manifest:[],values:{}}}}function hk(e,t){La(Yn(e),{recursive:!0}),oo(Rt(Yn(e),"env.json"),JSON.stringify(t,null,2)+`
609
- `),Vr(e)}function Fa(e,t){if(t.length===0)return;let n=dk(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&&kd.has(s.class)&&!kd.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)}}hk(e,n)}function _d(e,t){let n=[],r=Yn(e);if(La(r,{recursive:!0}),typeof t.setupSh=="string"&&t.setupSh.trim()&&(oo(Rt(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)+`
610
- `}catch{}oo(Rt(r,"run.json"),o),n.push(".canary/run.json")}let s=Object.entries(t.envOverrides??{});return s.length>0&&(Fa(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 Ye,Sd,bd,lk,kd,Ha=X(()=>{"use strict";w();Ye=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="RecipeError"}};Sd=new Set(["github.com","ssh.github.com"]);bd=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),lk=new Set(["boot","runtime"]);kd=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"])});import{execFileSync as fk}from"node:child_process";import{createHash as Ad,randomUUID as ao}from"node:crypto";import{linkSync as pk,lstatSync as Rd,mkdirSync as co,readdirSync as gk,readFileSync as qa,realpathSync as io,renameSync as Ed,rmSync as lo,writeFileSync as Ba}from"node:fs";import{basename as Wa,dirname as Od,isAbsolute as mk,join as ze,relative as yk,resolve as Ja,sep as wk}from"node:path";function bk(e){let t=vd(e);if(!(!t||!Sd.has(t.host.toLowerCase().replace(/:\d+$/,"")))&&!(!$d.test(t.owner)||!$d.test(t.name)))return`${t.owner}/${t.name}`}function Qn(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=>fk("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=bk(n(["remote","get-url","origin"]))}catch{}if(o)return{root:r,commonDirectory:s,name:o,githubFullName:o};let i=Wa(r).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:r,commonDirectory:s,name:i}}function kk(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(Rd(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=Od(e);if(n===e)throw t;return ze(uo(n),Wa(e))}}function Ua(e,t){let n=yk(e,t);return n===""||!mk(n)&&n!==".."&&!n.startsWith(`..${wk}`)}function Xn(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 Zn(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=Qn(e.directory),n=kk(e.apiUrl),r=uo(Ja(Y())),s=Wa(t.commonDirectory)===".git"?Od(t.commonDirectory):t.commonDirectory,o=Ad("sha256").update(JSON.stringify([Kr,n,e.userId,e.workspaceId,t.githubFullName?`github:${t.githubFullName.toLowerCase()}`:t.commonDirectory])).digest("hex"),i=ze(r,"local-repositories"),a=Xn(i,ze(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 Id(e,t){let n=Xn(e.cacheRoot,ze(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=Id(e,"identity.json"),n=Id(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 Ga(e,t,n){co(e.cacheDirectory,{recursive:!0,mode:448});let r=ze(e.cacheDirectory,`${t}.${ao()}.tmp`);try{Ba(r,JSON.stringify({version:Kr,scope:e.scope,...n})+`
611
- `,{flag:"wx",mode:384});try{pk(r,ze(e.cacheDirectory,t))}catch(s){if(s.code!=="EEXIST")throw s}}finally{lo(r,{force:!0})}}function Td(e,t){co(e.cacheDirectory,{recursive:!0,mode:448});let n=ze(e.cacheDirectory,`repository.json.${ao()}.tmp`);Ba(n,JSON.stringify({version:Kr,scope:e.scope,...t})+`
612
- `,{flag:"wx",mode:384}),Ed(n,ze(e.cacheDirectory,"repository.json"))}function jd(e){return kn(Zn(e))}function Va(e,t){let n=Zn(e),r=kn(n);!r?.repositoryId||r.repositoryId===t||Td(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=Zn(e);return co(n.cacheDirectory,{recursive:!0,mode:448}),Xn(n.cacheRoot,ze(n.cacheDirectory,t))}function vk(e){return Nd(Zn(e))}function Nd(e){let t=kn(e);return t||(Ga(e,"identity.json",{localKey:ao()}),kn(e))}function Sk(e){try{let t=JSON.parse(qa(Xn(e.cacheRoot,ze(e.cacheDirectory,Ka)),"utf8"));return t.version===1&&t.checkout===Ya(e.githubFullName)}catch{return!1}}function xk(e){co(e.cacheDirectory,{recursive:!0,mode:448});let t=Xn(e.cacheRoot,ze(e.cacheDirectory,Ka)),n=`${t}.${ao()}.tmp`;try{Ba(n,JSON.stringify({version:1,at:new Date().toISOString(),checkout:Ya(e.githubFullName)})+`
613
- `,{flag:"wx",mode:384}),Ed(n,t)}finally{lo(n,{force:!0})}}async function Pd(e,t){let n=Zn(e),r=kn(n);if(r?.repositoryId)return r;let{githubFullName:s}=n;if(!s||Sk({...n,githubFullName:s}))return null;let o=await t(s);if(!o)return null;if("notConnected"in o)return xk({...n,githubFullName:s}),null;if(!zn.test(o.repositoryId))return null;let i=Nd(n);return i.repositoryId||Ga(n,"repository.json",{localKey:i.localKey,repositoryId:o.repositoryId}),kn(n)}function Md(){let e=ze(uo(Ja(Y())),"local-repositories"),t=Xn(e,e),n;try{n=gk(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}return n.map(r=>ze(t,r,Ka)).filter(r=>Rd(r,{throwIfNoEntry:!1})?.isFile())}function ho(){try{for(let e of Md())lo(e,{force:!0})}catch{}}function fo(e){try{let t=Md();if(!t.length)return;let{githubFullName:n}=Qn(e??process.cwd());if(!n)return;let r=Ya(n);for(let s of t)try{JSON.parse(qa(s,"utf8")).checkout===r&&lo(s,{force:!0})}catch{}}catch{}}function Ck(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=U){if(!e.token)throw new re("not_logged_in","Run canary login first.");let n=Zn(e),r=vk(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=Ck(o,r,n,e.workspaceId);r.repositoryId&&r.repositoryId!==i.repositoryId?Td(n,{localKey:r.localKey,repositoryId:i.repositoryId}):Ga(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,$d,re,Ka,Ya,De=X(()=>{"use strict";w();fe();Z();Ha();zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Kr=2,$d=/^[A-Za-z0-9_.-]+$/,re=class extends Error{constructor(n,r){super(r);this.code=n;this.name="LocalRepositoryError"}};Ka="not-connected.json",Ya=e=>Ad("sha256").update(JSON.stringify([Kr,`github:${e.toLowerCase()}`])).digest("hex")});async function Sn(e,t,n=ue()){let r=K().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 U("/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=jd(e);if(!r?.repositoryId)return;let s=await U(`/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 Ld(e=process.cwd()){try{return Qn(e).name}catch{return}}var Yr=X(()=>{"use strict";w();fe();Z();De()});import{spawn as _k}from"node:child_process";import{createHash as xo}from"node:crypto";import{constants as Dd}from"node:fs";import{lstat as tc,mkdir as Hd,mkdtemp as Ud,open as qd,readFile as $k,readdir as Ik,readlink as Ak,realpath as Et,rm as Bd,writeFile as Rk}from"node:fs/promises";import{tmpdir as Wd}from"node:os";import{basename as Ek,dirname as Ok,isAbsolute as Tk,join as Fe,relative as jk,resolve as Jd,sep as Nk}from"node:path";import{promisify as Pk}from"node:util";import{deflate as Mk}from"node:zlib";function nc(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===".."||Vd(r)||r.includes("\0")||r.includes("\\")))&&B("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(e)}.`)}function Fk(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 Kd(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))?B("git_source_error","Git returned an invalid source entry."):(t&&i!=="0"&&B("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:n.slice(r+1),mode:s,oid:t?o:i})})}function rc(e){return(e??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256)||void 0}async function Qa(e,t){let n=await e.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,r=await za(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))&&B("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)||B("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 Yd(e,t){let{git:n}=await sc(e,t);return(await Qa(n)).baseSha}async function Xa(e){return new Set(Cn(await e.run(["ls-files","--cached","--ignored","--exclude-standard","-z"])))}async function xn(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"&&B("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(r[s])}. Remove the LFS attribute for it, or ignore the file.`)}function Uk(e,t){(e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
1648
+ `)}catch{}}function Wt(e){let t=Kn(e),n;try{n=Vn(Et(t,"setup.sh"),"utf8")}catch{throw new Ke("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 Ke("recipe_invalid",".canary/setup.sh is empty.");let r;try{r=JSON.parse(Vn(Et(t,"run.json"),"utf8"))}catch(a){throw new Ke("recipe_invalid",`Cannot read .canary/run.json: ${a instanceof Error?a.message:String(a)}`)}let s=[],o={},i=Et(t,"env.json");if(c0(i)){let a;try{a=JSON.parse(Vn(i,"utf8"))}catch(l){throw new Ke("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 Ke("recipe_invalid",".canary/env.json must be a JSON object with `manifest` and `values`");let c=a;s=Sd(c.manifest),o=Cd(c.values),u0(s)}return{setupSh:n,runJson:r,envManifest:s,envValues:o}}function bn(e){return a0("sha256").update(JSON.stringify([e.setupSh,e.runJson,e.envManifest,e.envValues])).digest("hex")}function Fa(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 Sd(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.name=="string"):[]}function u0(e){for(let t of e){if(!bd.has(String(t.class)))throw new Ke("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has unknown class "${String(t.class)}"`,`use one of: ${[...bd].join(", ")}`);if(!l0.has(String(t.neededAt)))throw new Ke("recipe_invalid",`.canary/env.json: manifest entry "${t.name}" has invalid neededAt "${String(t.neededAt)}"`,'use "boot" or "runtime"')}}function Cd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function d0(e){try{let t=JSON.parse(Vn(Et(Kn(e),"env.json"),"utf8"));return{manifest:Sd(t.manifest),values:Cd(t.values)}}catch{return{manifest:[],values:{}}}}function h0(e,t){La(Kn(e),{recursive:!0}),oo(Et(Kn(e),"env.json"),JSON.stringify(t,null,2)+`
1649
+ `),Yr(e)}function Da(e,t){if(t.length===0)return;let n=d0(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&&kd.has(s.class)&&!kd.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)}}h0(e,n)}function Ad(e,t){let n=[],r=Kn(e);if(La(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)+`
1650
+ `}catch{}oo(Et(r,"run.json"),o),n.push(".canary/run.json")}let s=Object.entries(t.envOverrides??{});return s.length>0&&(Da(e,s.map(([o,i])=>({name:o,value:i,why:"authored by the cloud verifier while fixing the boot"}))),n.push(".canary/env.json")),Yr(e),n}var Ke,xd,bd,l0,kd,Wa=Z(()=>{"use strict";w();Ke=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="RecipeError"}};xd=new Set(["github.com","ssh.github.com"]);bd=new Set(["config","provisioned_infra","internal_shared_secret","external_boot","external_flow","external_incidental"]),l0=new Set(["boot","runtime"]);kd=new Set(["external_boot","external_flow","external_incidental","internal_shared_secret"])});import{execFileSync as f0}from"node:child_process";import{createHash as Td,randomUUID as ao}from"node:crypto";import{linkSync as p0,lstatSync as Ed,mkdirSync as co,readdirSync as g0,readFileSync as Ua,realpathSync as io,renameSync as Od,rmSync as lo,writeFileSync as Ha}from"node:fs";import{basename as qa,dirname as $d,isAbsolute as m0,join as ze,relative as y0,resolve as Ga,sep as w0}from"node:path";function b0(e){let t=vd(e);if(!(!t||!xd.has(t.host.toLowerCase().replace(/:\d+$/,"")))&&!(!Id.test(t.owner)||!Id.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=>f0("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(Ga(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=b0(n(["remote","get-url","origin"]))}catch{}if(o)return{root:r,commonDirectory:s,name:o,githubFullName:o};let i=qa(r).replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,200)||"Local repository";return{root:r,commonDirectory:s,name:i}}function k0(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(Ed(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 ze(uo(n),qa(e))}}function Ba(e,t){let n=y0(e,t);return n===""||!m0(n)&&n!==".."&&!n.startsWith(`..${w0}`)}function Zn(e,t){let n=uo(t);if(!Ba(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=k0(e.apiUrl),r=uo(Ga(K())),s=qa(t.commonDirectory)===".git"?$d(t.commonDirectory):t.commonDirectory,o=Td("sha256").update(JSON.stringify([Vr,n,e.userId,e.workspaceId,t.githubFullName?`github:${t.githubFullName.toLowerCase()}`:t.commonDirectory])).digest("hex"),i=ze(r,"local-repositories"),a=Zn(i,ze(i,o));if([t.root,t.commonDirectory,s].some(c=>Ba(c,r)||Ba(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 Rd(e,t){let n=Zn(e.cacheRoot,ze(e.cacheDirectory,t)),r;try{r=Ua(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!==Vr||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=Rd(e,"identity.json"),n=Rd(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 Ja(e,t,n){co(e.cacheDirectory,{recursive:!0,mode:448});let r=ze(e.cacheDirectory,`${t}.${ao()}.tmp`);try{Ha(r,JSON.stringify({version:Vr,scope:e.scope,...n})+`
1651
+ `,{flag:"wx",mode:384});try{p0(r,ze(e.cacheDirectory,t))}catch(s){if(s.code!=="EEXIST")throw s}}finally{lo(r,{force:!0})}}function Nd(e,t){co(e.cacheDirectory,{recursive:!0,mode:448});let n=ze(e.cacheDirectory,`repository.json.${ao()}.tmp`);Ha(n,JSON.stringify({version:Vr,scope:e.scope,...t})+`
1652
+ `,{flag:"wx",mode:384}),Od(n,ze(e.cacheDirectory,"repository.json"))}function _d(e){return kn(Qn(e))}function Ya(e,t){let n=Qn(e),r=kn(n);!r?.repositoryId||r.repositoryId===t||Nd(n,{localKey:r.localKey,repositoryId:t})}function Bt(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,ze(n.cacheDirectory,t))}function v0(e){return jd(Qn(e))}function jd(e){let t=kn(e);return t||(Ja(e,"identity.json",{localKey:ao()}),kn(e))}function x0(e){try{let t=JSON.parse(Ua(Zn(e.cacheRoot,ze(e.cacheDirectory,Va)),"utf8"));return t.version===1&&t.checkout===Ka(e.githubFullName)}catch{return!1}}function S0(e){co(e.cacheDirectory,{recursive:!0,mode:448});let t=Zn(e.cacheRoot,ze(e.cacheDirectory,Va)),n=`${t}.${ao()}.tmp`;try{Ha(n,JSON.stringify({version:1,at:new Date().toISOString(),checkout:Ka(e.githubFullName)})+`
1653
+ `,{flag:"wx",mode:384}),Od(n,t)}finally{lo(n,{force:!0})}}async function Pd(e,t){let n=Qn(e),r=kn(n);if(r?.repositoryId)return r;let{githubFullName:s}=n;if(!s||x0({...n,githubFullName:s}))return null;let o=await t(s);if(!o)return null;if("notConnected"in o)return S0({...n,githubFullName:s}),null;if(!zn.test(o.repositoryId))return null;let i=jd(n);return i.repositoryId||Ja(n,"repository.json",{localKey:i.localKey,repositoryId:o.repositoryId}),kn(n)}function Md(){let e=ze(uo(Ga(K())),"local-repositories"),t=Zn(e,e),n;try{n=g0(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}return n.map(r=>ze(t,r,Va)).filter(r=>Ed(r,{throwIfNoEntry:!1})?.isFile())}function ho(){try{for(let e of Md())lo(e,{force:!0})}catch{}}function fo(e){try{let t=Md();if(!t.length)return;let{githubFullName:n}=Xn(e??process.cwd());if(!n)return;let r=Ka(n);for(let s of t)try{JSON.parse(Ua(s,"utf8")).checkout===r&&lo(s,{force:!0})}catch{}}catch{}}function C0(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=B){if(!e.token)throw new re("not_logged_in","Run canary login first.");let n=Qn(e),r=v0(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=C0(o,r,n,e.workspaceId);r.repositoryId&&r.repositoryId!==i.repositoryId?Nd(n,{localKey:r.localKey,repositoryId:i.repositoryId}):Ja(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,Vr,Id,re,Va,Ka,Fe=Z(()=>{"use strict";w();fe();Q();Wa();zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Vr=2,Id=/^[A-Za-z0-9_.-]+$/,re=class extends Error{constructor(n,r){super(r);this.code=n;this.name="LocalRepositoryError"}};Va="not-connected.json",Ka=e=>Td("sha256").update(JSON.stringify([Vr,`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 B("/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=_d(e);if(!r?.repositoryId)return;let s=await B(`/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&&Ya(e,s.repositoryId),s}function Ld(e=process.cwd()){try{return Xn(e).name}catch{return}}var Kr=Z(()=>{"use strict";w();fe();Q();Fe()});import{spawn as A0}from"node:child_process";import{createHash as So}from"node:crypto";import{constants as Fd}from"node:fs";import{lstat as tc,mkdir as Wd,mkdtemp as Bd,open as Ud,readFile as I0,readdir as R0,readlink as T0,realpath as Ot,rm as Hd,writeFile as E0}from"node:fs/promises";import{tmpdir as qd}from"node:os";import{basename as O0,dirname as $0,isAbsolute as N0,join as De,relative as _0,resolve as Gd,sep as j0}from"node:path";import{promisify as P0}from"node:util";import{deflate as M0}from"node:zlib";function nc(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===".."||Yd(r)||r.includes("\0")||r.includes("\\")))&&H("unsupported_path",`This path cannot be uploaded (unsafe or too long): ${JSON.stringify(e)}.`)}function D0(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 Vd(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))?H("git_source_error","Git returned an invalid source entry."):(t&&i!=="0"&&H("unmerged_index","Resolve the merge conflicts, then run the command again."),{path:n.slice(r+1),mode:s,oid:t?o:i})})}function rc(e){return(e??"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").slice(0,256)||void 0}async function Xa(e,t){let n=await e.text(["rev-parse","--verify","--quiet","HEAD^{commit}"],!0)||null,r=await za(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))&&H("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)||H("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 Kd(e,t){let{git:n}=await sc(e,t);return(await Xa(n)).baseSha}async function Za(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"&&H("unsupported_lfs",`Git LFS files cannot be uploaded: ${JSON.stringify(r[s])}. Remove the LFS attribute for it, or ignore the file.`)}function B0(e,t){(e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1
614
1654
  `)||e.subarray(0,128).toString("utf8").startsWith(`version https://git-lfs.github.com/spec/v1\r
615
- `))&&B("unsupported_lfs",`${JSON.stringify(t)} is a Git LFS pointer. Canary needs the real file contents.`)}function Za(e,t){(e.length>t.maxTreeFiles||e.reduce((o,i)=>o+i.size,0)>t.maxTreeBytes)&&B("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){nc(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&&B("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&&B("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&&B("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))&&B("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||B("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(o)}.`),c.pop();continue}Vd(d)&&B("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&&B("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))&&B("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(o)}.`),c.pop(),a.unshift(...h.split("/"))}a.length+c.length>t.maxPathBytes&&B("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 tc(Fe(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 qk(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()&&B("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)&&B("snapshot_limit",`This file is too large to upload: ${JSON.stringify(t)}.`),s.isSymbolicLink())return{data:await Ak(Fe(e,t),{encoding:"buffer"}),mode:"120000"};let o=await qd(Fe(e,t),Dd.O_RDONLY|Dd.O_NOFOLLOW);try{er(await o.stat())!==er(s)&&B("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))&&B("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 Bk(e,t,n,r,s){let o=Buffer.from(`# v2 git bundle
1655
+ `))&&H("unsupported_lfs",`${JSON.stringify(t)} is a Git LFS pointer. Canary needs the real file contents.`)}function Qa(e,t){(e.length>t.maxTreeFiles||e.reduce((o,i)=>o+i.size,0)>t.maxTreeBytes)&&H("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){nc(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&&H("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&&H("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&&H("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))&&H("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||H("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(o)}.`),c.pop();continue}Yd(d)&&H("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&&H("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))&&H("unsafe_symlink",`Symlink escapes the source tree: ${JSON.stringify(o)}.`),c.pop(),a.unshift(...h.split("/"))}a.length+c.length>t.maxPathBytes&&H("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 tc(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 U0(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()&&H("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)&&H("snapshot_limit",`This file is too large to upload: ${JSON.stringify(t)}.`),s.isSymbolicLink())return{data:await T0(De(e,t),{encoding:"buffer"}),mode:"120000"};let o=await Ud(De(e,t),Fd.O_RDONLY|Fd.O_NOFOLLOW);try{er(await o.stat())!==er(s)&&H("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))&&H("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
616
1656
  ${n} refs/canary/base
617
1657
  ${r} refs/canary/head
618
1658
 
619
- `),i=await qd(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=xo("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&&B("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}
620
- `);for await(let p of a.stdout)await h(p);return await u!==0&&B("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={...zr,...e};for(let[n,r]of Object.entries(t))(!Object.hasOwn(zr,n)||!Number.isSafeInteger(r)||r<=0||r>zr[n])&&B("invalid_limit",`Invalid source snapshot limit ${n}.`);return t}async function sc(e,t){let n=await Et(e),r=new qt(n,t),s;try{s=await Et(await r.text(["rev-parse","--show-toplevel"]))}catch(c){if(t?.aborted)throw c;return B("not_a_git_repository","Run this command inside a Git repository.")}let o=new qt(s,t),i=await Et(Jd(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(`
621
- `).some(c=>/^extensions\.objectformat\s+(?!sha1$)/i.test(c))&&B("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(a.split(`
622
- `).some(c=>/^extensions\.partialclone\s/i.test(c)||/^remote\..*\.promisor(?:\s|$)/i.test(c)&&!/\s(false|no|off|0)$/i.test(c))||(await Ik(Fe(i,"objects","pack")).catch(()=>[])).some(c=>c.endsWith(".promisor")))&&B("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 Wk(e,t,n){let r=Fe(e,n,".git"),s=await tc(r).catch(()=>null);if(!s?.isFile()||s.size>4096)return!1;let o=/^gitdir: (.+?)\r?\n?$/.exec(await $k(r,"utf8").catch(()=>""))?.[1];if(!o)return!1;let[i,a]=await Promise.all([Et(Jd(e,n,o)).catch(()=>null),Et(Fe(t,"worktrees")).catch(()=>null)]);return i!==null&&a!==null&&Ok(i)===a}async function So(e,t,n,r){let s=Kd(await e.run(["ls-files","--stage","-z"]),!0),o=r.likeClone?new Set:await Xa(e),i=s.filter(d=>Zd(d,o)),a=[];for(let d of Cn(await e.run(["ls-files","--others","--exclude-standard","-z"])).filter(u=>!Xd(u)))d.endsWith("/")&&(r.likeClone||await Wk(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(Bt).map(d=>d.path));return{tracked:i,paths:[...new Set([...i.map(d=>d.path),...a])].sort(),skip:c,gitlinks:l}}async function eh(e){return async()=>xo("sha256").update(await e.run(["ls-files","--stage","-v","-z"])).digest("hex")}function th(e,t){for(let n of e)nc(n.path,t),["100644","100755","120000",Co].includes(n.mode)||B("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(n.path)}.`)}function rh(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;B("embedded_repo",`${s?"This directory is a separate Git repository, so its":"These directories are separate Git repositories, so their"} files cannot be uploaded: ${nh(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)nc(r,t)}function sh(e,t){let n=new Map;return async(r,s,o)=>{Uk(s,r.path);let i=await e.put("blob",s);r.oid&&r.oid!==i&&B("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&&B("snapshot_limit","This repository has too many bytes to upload."),o.push({...r,oid:i,size:s.length,...r.mode==="120000"?{link:Gd(s)}:{}})}}async function oh(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 Jk(e,t){if(!e.includes(`\r
1659
+ `),i=await Ud(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&&H("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}
1660
+ `);for await(let p of a.stdout)await h(p);return await u!==0&&H("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 Xd(e){let t={...zr,...e};for(let[n,r]of Object.entries(t))(!Object.hasOwn(zr,n)||!Number.isSafeInteger(r)||r<=0||r>zr[n])&&H("invalid_limit",`Invalid source snapshot limit ${n}.`);return t}async function sc(e,t){let n=await Ot(e),r=new Ut(n,t),s;try{s=await Ot(await r.text(["rev-parse","--show-toplevel"]))}catch(c){if(t?.aborted)throw c;return H("not_a_git_repository","Run this command inside a Git repository.")}let o=new Ut(s,t),i=await Ot(Gd(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(`
1661
+ `).some(c=>/^extensions\.objectformat\s+(?!sha1$)/i.test(c))&&H("unsupported_object_format","Canary cannot upload a SHA-256 Git repository yet."),(a.split(`
1662
+ `).some(c=>/^extensions\.partialclone\s/i.test(c)||/^remote\..*\.promisor(?:\s|$)/i.test(c)&&!/\s(false|no|off|0)$/i.test(c))||(await R0(De(i,"objects","pack")).catch(()=>[])).some(c=>c.endsWith(".promisor")))&&H("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 q0(e,t,n){let r=De(e,n,".git"),s=await tc(r).catch(()=>null);if(!s?.isFile()||s.size>4096)return!1;let o=/^gitdir: (.+?)\r?\n?$/.exec(await I0(r,"utf8").catch(()=>""))?.[1];if(!o)return!1;let[i,a]=await Promise.all([Ot(Gd(e,n,o)).catch(()=>null),Ot(De(t,"worktrees")).catch(()=>null)]);return i!==null&&a!==null&&$0(i)===a}async function xo(e,t,n,r){let s=Vd(await e.run(["ls-files","--stage","-z"]),!0),o=r.likeClone?new Set:await Za(e),i=s.filter(d=>Qd(d,o)),a=[];for(let d of Cn(await e.run(["ls-files","--others","--exclude-standard","-z"])).filter(u=>!Zd(u)))d.endsWith("/")&&(r.likeClone||await q0(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 eh(e){return async()=>So("sha256").update(await e.run(["ls-files","--stage","-v","-z"])).digest("hex")}function th(e,t){for(let n of e)nc(n.path,t),["100644","100755","120000",Co].includes(n.mode)||H("unsupported_file",`Unsupported Git source mode at ${JSON.stringify(n.path)}.`)}function rh(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;H("embedded_repo",`${s?"This directory is a separate Git repository, so its":"These directories are separate Git repositories, so their"} files cannot be uploaded: ${nh(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)nc(r,t)}function sh(e,t){let n=new Map;return async(r,s,o)=>{B0(s,r.path);let i=await e.put("blob",s);r.oid&&r.oid!==i&&H("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&&H("snapshot_limit","This repository has too many bytes to upload."),o.push({...r,oid:i,size:s.length,...r.mode==="120000"?{link:Jd(s)}:{}})}}async function oh(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 G0(e,t){if(!e.includes(`\r
623
1663
  `)||e.subarray(0,8e3).includes(0))return null;let n=Buffer.allocUnsafe(e.length),r=0,s=0;for(let i=e.indexOf(`\r
624
1664
  `);i!==-1;i=e.indexOf(`\r
625
- `,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 xo("sha1").update(`blob ${r}\0`).update(o).digest("hex")===t.oid?o:null}async function ih(e,t,n){let r=Fe(e,t);if(!await tc(Fe(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 He&&l.code==="git_source_error")return null;throw l}let[o,i]=s.trim().split(`
626
- `);if(!o||!i||!wo.test(i))return null;let[a,c]=await Promise.all([Et(o).catch(()=>null),Et(r).catch(()=>null)]);return a!==null&&a===c?i:null}async function ah(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&&Bt(u)){c.push(yo(d,u.oid));continue}let h=await qk(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)?Jk(h.data,u):null;await a({path:d,mode:p,oid:""},f??h.data,c)}else if(u&&Bt(u))if(o.get(d)!==null){let p=await ih(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 ch(e,t){for(let[n,r]of t){let s=await zd(e,n);(s?er(s):null)!==r&&B("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}}async function lh(e,t,n){for(let[r,s]of t)await ih(e,r,n)!==s&&B("source_changed","A submodule moved to another commit while the source was being captured. Run the command again once it has settled.")}async function Gk(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(`
627
- `)+1)))}catch(r){if(r instanceof He&&r.code==="git_source_error")return new Set;throw r}}async function Vk(e,t,n,r){let s=new Map(n.filter(Bt).map(d=>[d.path,d.oid])),o=r.filter(d=>Bt(d)&&s.get(d.path)!==d.oid);if(!o.length)return;let i=await Gk(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;B("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: ${nh(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 Kk(e,t){return e?t?e.oid===t.oid&&e.mode===t.mode?null:Fd(e.mode)===Fd(t.mode)?"M":"T":"D":"A"}async function _n(e,t={}){let n=Qd(t.limits),{root:r,common:s,git:o}=await sc(e,t.signal),i=await Et(Wd());(bo(r,i)||bo(s,i))&&B("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Ud(Fe(i,"canary-source-")),c,l=()=>Bd(a,{recursive:!0,force:!0});try{let d=await Qa(o,t.baseRef),u=await eh(o),h=await u(),p=new qt(r,t.signal,!1,{GIT_INDEX_FILE:Fe(a,"baseline-index")});await p.run(["read-tree",d.baseSha??"--empty"]);let f=d.baseSha?Kd(await o.run(["ls-tree","-r","-z","--full-tree",d.baseSha]),!1):[],g=t.likeClone?new Set:await Xa(p),m=f.filter(z=>Zd(z,g)),C=await So(o,r,s,t),_=await o.text(["config","--bool","--get","core.fileMode"],!0)!=="false";(m.length>n.maxTreeFiles||C.paths.length>n.maxTreeFiles)&&B("snapshot_limit","This repository has too many files to upload."),th([...m,...C.tracked],n),rh(C.paths,n),await xn(p,mo(m),!0),await xn(o,ec(C),!1);let b=Fe(a,"repository.git");await Hd(b);let x=new qt(b,t.signal,!0);await x.run(["init","--bare","--quiet","--template="]);let S=new Qr(b,n,t.signal);c=new ko(o,n);let v=[],$=[],O=sh(S,n),y=c;for(let z of m)Bt(z)?v.push(yo(z.path,z.oid)):await O(z,await c.get(z.oid),v);let k=new Map,T=new Map,J=t.likeClone?await oh(o,C.tracked):new Set;await ah({root:r,current:C,trustFileMode:_,limits:n,signal:t.signal,stamps:k,heads:T,capture:O,blob:z=>y.get(z),out:$,converts:J,likeClone:t.likeClone===!0}),Za(v,n),Za($,n);let Le=await vo(v,S),Ce=await vo($,S);for(let[z,gt]of[[Le,v],[Ce,$]])await x.run(["read-tree",z]),await xn(x,mo(gt),!0);await Vk(x,Ce,v,$);let ae=await S.put("commit",Buffer.from(`tree ${Le}
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 ih(e,t,n){let r=De(e,t);if(!await tc(De(r,".git")).then(()=>!0,()=>!1))return null;let s;try{s=(await new Ut(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(`
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 ah(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 U0(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)?G0(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 ih(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 ch(e,t){for(let[n,r]of t){let s=await zd(e,n);(s?er(s):null)!==r&&H("source_changed","Files changed while the source was being captured. Run the command again once editing has stopped.")}}async function lh(e,t,n){for(let[r,s]of t)await ih(e,r,n)!==s&&H("source_changed","A submodule moved to another commit while the source was being captured. Run the command again once it has settled.")}async function J0(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(`
1667
+ `)+1)))}catch(r){if(r instanceof We&&r.code==="git_source_error")return new Set;throw r}}async function Y0(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 J0(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;H("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: ${nh(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 V0(e,t){return e?t?e.oid===t.oid&&e.mode===t.mode?null:Dd(e.mode)===Dd(t.mode)?"M":"T":"D":"A"}async function An(e,t={}){let n=Xd(t.limits),{root:r,common:s,git:o}=await sc(e,t.signal),i=await Ot(qd());(bo(r,i)||bo(s,i))&&H("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Bd(De(i,"canary-source-")),c,l=()=>Hd(a,{recursive:!0,force:!0});try{let d=await Xa(o,t.baseRef),u=await eh(o),h=await u(),p=new Ut(r,t.signal,!1,{GIT_INDEX_FILE:De(a,"baseline-index")});await p.run(["read-tree",d.baseSha??"--empty"]);let f=d.baseSha?Vd(await o.run(["ls-tree","-r","-z","--full-tree",d.baseSha]),!1):[],g=t.likeClone?new Set:await Za(p),m=f.filter(z=>Qd(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)&&H("snapshot_limit","This repository has too many files to upload."),th([...m,...C.tracked],n),rh(C.paths,n),await Sn(p,mo(m),!0),await Sn(o,ec(C),!1);let b=De(a,"repository.git");await Wd(b);let S=new Ut(b,t.signal,!0);await S.run(["init","--bare","--quiet","--template="]);let x=new Xr(b,n,t.signal);c=new ko(o,n);let v=[],I=[],$=sh(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 oh(o,C.tracked):new Set;await ah({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}),Qa(v,n),Qa(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 Y0(S,Ce,v,I);let ae=await x.put("commit",Buffer.from(`tree ${Le}
628
1668
  author ${go}
629
1669
  committer ${go}
630
1670
 
631
1671
  Canary snapshot baseline
632
- `)),A=await S.put("commit",Buffer.from(`tree ${Ce}
1672
+ `)),T=await x.put("commit",Buffer.from(`tree ${Ce}
633
1673
  parent ${ae}
634
1674
  author ${go}
635
1675
  committer ${go}
636
1676
 
637
1677
  Canary snapshot current
638
- `)),M=Fe(a,"source.bundle"),R=await Bk(x,M,ae,A,n),q=await So(o,r,s,t);(h!==await u()||JSON.stringify(C.paths)!==JSON.stringify(q.paths)||!t.likeClone&&JSON.stringify([...g].sort())!==JSON.stringify([...await Xa(p)].sort())||JSON.stringify(d)!==JSON.stringify(await Qa(o,t.baseRef)))&&B("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped."),await ch(r,k),await lh(r,T,t.signal),await xn(p,mo(m),!0),await xn(o,ec(C),!1);let G=new Map(v.map(z=>[z.path,z])),te=new Map($.map(z=>[z.path,z])),Ve=[];for(let z of[...new Set([...G.keys(),...te.keys()])].sort()){let gt=Kk(G.get(z),te.get(z));gt&&Ve.push({path:z,status:gt})}await c.close(),c=void 0;let xt=$.map(z=>({path:z.path,mode:z.mode,oid:z.oid})),Ze=$.filter(Bt).map(z=>z.path);return{bundlePath:M,manifest:{kind:"local_snapshot",version:2,...R,baseTreeHash:Le,treeHash:Ce,baseSha:ae,headSha:A,provenance:d},files:Ve,entries:xt,submodules:Ze,dispose:l}}catch(d){throw await c?.close(),await l(),d}}async function Yk(e,t,n,r,s,o){let i=await Et(Wd());(bo(e,i)||bo(t,i))&&B("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Ud(Fe(i,"canary-identity-"));try{let c=new qt(a,o,!0);await c.run(["init","--bare","--quiet","--template="]);let l=new Qr(a,s,o);for(let d of r.values())await l.put("blob",d);await c.run(["read-tree",await vo(n,l)]),await xn(c,mo(n),!0)}finally{await Bd(a,{recursive:!0,force:!0})}}async function Xr(e,t={}){let n=Qd(t.limits),{root:r,common:s,git:o}=await sc(e,t.signal),i;try{let a=await za(o),c=await eh(o),l=await c(),d=await So(o,r,s,t),u=await o.text(["config","--bool","--get","core.fileMode"],!0)!=="false";d.paths.length>n.maxTreeFiles&&B("snapshot_limit","This repository has too many files to upload."),th(d.tracked,n),rh(d.paths,n),await xn(o,ec(d),!1);let h=new Qr(null,n,t.signal),p=[],f=new Map,g=new Map,m=new Map,C=sh(h,n),_=(v,$,O)=>(Ek(v.path)===".gitattributes"&&m.set(v.path,$),C(v,$,O)),b=t.likeClone?await oh(o,d.tracked):new Set;await ah({root:r,current:d,trustFileMode:u,limits:n,signal:t.signal,stamps:f,heads:g,capture:_,blob:v=>(i??=new ko(o,n)).get(v),out:p,converts:b,likeClone:t.likeClone===!0}),Za(p,n);let x=await vo(p,h);[...m.values()].some(v=>/(?:^|\s)filter=lfs(?:\s|$)/m.test(v.toString("utf8")))&&await Yk(r,s,p,m,n,t.signal);let S=await So(o,r,s,t);return(l!==await c()||JSON.stringify(d.paths)!==JSON.stringify(S.paths)||a!==await za(o))&&B("source_changed","The Git state changed while the source was being read. Run the command again once editing has stopped."),await ch(r,f),await lh(r,g,t.signal),{root:r,treeHash:x,branch:a,files:p.map(v=>({path:v.path,mode:v.mode,oid:v.oid}))}}finally{await i?.close()}}var zr,He,B,Lk,Dk,wo,Co,go,bo,Gd,Cn,Vd,Hk,qt,za,ko,Qr,er,Xd,Zd,Bt,ec,mo,nh,yo,Fd,Wt=X(()=>{"use strict";w();zr={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},He=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="SourceSnapshotError"}},B=(e,t,n)=>{throw new He(e,t,n)},Lk=Pk(Mk),Dk=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=jk(e,t);return n===""||!n.startsWith(`..${Nk}`)&&n!==".."&&!Tk(n)},Gd=e=>{try{return Dk.decode(e)}catch{return B("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},Cn=e=>e.length?Gd(e).split("\0").filter(Boolean):[],Vd=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)};Hk=["-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(),_k("git",[...Hk,...t],{cwd:this.cwd,env:{...Fk(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 He("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)&&B("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()}};za=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 He("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}
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 Za(p)].sort())||JSON.stringify(d)!==JSON.stringify(await Xa(o,t.baseRef)))&&H("source_changed","The Git state changed while the source was being captured. Run the command again once editing has stopped."),await ch(r,k),await lh(r,N,t.signal),await Sn(p,mo(m),!0),await Sn(o,ec(C),!1);let J=new Map(v.map(z=>[z.path,z])),te=new Map(I.map(z=>[z.path,z])),Ye=[];for(let z of[...new Set([...J.keys(),...te.keys()])].sort()){let gt=V0(J.get(z),te.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})),Qe=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:Qe,dispose:l}}catch(d){throw await c?.close(),await l(),d}}async function K0(e,t,n,r,s,o){let i=await Ot(qd());(bo(e,i)||bo(t,i))&&H("unsafe_temporary_directory","TMPDIR is inside this repository. Point it somewhere outside the checkout, then run the command again.");let a=await Bd(De(i,"canary-identity-"));try{let c=new Ut(a,o,!0);await c.run(["init","--bare","--quiet","--template="]);let l=new Xr(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 Hd(a,{recursive:!0,force:!0})}}async function Zr(e,t={}){let n=Xd(t.limits),{root:r,common:s,git:o}=await sc(e,t.signal),i;try{let a=await za(o),c=await eh(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&&H("snapshot_limit","This repository has too many files to upload."),th(d.tracked,n),rh(d.paths,n),await Sn(o,ec(d),!1);let h=new Xr(null,n,t.signal),p=[],f=new Map,g=new Map,m=new Map,C=sh(h,n),A=(v,I,$)=>(O0(v.path)===".gitattributes"&&m.set(v.path,I),C(v,I,$)),b=t.likeClone?await oh(o,d.tracked):new Set;await ah({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}),Qa(p,n);let S=await vo(p,h);[...m.values()].some(v=>/(?:^|\s)filter=lfs(?:\s|$)/m.test(v.toString("utf8")))&&await K0(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 za(o))&&H("source_changed","The Git state changed while the source was being read. Run the command again once editing has stopped."),await ch(r,f),await lh(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 zr,We,H,L0,F0,wo,Co,go,bo,Jd,Cn,Yd,W0,Ut,za,ko,Xr,er,Zd,Qd,Ht,ec,mo,nh,yo,Dd,qt=Z(()=>{"use strict";w();zr={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"}},H=(e,t,n)=>{throw new We(e,t,n)},L0=P0(M0),F0=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=_0(e,t);return n===""||!n.startsWith(`..${j0}`)&&n!==".."&&!N0(n)},Jd=e=>{try{return F0.decode(e)}catch{return H("unsupported_path","Source paths and symlink targets must be valid UTF-8.")}},Cn=e=>e.length?Jd(e).split("\0").filter(Boolean):[],Yd=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)};W0=["-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"],Ut=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(),A0("git",[...W0,...t],{cwd:this.cwd,env:{...D0(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)&&H("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()}};za=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}
639
1679
  `);let n="";for(;!n.endsWith(`
640
- `)&&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)&&B("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&&B("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&&B("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())))}},Qr=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&&B("snapshot_limit","A file in this repository is too large to upload.");let r=Buffer.from(`${t} ${n.length}\0`),s=xo("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)&&B("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=Fe(this.directory,"objects",s.slice(0,2));await Hd(o,{recursive:!0}),await Rk(Fe(o,s.slice(2)),await Lk(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}`;Xd=e=>e.split("/").some(t=>t.toLowerCase()===".git"),Zd=(e,t)=>!t.has(e.path)&&!Xd(e.path),Bt=e=>e.mode===Co;ec=e=>e.paths.filter(t=>!e.gitlinks.has(t)),mo=e=>e.filter(t=>!Bt(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});Fd=e=>e==="120000"?"symlink":e===Co?"submodule":"file"});import{readFileSync as zk,renameSync as qE,rmSync as Qk,writeFileSync as BE}from"node:fs";async function Zr(e,t,n={}){try{await U("/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"||!Xk.has(e.cause)?Promise.resolve():Zr(`gate_allow:${e.cause}`,t,{timeoutMs:500})}function dh(e,t=Date.now()){try{let n=Ut(e,Zk),r=Date.parse(JSON.parse(zk(n,"utf8")).at??"");return Qk(n,{force:!0}),Number.isFinite(r)&&t-r>=0&&t-r<ev}catch{return!1}}var Xk,Zk,ev,_o=X(()=>{"use strict";w();fe();De();Xk=new Set(["hash_failed","lookup_timeout","lookup_unreachable","unknown_state","ceiling","crash"]);Zk="last-denial.json",ev=1440*60*1e3});import{randomUUID as tv}from"node:crypto";import{readdirSync as nv,readFileSync as zE,renameSync as rv,rmSync as hh,statSync as sv,writeFileSync as ov}from"node:fs";import{dirname as fh,join as iv}from"node:path";import{gunzipSync as ZE,gzipSync as av}from"node:zlib";function ph(e,t,n){try{let r=Ut(e,lv(t)),s=`${r}.${tv()}.tmp`,o=av(Buffer.from(JSON.stringify({version:1,at:new Date().toISOString(),treeHash:t,entries:n.map(i=>[i.path,i.mode,i.oid])})));try{ov(s,o,{flag:"wx",mode:384}),rv(s,r)}catch(i){throw hh(s,{force:!0}),i}for(let i of nv(fh(r))){if(!i.startsWith("tree-")||!i.endsWith(".json.gz"))continue;let a=iv(fh(r),i);try{Date.now()-sv(a).mtimeMs>cv&&hh(a,{force:!0})}catch{}}}catch{}}var cv,lv,oc=X(()=>{"use strict";w();De();cv=720*60*60*1e3,lv=e=>`tree-${e}.json.gz`});import{createHash as uv}from"node:crypto";import{constants as gh}from"node:fs";import{open as dv}from"node:fs/promises";import{Readable as hv}from"node:stream";function Ao(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,Sh)&&[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 fv(e,t){return vh.filter(n=>n!=="provenance").every(n=>e[n]===t[n])&&Sh.every(n=>e.provenance[n]===t.provenance[n])}function es(e,t){if(!ic(e,["uploadId","expiresAt","status","source"])||typeof e.uploadId!="string"||!Io.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)||!Ao(e.source)||t?.uploadId!==void 0&&t.uploadId!==e.uploadId||t?.manifest!==void 0&&!fv(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 xh(e){if(!Io.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 pv(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 $o(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??U)(xh(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=uv("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=hv.from(Ch(e,t.manifest.bytes,t.signal));try{let o=await(r.fetch??fetch)(`${t.baseUrl.replace(/\/+$/,"")}${xh(n)}/content`,{method:"PUT",headers:{...(r.headers??Ft)(),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 $o(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 _h(e,t={}){if(!Ao(e.manifest)||!Io.test(e.workspaceId)||!Io.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 $o(r);let s=await dv(e.bundlePath,gh.O_RDONLY|gh.O_NOFOLLOW);try{if(await wh(s,e.manifest,e.signal),r||(r=es(await(t.request??U)(kh,{...n,method:"POST",body:{workspaceId:e.workspaceId,repositoryId:e.repositoryId,source:e.manifest}}),{manifest:e.manifest})),e.onReceipt?.(r),r.status!=="pending")return $o(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"?$o(i):(await wh(s,e.manifest,e.signal),await bh(s,e,r.uploadId,t))}}catch(o){throw r?pv(o,r.uploadId):o}finally{await s.close()}}var ke,kh,Io,mh,vh,Sh,ic,ac=X(()=>{"use strict";w();fe();nt();Wt();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",Io=/^[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"],Sh=["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 gv,randomUUID as mv}from"node:crypto";import{readFileSync as yv,renameSync as wv,rmSync as $h,writeFileSync as bv}from"node:fs";function Ih(e,t,n,r="verify"){let s=gv("sha256").update(JSON.stringify([n,e,r])).digest("hex");return Ut(t,`source-upload-${s}.json`)}function Ah(e){try{let t=JSON.parse(yv(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=Ih(e,t,n,r.requestKey),o=Ah(s);o&&(!r.uploadId||o.uploadId===r.uploadId)&&$h(s,{force:!0})}async function tr(e,t,n,r,s={}){let o=Ih(e.manifest,t,n,s.requestKey),i=s.fresh?void 0:Ah(o),a=i&&Date.parse(i.expiresAt)>Date.now()?i.uploadId:void 0,c=await _h({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}.${mv()}.tmp`;try{bv(u,JSON.stringify({uploadId:l,expiresAt:d})+`
641
- `,{flag:"wx",mode:384}),wv(u,o)}finally{$h(u,{force:!0})}}});return{...c.source,uploadId:c.uploadId}}var Ro=X(()=>{"use strict";w();De();ac()});import{readFileSync as Rh}from"node:fs";function ss(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(`
642
- `),do:Array.isArray(e.do)?e.do:[]}}function Cv(e){if(e===void 0)return;let t=e;try{e==="-"?t=Rh(0,"utf8"):e.startsWith("@")&&(t=Rh(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 _v(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:D(r?.finding?.headline)||D(e.title),summary:D(r?.verdict?.reasonOneLiner??r?.finding?.whatWasTested),location:jh(r?.finding?.nextActionCodeRef??r?.codeRefs?.[0]),fix:D(r?.finding?.reproduce)||null}:e.result==="blocked"?{checkRunId:e.checkRunId,kind:"blocked",proof:"none",headline:D(e.title),summary:D(r?.verdict?.reasonOneLiner)||(os[e.blockedReason??""]??""),location:jh(r?.checkReadback?.codeRefs?.[0]??r?.codeRefs?.[0]),fix:null}:null}function uc(e,t,n){let r=ne();U("/api/v1/cli/events",{method:"POST",...r?{token:r}:{},...n?{baseUrl:n}:{},body:{outcome:e,...t?{runId:t}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function Ph(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 dc(e,t,n={}){let r=u=>U(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<kv)){n.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await ns(cc);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(!ht.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",_=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} ${_}: ${D(f.title)}`)}u.stageB.status!=="completed"&&(c=!0);let h=u.stageC.checks.length>0||u.stageB.finalChecksCount===0||lc.has(u.status);!a&&u.stageB.status==="completed"&&h&&(a=!0,n.onProgress?.(Iv(u,c?Date.now()-d:null,s)));let p=$v(u);if(p!==o&&(n.onProgress?.(p),o=p),lc.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 ns(Math.min(cc,1e3));for(let C of m)try{s.set(C.checkRunId,await r(`/api/v1/red-team/runs/${e}/checks/${C.checkRunId}/finding`))}catch(_){(!be(_)||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)=>Nh[kt(g.materiality)??"P2"]-Nh[kt(m.materiality)??"P2"]).map(g=>_v(g,s.get(g.checkRunId)??null)).filter(g=>g!==null);return{run:u,findings:f}}if(Date.now()-d>Eh)throw new bt("still_running",`run ${e} is still ${u.status} after ${Math.round(Eh/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await ns(cc)}}function $v(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 Iv(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=lc.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 Av(e,t,n){let r=e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns;if(Ph(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.":""}${Rv(n)}`}function Rv(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 Ev(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 hc(e,t,n,r){return{ok:!0,runId:e.runId,treeHash:t,status:e.status,findings:n,summary:Av(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:Ph(e),failureMessage:e.failure?.publicMessage??null,...r?{reverify:r}:{}}}function fc(e){let t=[];if(t.push(`Receipt ${so(e.treeHash)} \xB7 run ${D(e.runId)}`),e.exitCode===2)return t.push(`\u2717 Verification did not complete (${D(e.status)})${e.failureMessage?`: ${D(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 ${D(e.runId)}.`),t.join(`
643
- `);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(`${Ov[r.kind]} ${D(r.headline)}${Tv[r.kind]}`),r.summary&&t.push(` ${D(r.summary)}`),r.location&&t.push(` \u2192 ${D(r.location)}`),r.fix&&t.push(` reproduce: ${D(r.fix)}`);return e.errored>0&&t.push(`
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}),wk(u,o)}finally{Ih(u,{force:!0})}}});return{...c.source,uploadId:c.uploadId}}var Eo=Z(()=>{"use strict";w();Fe();ac()});import{readFileSync as Eh}from"node:fs";function ss(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(`
1682
+ `),do:Array.isArray(e.do)?e.do:[]}}function Ck(e){if(e===void 0)return;let t=e;try{e==="-"?t=Eh(0,"utf8"):e.startsWith("@")&&(t=Eh(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 Ak(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:_h(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)||(os[e.blockedReason??""]??""),location:_h(r?.checkReadback?.codeRefs?.[0]??r?.codeRefs?.[0]),fix:null}:null}function uc(e,t,n){let r=ne();B("/api/v1/cli/events",{method:"POST",...r?{token:r}:{},...n?{baseUrl:n}:{},body:{outcome:e,...t?{runId:t}:{}},signal:AbortSignal.timeout(1500)}).catch(()=>{})}function Ph(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 dc(e,t,n={}){let r=u=>B(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<kk)){n.onProgress?.("\u2026 cloud service unreachable \u2014 retrying"),await ns(cc);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(!ht.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||lc.has(u.status);!a&&u.stageB.status==="completed"&&h&&(a=!0,n.onProgress?.(Rk(u,c?Date.now()-d:null,s)));let p=Ik(u);if(p!==o&&(n.onProgress?.(p),o=p),lc.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 ns(Math.min(cc,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)=>jh[kt(g.materiality)??"P2"]-jh[kt(m.materiality)??"P2"]).map(g=>Ak(g,s.get(g.checkRunId)??null)).filter(g=>g!==null);return{run:u,findings:f}}if(Date.now()-d>Oh)throw new bt("still_running",`run ${e} is still ${u.status} after ${Math.round(Oh/6e4)} minutes`,"run `canary verify` again to keep following it, or check the run page");await ns(cc)}}function Ik(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 Rk(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=lc.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 Tk(e,t,n){let r=e.stageC.failedCheckRuns+e.stageC.cancelledCheckRuns;if(Ph(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.":""}${Ek(n)}`}function Ek(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 Ok(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 hc(e,t,n,r){return{ok:!0,runId:e.runId,treeHash:t,status:e.status,findings:n,summary:Tk(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:Ph(e),failureMessage:e.failure?.publicMessage??null,...r?{reverify:r}:{}}}function fc(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(`
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(`${$k[r.kind]} ${F(r.headline)}${Nk[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(`
644
1684
  (${rt(e.errored,"check")} errored and could not be verified.)`),t.push(`
645
1685
  ${e.summary}`),t.join(`
646
- `)}function is(e){let t=e;return!t||!["EPERM","EACCES","EROFS"].includes(t.code??"")||typeof t.path!="string"||!t.path.startsWith(Y())?null:{message:`Canary keeps its records under ${Y()} and cannot write there from here (${t.code})`,fix:"run the command outside the sandbox, or let it write under that folder"}}function F(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 ${D(n)}${r?`
647
- fix: ${D(r)}`:""}${i?`
648
- run: ${D(i)}`:""}`)}process.exitCode=s}async function jv(e,t,n,r,s={}){let o={baseUrl:s.baseUrl??ue()};tt({cwd:e,agent:n,mode:r!==void 0?"reverify_failed":"full"});let i=(b,x,S,v=3,$={})=>{F(n,b,x,S,v,$),uc(`exit${v}:${b}`,$.runId,o.baseUrl)},a=ne();if(!a)return i("not_logged_in","Not logged in","run `canary login` first");if(r!==void 0&&!ht.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=Cv(t),l=await _n(e,{baseRef:s.baseRef})}catch(b){if(b instanceof He||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 Sn(e,a,o.baseUrl),u=await vn({...d,token:a});let b=AbortSignal.timeout(3e3);if((await po(d,a,b).catch(S=>{throw b.aborted?new L(0,"Checking this repository's setup timed out","run `canary verify` again"):S}))?.state!=="ready")throw new bt("setup_required",`This repository isn't set up for you in ${D(u.workspace.name)} yet`,"run `canary setup`");h=await tr(l,d,u.repositoryId,a,{fresh:!0}),ph(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."),Vn();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: ${D(l.manifest.provenance.baseRef)} \xB7 source ${so(l.manifest.treeHash)}`);let f,g,m;{let b,x=rc(l.manifest.provenance.branch),S=()=>U("/api/v1/cli/runs",{method:"POST",token:a,...o,body:{repositoryId:u.repositoryId,workspaceId:d.workspaceId,source:h,...c!==void 0?{brief:c}:{},...x?{branch:x}:{},...r!==void 0?{reverifySourceRunId:r}:{}}});try{for(let $=1;;$+=1)try{b=await S();break}catch(O){if($>=Oh||!be(O)||O instanceof L&&O.runId&&ht.test(O.runId))throw O;p(`${O.message} \u2014 retrying (${$}/${Oh-1})`),await ns(Th*$)}}catch($){if($ instanceof L){let O=!be($)&&$.status>=400&&$.status<500,y=$.fix??($.status===401||$.status===403?"run `canary login`":O?void 0:"run `canary verify` again in a minute"),k={httpStatus:$.status,...$.runId?{runId:$.runId}:{}};return O?F(n,"api_error",$.message,y,3,k):i("api_error",$.message,y,2,k)}throw $}if(b.treeHash!==l.manifest.treeHash||b.headSha!==l.manifest.headSha)return F(n,"api_error","Canary's answer does not match the source that was uploaded","run `canary verify` again",2);if(!ht.test(b.runId))return F(n,"api_error","the service returned a malformed run id","run `canary verify` again in a minute",2);f=b.runId;let v=r?Ev(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&&Zr(`started_by:${dh(d)?"hook":n||Ma().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 S=0;S<3&&!g;S++)try{g=(await U(`/api/v1/red-team/runs/${f}`,{token:a,...o})).run.reverify;break}catch(v){if(!be(v)||S===2){b=!0;break}await ns(Th*(S+1))}let x={ok:!0,runId:f,runUrl:Sv(f),treeHash:l.manifest.treeHash,created:m,...g?{reverify:g}:{},next:`${xv(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(x):`Run ${f} is under way: ${x.runUrl}
649
- ${x.next}`);return}let C;try{C=await dc(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 x=b.status===401||b.status===403;return i("api_error",`${b.message} \u2014 run ${f} may still be running`,b.fix??(x?"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 _={...hc(C.run,l.manifest.treeHash,C.findings,g),source:l.manifest,repositoryId:u.repositoryId};console.log(n?JSON.stringify(_):fc(_)),process.exitCode=_.exitCode}function Mh(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{ne()&&await(await Promise.resolve().then(()=>($n(),Lh))).installByDefault({json:t.json===!0}),await jv(t.dir??process.cwd(),t.brief,t.json===!0,t.failed,{baseRef:t.base,noWait:t.wait===!1})}catch(n){let r=is(n);if(r){F(t.json===!0,"home_not_writable",r.message,r.fix,2),uc("exit2:home_not_writable");return}F(t.json===!0,"internal_error",n instanceof Error?n.message:String(n),void 0,2),uc("exit2:internal_error")}})}var cc,kv,Eh,lc,bt,D,vv,Jt,rs,ht,Sv,xv,ns,Oh,Th,jh,Nh,os,Ov,Tv,rt,Gt=X(()=>{"use strict";w();fe();nt();Z();wd();Yr();De();Wt();_o();oc();Ro();mn();cc=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,kv=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,Eh=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,lc=new Set(["completed","failed","cancelled"]),bt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="VerifyError"}},D=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ").trim(),vv=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ").trimEnd(),Jt=e=>e.split(`
650
- `).map(vv).join(`
651
- `).trim(),rs=e=>e.map(Jt).filter(t=>t!=="").join(`
652
-
653
- `);ht=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Sv=e=>`${At().replace(/\/+$/,"")}/runs/${e}`,xv=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).`,ns=e=>new Promise(t=>setTimeout(t,e)),Oh=3,Th=1e3;jh=e=>e?e.startLine?`${e.file}:${e.startLine}`:e.file:null;Nh={P0:0,P1:1,P2:2},os={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"};Ov={fail:"\u2717",blocked:"\u23F8"},Tv={fail:"",blocked:" (could not be verified)"},rt=(e,t)=>`${e} ${t}${e===1?"":"s"}`});var Lh={};Ti(Lh,{hooksStatus:()=>as,installByDefault:()=>cs,pendingPushCheck:()=>mc,registerHooks:()=>yc,runHooksInstall:()=>Uh,runHooksUninstall:()=>qh,statusLines:()=>Eo});function gc(e,t=[]){try{Te(n=>({...n,hooks:{...n.hooks?.codex?{codex:n.hooks.codex}:{},state:e,at:new Date().toISOString(),...t.length?{refused:t}:{}}}))}catch{}}function Nv(e){return[pc,"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(`
654
- `).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${Dh}`].join(`
655
- `)}function Hh(e){for(let t of e)t.result==="refused"?console.log(`\u2717 ${t.file} was left alone: ${t.detail}. To do it by hand:
656
- ${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}`:""}${Fh(t.edit?.backup??t.removed?.backup)}`)}function Pv(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}`);Zs("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 Mv(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 Uh(e){let t=e.targets??Wr(),{targets:n,unknown:r}=Mv(t,e.harnesses),s=n.flatMap(i=>i.plan());if(r.length)return F(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(`
657
- `));return}if(e.plan){console.log(e.json?JSON.stringify({ok:!0,plan:s}):Nv(s));return}let o=n.flatMap(i=>i.install());o.some(i=>i.result!=="refused")&&gc("installed"),e.json?console.log(JSON.stringify({ok:!o.some(i=>i.result==="refused"),outcomes:o,canaryOnPath:Zs("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}`)})):(Hh(o),Pv(o,n)),o.some(i=>i.result==="refused")&&(process.exitCode=2)}function qh(e){let t=(e.targets??Wr()).flatMap(n=>n.uninstall());gc("removed"),e.json?console.log(JSON.stringify({ok:!t.some(n=>n.result==="refused"),outcomes:t})):Hh(t),t.some(n=>n.result==="refused")&&(process.exitCode=2)}function as(e=Wr()){return{mode:wn(),registration:K().hooks?.state??null,canaryOnPath:Zs("canary"),harnesses:e.map(t=>({harness:t.id,label:t.label,detected:t.detected(),items:t.status()}))}}function mc(e){try{return wn()==="off"?[]:as(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 Eo(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 cs(e){try{if(process.env.CI||!e.targets&&process.env.NODE_TEST_CONTEXT)return;let t=K();if(t.agentSkills===!1||t.hooks?.state==="removed")return;let n=new Set(t.hooks?.refused??[]);if(t.hooks?.state==="installed"&&!n.size)return;let r=(e.targets??Wr()).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")gc("installed",a);else if(a.length)try{Te(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:pc,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(`
1686
+ `)}function is(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
+ fix: ${F(r)}`:""}${i?`
1688
+ run: ${F(i)}`:""}`)}process.exitCode=s}async function _k(e,t,n,r,s={}){let o={baseUrl:s.baseUrl??ue()};tt({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),uc(`exit${v}:${b}`,I.runId,o.baseUrl)},a=ne();if(!a)return i("not_logged_in","Not logged in","run `canary login` first");if(r!==void 0&&!ht.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=Ck(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}),ph(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=rc(l.manifest.provenance.branch),x=()=>B("/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&&ht.test($.runId))throw $;p(`${$.message} \u2014 retrying (${I}/${$h-1})`),await ns(Nh*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(!ht.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?Ok(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&&Qr(`started_by:${dh(d)?"hook":n||Ma().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 B(`/api/v1/red-team/runs/${f}`,{token:a,...o})).run.reverify;break}catch(v){if(!be(v)||x===2){b=!0;break}await ns(Nh*(x+1))}let S={ok:!0,runId:f,runUrl:xk(f),treeHash:l.manifest.treeHash,created:m,...g?{reverify:g}:{},next:`${Sk(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}
1689
+ ${S.next}`);return}let C;try{C=await dc(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={...hc(C.run,l.manifest.treeHash,C.findings,g),source:l.manifest,repositoryId:u.repositoryId};console.log(n?JSON.stringify(A):fc(A)),process.exitCode=A.exitCode}function Mh(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{ne()&&await(await Promise.resolve().then(()=>(In(),Lh))).installByDefault({json:t.json===!0}),await _k(t.dir??process.cwd(),t.brief,t.json===!0,t.failed,{baseRef:t.base,noWait:t.wait===!1})}catch(n){let r=is(n);if(r){D(t.json===!0,"home_not_writable",r.message,r.fix,2),uc("exit2:home_not_writable");return}D(t.json===!0,"internal_error",n instanceof Error?n.message:String(n),void 0,2),uc("exit2:internal_error")}})}var cc,kk,Oh,lc,bt,F,vk,Gt,rs,ht,xk,Sk,ns,$h,Nh,_h,jh,os,$k,Nk,rt,Jt=Z(()=>{"use strict";w();fe();nt();Q();wd();Kr();Fe();qt();Ao();oc();Eo();mn();cc=Number(process.env.CANARY_VERIFY_POLL_MS)||3e3,kk=Number(process.env.CANARY_VERIFY_GRACE_MS)||9e4,Oh=Number(process.env.CANARY_VERIFY_MAX_MS)||60*6e4,lc=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(),vk=e=>(e??"").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ").trimEnd(),Gt=e=>e.split(`
1690
+ `).map(vk).join(`
1691
+ `).trim(),rs=e=>e.map(Gt).filter(t=>t!=="").join(`
1692
+
1693
+ `);ht=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,xk=e=>`${Tt().replace(/\/+$/,"")}/runs/${e}`,Sk=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).`,ns=e=>new Promise(t=>setTimeout(t,e)),$h=3,Nh=1e3;_h=e=>e?e.startLine?`${e.file}:${e.startLine}`:e.file:null;jh={P0:0,P1:1,P2:2},os={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"};$k={fail:"\u2717",blocked:"\u23F8"},Nk={fail:"",blocked:" (could not be verified)"},rt=(e,t)=>`${e} ${t}${e===1?"":"s"}`});var Lh={};Ni(Lh,{hooksStatus:()=>as,installByDefault:()=>cs,pendingPushCheck:()=>mc,registerHooks:()=>yc,runHooksInstall:()=>Bh,runHooksUninstall:()=>Uh,statusLines:()=>Oo});function gc(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 jk(e){return[pc,"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(`
1694
+ `).map(n=>` ${n}`),""]),`Only these user-level files are touched, never a repository. ${Fh}`].join(`
1695
+ `)}function Wh(e){for(let t of e)t.result==="refused"?console.log(`\u2717 ${t.file} was left alone: ${t.detail}. To do it by hand:
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}`:""}${Dh(t.edit?.backup??t.removed?.backup)}`)}function Pk(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 Mk(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 Bh(e){let t=e.targets??qr(),{targets:n,unknown:r}=Mk(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(`
1697
+ `));return}if(e.plan){console.log(e.json?JSON.stringify({ok:!0,plan:s}):jk(s));return}let o=n.flatMap(i=>i.install());o.some(i=>i.result!=="refused")&&gc("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}`)})):(Wh(o),Pk(o,n)),o.some(i=>i.result==="refused")&&(process.exitCode=2)}function Uh(e){let t=(e.targets??qr()).flatMap(n=>n.uninstall());gc("removed"),e.json?console.log(JSON.stringify({ok:!t.some(n=>n.result==="refused"),outcomes:t})):Wh(t),t.some(n=>n.result==="refused")&&(process.exitCode=2)}function as(e=qr()){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 mc(e){try{return wn()==="off"?[]:as(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 cs(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??qr()).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")gc("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:pc,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(`
658
1698
  Canary added its push check to ${u} (${l.map(h=>h.file).join(", ")}).
659
1699
  ${pc}
660
- ${Dh}`)}for(let u of d)console.error(`Canary ${u.edit.created?"created":"edited"} ${u.file}: ${u.detail}${Fh(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 yc(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 Uh({plan:n.plan===!0,json:n.json===!0,harnesses:n.harness})}catch(r){F(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{qh({json:n.json===!0})}catch(r){F(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=as();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(`The push check is ${r.mode}.`);for(let s of Eo(r))console.log(s)}})}var pc,Dh,Fh,$n=X(()=>{"use strict";w();Z();ro();Sa();Gt();pc="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.",Dh="Switch it off: `canary gate off` \xB7 take it out: `canary hooks uninstall`.";Fh=e=>e?` (the file as it was: ${e})`:""});w();w();var ru=Oy(nu(),1),{program:sA,createCommand:oA,createArgument:iA,createOption:aA,CommanderError:cA,InvalidArgumentError:lA,InvalidOptionArgumentError:uA,Command:su,Argument:dA,Option:hA,Help:fA}=ru.default;w();Aa();to();fe();mn();Z();$n();De();import{createHash as Vv,randomBytes as nf}from"node:crypto";import{spawn as Kv}from"node:child_process";import{createServer as Yv}from"node:http";w();fe();Yr();function Bh(e){try{return new URL(e).href.replace(/\/+$/,"")}catch{return}}var wc=Ld;async function Wh(e,t,n,r){let s=await U("/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&&Bh(n)===Bh(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=wc();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 Oo(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 To(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 Jh}from"node:util";var ve="\x1B[";function us(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 Jh(e).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var bc=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Gh(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 ls(e){return[...bc.segment(Jh(e))].reduce((t,n)=>t+Gh(n.segment),0)}function jo(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 bc.segment(s))n+=Gh(o),n<=t&&(r+=o)}return r}function Vt(e,t){let n=[],r="";for(let s of ie(e).split(/\s+/)){r&&ls(r+" "+s)>t&&(n.push(r),r="");for(let{segment:o}of bc.segment((r?" ":"")+s))ls(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(`
1700
+ ${Fh}`)}for(let u of d)console.error(`Canary ${u.edit.created?"created":"edited"} ${u.file}: ${u.detail}${Dh(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 yc(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 Bh({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{Uh({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=as();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 pc,Fh,Dh,In=Z(()=>{"use strict";w();Q();ro();xa();Jt();pc="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.",Fh="Switch it off: `canary gate off` \xB7 take it out: `canary hooks uninstall`.";Dh=e=>e?` (the file as it was: ${e})`:""});w();w();var ru=$y(nu(),1),{program:sR,createCommand:oR,createArgument:iR,createOption:aR,CommanderError:cR,InvalidArgumentError:lR,InvalidOptionArgumentError:uR,Command:su,Argument:dR,Option:hR,Help:fR}=ru.default;w();Ta();to();fe();mn();Q();In();Fe();import{createHash as Yk,randomBytes as nf}from"node:crypto";import{spawn as Vk}from"node:child_process";import{createServer as Kk}from"node:http";w();fe();Kr();function Hh(e){try{return new URL(e).href.replace(/\/+$/,"")}catch{return}}var wc=Ld;async function qh(e,t,n,r){let s=await B("/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&&Hh(n)===Hh(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=wc();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 Gh}from"node:util";var ve="\x1B[";function us(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 Gh(e).replace(/[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g," ")}var bc=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Jh(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 ls(e){return[...bc.segment(Gh(e))].reduce((t,n)=>t+Jh(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 bc.segment(s))n+=Jh(o),n<=t&&(r+=o)}return r}function Yt(e,t){let n=[],r="";for(let s of ie(e).split(/\s+/)){r&&ls(r+" "+s)>t&&(n.push(r),r="");for(let{segment:o}of bc.segment((r?" ":"")+s))ls(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(`
661
1701
  `)===t.join(`
662
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(ls(a)/r)),0));e.write((o?`\r${ve}${o}A`:"")+`${ve}0J`+(n.length?n.join(`\r
663
1703
  `)+`\r
664
- `:"")),t=n}}}function Vh(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:
1704
+ `:"")),t=n}}}function Yh(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:
665
1705
  `:" ")+n+`
666
- `]}function Kh(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 No(e){return`Repository ${ie(e)}`}var In="Next: in your coding agent, type /canary to check your changes.";function Yh(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 Lv}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[",Dv={gold:"33",text:"39",muted:"90",green:"32"};function Fv(e,t,n){if(!n)return e;let r=t==="gold"?"38;2;255;212;0":Dv[t];return`${ds}${r}m${e}${ds}0m`}function zh(e){return Lv(e).replace(/[\x00-\x1f\x7f-\x9f]/g," ")}var Qh=1.4;function Hv(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,x="text")=>Fv(b,x,o),C=t==="success"?"green":t==="failed"?"muted":"gold",_;if(s<5)_=[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")};_=["",...p.map((x,S)=>` ${m(x,C)} ${b[S]??""}`)]}else r>=42&&s>=23?_=["",...p.map(b=>` ${m(b,C)}`),` ${m("CANARY","gold")}`,"",` ${m(f)}`,` ${m(g,"muted")}`]:_=["",` ${m("CANARY","gold")}`,` ${m(f)}`];return s>=10&&(_.push("",` ${m("\u2500".repeat(Math.max(1,Math.min(54,r-5))),"gold")}`),(t==="waiting"||t==="saving")&&_.push(` ${m("Ctrl+C","muted")} ${m("cancel sign-in","muted")}`),_.push("")),_.slice(0,Math.max(1,s-2)).map(b=>{let x=0;return b.replace(/\x1b\[[0-9;]*m|[^\x1b]/gu,S=>S.startsWith("\x1B")||++x<r?S:"")})}function Xh(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),_=performance.now(),b=Hv({phase:s,seconds:(_-r)/1e3,phaseSeconds:(_-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.
667
- `),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(`${ds}?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)}
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(`${ds}?25l`),l(),{saving(){i("saving"),l()},celebrate(){return i("success"),l(),new Promise(m=>setTimeout(m,Xh*1e3+100))},succeed(m,C){i("success"),l(),u(),process.stdout.write(` Account ${zh(m)}
668
1708
  Workspace ${zh(C)}
669
1709
 
670
- `)},fail(){i("failed"),l(),u()},clear(){a.render([]),u()},stop:u}}w();import{spawn as Uv}from"node:child_process";import{createInterface as qv,emitKeypressEvents as Bv}from"node:readline";function kc(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 vc(e){return e.workspaces.length>1}function Wv(e){return!e||e.result==="skipped"?null:e.result==="refused"?`Not added \xB7 ${e.detail}`:"Added \xB7 new Claude Code chats load it"}var Zh="/canary";async function ef(e){let t=process.stdin,n=process.stderr,r=t.readableFlowing===!0;n.write(`Choose a workspace:
1710
+ `)},fail(){i("failed"),l(),u()},clear(){a.render([]),u()},stop:u}}w();import{spawn as Bk}from"node:child_process";import{createInterface as Uk,emitKeypressEvents as Hk}from"node:readline";function kc(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 vc(e){return e.workspaces.length>1}function qk(e){return!e||e.result==="skipped"?null:e.result==="refused"?`Not added \xB7 ${e.detail}`:"Added \xB7 new Claude Code chats load it"}var Qh="/canary";async function ef(e){let t=process.stdin,n=process.stderr,r=t.readableFlowing===!0;n.write(`Choose a workspace:
671
1711
  `),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)})`:""}
672
- `)});let s=qv({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 To(e,i.trim())}catch(a){n.write(`${a instanceof Error?a.message:"Choose a listed workspace."}
673
- Workspace (number or name): `)}}finally{process.off("SIGINT",o),s.close(),r||t.pause()}}function Jv(e,t,n,r){let{context:s}=e,o=Math.max(1,t-5),i=(h,p="text")=>us(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&&vc(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)}`:"",_=!s.selectionRequired&&g.id===s.workspace.id?" \xB7 current":"";c.push(a(`${f===e.highlighted?"\u203A":" "} ${f+1}. ${ie(g.name)}${C}${_}`,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 ${kc(e.skill)}`,e.skill&&kc(e.skill).startsWith("Installed")?"green":"muted"));let p=Wv(e.plugin);p&&c.push(a(`Plugin ${p}`,e.plugin?.result==="refused"?"muted":"green")),s.workspaceNotice&&c.push(...Vt(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&&kc(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(...Vt(Zh,o-2).map(g=>a(`\u2502 ${g}`))),e.done||c.push("",a(`${vc(s)?"[w] Workspace ":""}[c] Copy [enter] Done`,"gold")),e.message&&c.push(...Vt(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=>jo(h,Math.max(1,t-1)))}async function Gv(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=Uv(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 tf(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(Jv(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(`
674
- ${In}
675
- `);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 _=e.sessionCurrent();_?i():o.render(["CLI session changed in another process. Run canary whoami to check the active account."]),f(),_&&!r.context.selectionRequired&&n.write(`
676
- ${In}
1712
+ `)});let s=Uk({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."}
1713
+ Workspace (number or name): `)}}finally{process.off("SIGINT",o),s.close(),r||t.pause()}}function Gk(e,t,n,r){let{context:s}=e,o=Math.max(1,t-5),i=(h,p="text")=>us(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&&vc(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 ${kc(e.skill)}`,e.skill&&kc(e.skill).startsWith("Installed")?"green":"muted"));let p=qk(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&&kc(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(Qh,o-2).map(g=>a(`\u2502 ${g}`))),e.done||c.push("",a(`${vc(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 Jk(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=Bk(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 tf(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(Gk(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
+ ${Rn}
1715
+ `);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
+ ${Rn}
677
1717
 
678
- `),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(_,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 x=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)<=x)r.highlighted=Number(b.sequence)-1;else if(b.name==="up")r.highlighted=(r.highlighted+x-1)%x;else if(b.name==="down")r.highlighted=(r.highlighted+1)%x;else if(b.name==="return"){let S=r.context.workspaces[r.highlighted];try{e.selectWorkspace(S),r.context={...r.context,workspace:S,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(x=>x.id===r.context.workspace.id));else if(b.name==="c"&&!u){let x=new AbortController;u=x,l.signal.addEventListener("abort",()=>x.abort(),{once:!0}),Gv(Zh,x.signal).then(S=>{u===x&&(u=void 0),!d&&(r.message=S?"Instruction copied. Paste it into your coding agent.":"Clipboard unavailable. Select the instruction above to copy it.",i())})}i()}}}Bv(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 zv=900*1e3,Qv=6e4;var rf=e=>e.toString("base64url");function Xv(e){let t=process.platform,[n,r]=t==="darwin"?["open",[e]]:t==="win32"?["explorer.exe",[e]]:["xdg-open",[e]];try{let s=Kv(n,r,{stdio:"ignore",detached:!0});s.on("error",()=>{}),s.unref()}catch{}}function Zv(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 eS(e){return new Promise((t,n)=>{let r,s,o=new Promise((l,d)=>{r=l,s=d}),i=Yv((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(Zv(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")),zv);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 tS(e,t){let n=K(),r=n.apiUrl||ue(),s=(t.apiUrl||ue()).replace(/\/+$/,""),o=rf(nf(32)),i=Vv("sha256").update(o).digest("base64url"),a=rf(nf(16)),{port:c,code:l,close:d}=await eS(a),u=`http://127.0.0.1:${c}/callback`,h=(t.webUrl||At()).replace(/\/+$/,""),p=`${h}/cli/authorize?challenge=${encodeURIComponent(i)}&state=${encodeURIComponent(a)}&redirect=${encodeURIComponent(u)}`;for(let C of Vh(e,t.open,p))console.error(C);let f=Xh({json:e,animation:t.animation,open:t.open}),g=Date.now(),m=f?void 0:setInterval(()=>console.error(Kh(e,Math.round((Date.now()-g)/1e3))),Qv);m?.unref?.();try{t.open&&Xv(p);let C=await l;m&&clearInterval(m),f?.saving();let _=await U("/api/v1/cli/auth/token",{method:"POST",body:{code:C,codeVerifier:o},baseUrl:s});return f&&await f.celebrate(),f?.clear(),await of(_,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){Te(({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 Wh(e,t,n,r);o.workspace!==void 0&&(i.workspace=To(i,o.workspace),i.source="selected in CLI",i.selectionRequired=!1),i.selectionRequired||Te(g=>({...g,team:i.workspace}));let a=o.agentSkills?Jr():void 0,c=o.agentSkills?Ia():void 0,l=()=>{let g=K();return g.token===e.token&&g.apiUrl===r},d=g=>{Te(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=>Oo({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=K().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 ${At()}, 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,_)=>console.log(` ${_+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(No(f.name));for(let g of[a&&nS(a),Yh(c)])g&&console.log(g);console.log(In)}return h}async function sf(e,t,n){let r=K(),s=r.apiUrl||ue(),o=(n.apiUrl||ue()).replace(/\/+$/,""),i=await U("/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 nS(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 tS(n,{webUrl:t.webUrl,apiUrl:t.apiUrl,workspace:t.workspace,open:t.open!==!1,animation:t.animation!==!1,agentSkills:t.agentSkills!==!1}),Vn())}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();Z();ro();$n();w();fe();Z();De();w();fe();De();var An=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 cf(e,t,n,r={}){let s=AbortSignal.timeout(r.timeoutMs??An);try{let o=await U(`/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 xc(e,t={}){let{signal:n}=t,r=ne();if(!r)return{ok:!1,cause:"not_logged_in"};let s=K(),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 U("/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"}}}_o();nt();De();w();Z();De();import{randomUUID as rS}from"node:crypto";import{mkdirSync as sS,readFileSync as lf,renameSync as oS,rmSync as iS,writeFileSync as aS}from"node:fs";import{dirname as cS,join as lS}from"node:path";var uS="skips.json",dS=720*60*60*1e3,hS=1440*60*1e3,fS=(e,t)=>{let n=Date.parse(e.at);return Number.isFinite(n)&&t-n<dS&&n-t<hS};function uf(e,t=Date.now()){let n={version:1,skips:{}},r;try{r=JSON.parse(lf(Ut(e,uS),"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"&&fS(i,t)&&(n.skips[o]={reason:i.reason,at:i.at,...typeof i.branch=="string"?{branch:i.branch}:{}});return n}var Po=()=>lS(Y(),"hold","skips.json"),pS=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<pS&&(r[s]={reason:o.reason,at:o.at})}return r}function hf(e){let t=Po(),n=`${t}.${rS()}.tmp`;sS(cS(t),{recursive:!0,mode:448});try{aS(n,JSON.stringify({version:1,skips:e},null,2)+`
679
- `,{flag:"wx",mode:384}),oS(n,t)}catch(r){throw iS(n,{force:!0}),r}}function ff(e,t,n=Date.now()){return Pr(`${Po()}.lock`,"the push skips",()=>{let r=df(n),s={reason:t,at:new Date(n).toISOString()};return hf({...r,[e]:s}),s})}function pf(e,t=Date.now()){try{return Pr(`${Po()}.lock`,"the push skips",()=>{let n=df(t),r=n[e];return r?(delete n[e],hf(n),{reason:r.reason}):null})}catch{return null}}Gt();var gS=500,gf={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 mf(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 mS(e,t){try{if(!yd(e))return F(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 F(t,"config_busy",n.message,void 0,2);throw n}console.log(t?JSON.stringify({ok:!0,mode:e}):mf(e))}async function yS(e,t,n){let r=(t??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,gS);if(!r)return F(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 F(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=ff(s,r)}catch(a){if(a instanceof hn)return F(n,"config_busy",a.message,void 0,2);throw a}let i=ne();i&&await Zr("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 (${D(o.reason)}).`)}async function wS(e,t){fo(e);let n=await xc(e);if(!n.ok){let[s,o]=gf[n.cause]??gf.context_error;return F(t,n.cause,s,o,3)}let r=Object.entries(uf(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?D(s.branch):"(detached)"} ${D(s.reason)}`)}function yf(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=>mS(n,r.json===!0));t.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let r=as();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(mf(r.mode));for(let s of Eo(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 wS(n.dir??process.cwd(),r):await yS(n.dir??process.cwd(),n.reason,r)}catch(s){F(r,"internal_error",s instanceof Error?s.message:String(s),void 0,2)}})}$n();w();nt();var bS={[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 wf(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=Ft();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)":bS[r]??"";console.log(`${r.padEnd(18)} ${s}${o?` ${o}`:""}`)}})}w();fe();import{execFileSync as Yg,spawn as zg}from"node:child_process";import{createHash as gC,randomBytes as mC}from"node:crypto";import{appendFileSync as yC,closeSync as wC,constants as ui,copyFileSync as bC,existsSync as Ae,mkdirSync as Dn,openSync as kC,readdirSync as yi,readFileSync as Pt,realpathSync as cn,rmSync as Fn,statSync as _r,utimesSync as vC,writeFileSync as Es,writeSync as SC}from"node:fs";import{homedir as yl}from"node:os";import{basename as wl,dirname as pt,join as P,relative as Qg,resolve as $l,sep as wi}from"node:path";w();fe();Z();nt();import{execFile as VS}from"node:child_process";import{copyFileSync as Zf,existsSync as ep,mkdirSync as tp,mkdtempSync as KS,readdirSync as np,readFileSync as YS,renameSync as zS,rmSync as Dc,statSync as QS,writeFileSync as Ko}from"node:fs";import{tmpdir as XS}from"node:os";import{join as $e,resolve as Xf}from"node:path";import{promisify as ZS}from"node:util";w();Z();import{createHash as Fo,randomBytes as vS}from"node:crypto";import{execFileSync as Ac}from"node:child_process";import{existsSync as ge,mkdirSync as Oe,readdirSync as ft,readFileSync as ar,realpathSync as xf,renameSync as SS,rmSync as Ne,statfsSync as xS,statSync as CS,utimesSync as _S,writeFileSync as Yt}from"node:fs";import{createServer as $S}from"node:net";import{basename as $c,dirname as IS,join as N,resolve as AS}from"node:path";w();import{spawn as kS}from"node:child_process";var bf=()=>process.env.SANDBOX_RUNTIME==="1",Cc=()=>!!(process.env.https_proxy||process.env.HTTPS_PROXY||process.env.http_proxy||process.env.HTTP_PROXY);function _c(){let[e,t]=process.versions.node.split(".").map(Number);return e>=24||e===22&&t>=21}var kf="Node 22.21 or later (or 24 and later)";function vf(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 Sf(){if(process.argv[2]!=="jobs"||!Cc()||!_c()||process.env.NODE_USE_ENV_PROXY==="1")return!1;let e=kS(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 RS=12*6e4,ES=720*6e4,OS=336*60*6e4,TS=3e3,jS=42e3,Ic=100,Cf=40,Lo=2,j=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="JobsError"}},W=()=>N(Y(),"jobs"),NS=2.2,_f=26e8,PS=1e9;function Rc(e,t,n=null){let r=Math.ceil(n!==null?e+n+_f:t?e+PS:e*NS+_f),s=Ec();return s<r?{needBytes:r,freeBytes:s}:null}function Ec(){Oe(W(),{recursive:!0,mode:448});let{bavail:e,bsize:t}=xS(W());return e*t}var MS=e=>(Math.ceil(e/1e8)/10).toFixed(1),LS=e=>(Math.floor(e/1e8)/10).toFixed(1),hs=e=>`This batch's copy and the app's dependencies need about ${MS(e.needBytes)} GB of free disk, and ${LS(e.freeBytes)} GB is free.`;function If(){let e=W();try{Oe(e,{recursive:!0,mode:448});let t=N(e,`.write-check-${process.pid}`);Yt(t,""),Ne(t,{force:!0})}catch(t){let n=t.code;throw n!=="EPERM"&&n!=="EACCES"&&n!=="EROFS"?t:Ho(n)}}function Ho(e){let t=W();return new j("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. ${vf(t)}`)}function cr(){let e=Number(process.env.CLAUDE_PID);if(!Number.isInteger(e)||e<=0)return null;let t=It(e);return t===null?null:{pid:e,startedAt:t}}function Xt(e){try{process.kill(e.pid,0)}catch(n){if(n.code==="ESRCH")return"gone"}if(DS(e.pid))return"gone";let t=It(e.pid);return t===null?"unknown":Math.abs(t-e.startedAt)<=TS?"alive":"gone"}function DS(e){try{return Ac("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||Xt(e)!=="gone"}var Af=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function st(e,t){if(!Af.test(e))throw new j("bad_id",`${JSON.stringify(e)} isn't a ${t} id.`,`Use the ${t} id Canary printed.`);return e}function _e(){let e=process.env.CLAUDE_CODE_SESSION_ID?.trim();if(!e)throw new j("no_session","canary jobs runs only inside a Claude Code session.");return e}function V(e){try{return JSON.parse(ar(e,"utf8"))}catch{return null}}function Pe(e,t,n=384){let r=`${e}.${process.pid}.tmp`;Yt(r,JSON.stringify(t,null,2)+`
680
- `,{mode:n}),SS(r,e)}function Rf(e){try{let t=new Date;_S(e,t,t)}catch{}}var Do=(e,t)=>{try{return Date.now()-CS(e).mtimeMs>=t}catch{return!0}},or=e=>N(W(),"sessions",`${/^[A-Za-z0-9_-]{1,128}$/.test(e)?e:Fo("sha256").update(e).digest("hex").slice(0,32)}.json`);function ot(e){return V(or(e))??{sessionId:e,runs:{},cursors:{}}}function vt(e,t){Oe(N(W(),"sessions"),{recursive:!0,mode:448});let n=t(ot(e));return Pe(or(e),n),n}function FS(){let e=N(W(),"sessions");return ge(e)?ft(e).filter(t=>t.endsWith(".json")).map(t=>V(N(e,t))).filter(t=>t!==null):[]}function Ef(e){let t=`${or(e)}.watch`,n=`${process.pid} ${Date.now()}`;return Oe(N(W(),"sessions"),{recursive:!0,mode:448}),Yt(t,n),()=>{try{return ar(t,"utf8")===n}catch{return!1}}}function Of(e){try{return xf(Ac("git",["-C",e,"rev-parse","--path-format=absolute","--git-common-dir"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim())}catch{try{return xf(e)}catch{return AS(e)}}}function HS(e){let t=n=>Ac("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(`
681
- `).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 US=(e,t)=>!!e&&!!t&&e!==t&&e.split(":")[0]===t.split(":")[0],Kt=()=>N(W(),"repos"),ir=e=>`${e.name.replace(/[^\w.-]/g,"_")}-${e.id.slice(0,8)}`;function Tf(){return ge(Kt())?ft(Kt()).map(e=>V(N(Kt(),e,"repo.json"))).filter(e=>e!==null):[]}function Mo(e){return Oe(N(Kt(),ir(e)),{recursive:!0,mode:448}),Pe(N(Kt(),ir(e),"repo.json"),e),e}function Be(e){let t=Of(e);return Tf().find(n=>n.path===t)??null}function Rn(e,t={}){let n=Of(e),r=Tf(),s=r.find(a=>a.path===n);if(s&&!t.verify)return s;let o=HS(e);if(s){if(!US(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:vS(8).toString("hex"),path:n,identity:o,name:$c(n)===".git"?$c(IS(n)):$c(n)})}function Qe(e){let t=N(Kt(),ir(e));return{dir:t,canaryMd:N(t,"canary.md"),secrets:N(t,"secrets.env"),scripts:N(t,"scripts")}}var jf=e=>N(Kt(),e,"scripts"),zt="## How the app runs here",Nf=`# Canary
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}),ov(n,t)}catch(r){throw iv(n,{force:!0}),r}}function ff(e,t,n=Date.now()){return Pr(`${Po()}.lock`,"the push skips",()=>{let r=df(n),s={reason:t,at:new Date(n).toISOString()};return hf({...r,[e]:s}),s})}function pf(e,t=Date.now()){try{return Pr(`${Po()}.lock`,"the push skips",()=>{let n=df(t),r=n[e];return r?(delete n[e],hf(n),{reason:r.reason}):null})}catch{return null}}Jt();var gv=500,gf={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 mf(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 mv(e,t){try{if(!yd(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}):mf(e))}async function yv(e,t,n){let r=(t??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"").replace(/\s+/g," ").trim().slice(0,gv);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=ff(s,r)}catch(a){if(a instanceof hn)return D(n,"config_busy",a.message,void 0,2);throw a}let i=ne();i&&await Qr("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 wv(e,t){fo(e);let n=await Sc(e);if(!n.ok){let[s,o]=gf[n.cause]??gf.context_error;return D(t,n.cause,s,o,3)}let r=Object.entries(uf(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 yf(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=>mv(n,r.json===!0));t.command("status").description("Show whether the check is on").option("--json","print one JSON document").action(n=>{let r=as();if(n.json===!0)console.log(JSON.stringify({ok:!0,...r}));else{console.log(mf(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 wv(n.dir??process.cwd(),r):await yv(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 bv={[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 wf(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=Dt();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)":bv[r]??"";console.log(`${r.padEnd(18)} ${s}${o?` ${o}`:""}`)}})}w();fe();import{execFileSync as Kg,spawn as zg}from"node:child_process";import{createHash as g1,randomBytes as m1}from"node:crypto";import{appendFileSync as y1,closeSync as w1,constants as ui,copyFileSync as b1,existsSync as Te,mkdirSync as Fn,openSync as k1,readdirSync as yi,readFileSync as Pt,realpathSync as cn,rmSync as Dn,statSync as Ar,utimesSync as v1,writeFileSync as Os,writeSync as x1}from"node:fs";import{homedir as yl}from"node:os";import{basename as wl,dirname as pt,join as P,relative as Xg,resolve as Il,sep as wi}from"node:path";w();fe();Q();nt();import{execFile as Yv}from"node:child_process";import{copyFileSync as Qf,existsSync as ep,mkdirSync as tp,mkdtempSync as Vv,readdirSync as np,readFileSync as Kv,renameSync as zv,rmSync as Fc,statSync as Xv,writeFileSync as Vo}from"node:fs";import{tmpdir as Zv}from"node:os";import{join as Ie,resolve as Zf}from"node:path";import{promisify as Qv}from"node:util";w();Q();import{createHash as Do,randomBytes as vv}from"node:crypto";import{execFileSync as Tc}from"node:child_process";import{existsSync as ge,mkdirSync as $e,readdirSync as ft,readFileSync as ar,realpathSync as Sf,renameSync as xv,rmSync as je,statfsSync as Sv,statSync as Cv,utimesSync as Av,writeFileSync as Kt}from"node:fs";import{createServer as Iv}from"node:net";import{basename as Ic,dirname as Rv,join as j,resolve as Tv}from"node:path";w();import{spawn as kv}from"node:child_process";var bf=()=>process.env.SANDBOX_RUNTIME==="1",Cc=()=>!!(process.env.https_proxy||process.env.HTTPS_PROXY||process.env.http_proxy||process.env.HTTP_PROXY);function Ac(){let[e,t]=process.versions.node.split(".").map(Number);return e>=24||e===22&&t>=21}var kf="Node 22.21 or later (or 24 and later)";function vf(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 xf(){if(process.argv[2]!=="jobs"||!Cc()||!Ac()||process.env.NODE_USE_ENV_PROXY==="1")return!1;let e=kv(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 Ev=12*6e4,Ov=720*6e4,$v=336*60*6e4,Nv=3e3,_v=42e3,Rc=100,Cf=40,Lo=2,_=class extends Error{constructor(n,r,s){super(r);this.code=n;this.fix=s;this.name="JobsError"}},q=()=>j(K(),"jobs"),jv=2.2,Af=26e8,Pv=1e9;function Ec(e,t,n=null){let r=Math.ceil(n!==null?e+n+Af:t?e+Pv:e*jv+Af),s=Oc();return s<r?{needBytes:r,freeBytes:s}:null}function Oc(){$e(q(),{recursive:!0,mode:448});let{bavail:e,bsize:t}=Sv(q());return e*t}var Mv=e=>(Math.ceil(e/1e8)/10).toFixed(1),Lv=e=>(Math.floor(e/1e8)/10).toFixed(1),hs=e=>`This batch's copy and the app's dependencies need about ${Mv(e.needBytes)} GB of free disk, and ${Lv(e.freeBytes)} GB is free.`;function Rf(){let e=q();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=q();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. ${vf(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(Fv(e.pid))return"gone";let t=Rt(e.pid);return t===null?"unknown":Math.abs(t-e.startedAt)<=Nv?"alive":"gone"}function Fv(e){try{return Tc("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 Tf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function st(e,t){if(!Tf.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)+`
1720
+ `,{mode:n}),xv(r,e)}function Ef(e){try{let t=new Date;Av(e,t,t)}catch{}}var Fo=(e,t)=>{try{return Date.now()-Cv(e).mtimeMs>=t}catch{return!0}},or=e=>j(q(),"sessions",`${/^[A-Za-z0-9_-]{1,128}$/.test(e)?e:Do("sha256").update(e).digest("hex").slice(0,32)}.json`);function ot(e){return Y(or(e))??{sessionId:e,runs:{},cursors:{}}}function vt(e,t){$e(j(q(),"sessions"),{recursive:!0,mode:448});let n=t(ot(e));return Pe(or(e),n),n}function Dv(){let e=j(q(),"sessions");return ge(e)?ft(e).filter(t=>t.endsWith(".json")).map(t=>Y(j(e,t))).filter(t=>t!==null):[]}function Of(e){let t=`${or(e)}.watch`,n=`${process.pid} ${Date.now()}`;return $e(j(q(),"sessions"),{recursive:!0,mode:448}),Kt(t,n),()=>{try{return ar(t,"utf8")===n}catch{return!1}}}function $f(e){try{return Sf(Tc("git",["-C",e,"rev-parse","--path-format=absolute","--git-common-dir"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim())}catch{try{return Sf(e)}catch{return Tv(e)}}}function Wv(e){let t=n=>Tc("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(`
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 Bv=(e,t)=>!!e&&!!t&&e!==t&&e.split(":")[0]===t.split(":")[0],Vt=()=>j(q(),"repos"),ir=e=>`${e.name.replace(/[^\w.-]/g,"_")}-${e.id.slice(0,8)}`;function Nf(){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 He(e){let t=$f(e);return Nf().find(n=>n.path===t)??null}function En(e,t={}){let n=$f(e),r=Nf(),s=r.find(a=>a.path===n);if(s&&!t.verify)return s;let o=Wv(e);if(s){if(!Bv(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:vv(8).toString("hex"),path:n,identity:o,name:Ic(n)===".git"?Ic(Rv(n)):Ic(n)})}function Xe(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 _f=e=>j(Vt(),e,"scripts"),zt="## How the app runs here",jf=`# Canary
682
1722
 
683
1723
  Canary's verifiers read this file before every check and add what they learn after each run.
684
1724
  It stays on this machine, in Canary's own folder: outside the repository, shared by its worktrees, and never uploaded.
@@ -698,43 +1738,43 @@ Name them here; keep the values in secrets.env beside this file.
698
1738
  ${zt}
699
1739
 
700
1740
  ## What worked and what failed
701
- `;function Uo(e){let t=Qe(Rn(e,{verify:!0}));return Oe(t.scripts,{recursive:!0,mode:448}),ge(t.canaryMd)||Yt(t.canaryMd,Nf,{flag:"wx"}),ge(t.secrets)||Yt(t.secrets,`# Test secrets Canary's verifiers may use, as NAME=value. Never uploaded.
702
- `,{flag:"wx",mode:384}),t}var lr="notes-before.json",Pf=e=>e.includes(zt)?e.slice(0,e.indexOf(zt)):e;function Mf(e){let t=Be(e),n=Nf;try{t&&(n=ar(Qe(t).canaryMd,"utf8"))}catch{}return{at:new Date().toISOString(),notes:Pf(n)}}function Lf(e,t){let n;try{n=ar(t,"utf8")}catch{return[]}let r=new Set(e.notes.split(`
1741
+ `;function Bo(e){let t=Xe(En(e,{verify:!0}));return $e(t.scripts,{recursive:!0,mode:448}),ge(t.canaryMd)||Kt(t.canaryMd,jf,{flag:"wx"}),ge(t.secrets)||Kt(t.secrets,`# Test secrets Canary's verifiers may use, as NAME=value. Never uploaded.
1742
+ `,{flag:"wx",mode:384}),t}var lr="notes-before.json",Pf=e=>e.includes(zt)?e.slice(0,e.indexOf(zt)):e;function Mf(e){let t=He(e),n=jf;try{t&&(n=ar(Xe(t).canaryMd,"utf8"))}catch{}return{at:new Date().toISOString(),notes:Pf(n)}}function Lf(e,t){let n;try{n=ar(t,"utf8")}catch{return[]}let r=new Set(e.notes.split(`
703
1743
  `).map(s=>s.trim()));return Pf(n).split(`
704
- `).map(s=>s.trim()).filter(s=>s&&!r.has(s))}function Zt(e){try{let t=Be(e),n=t&&/^\s*Verifiers at a time:\s*(\d+)\s*$/im.exec(ar(Qe(t).canaryMd,"utf8")),r=n?Number(n[1]):Lo;return r>=1&&r<=8?r:Lo}catch{return Lo}}var ce=e=>N(W(),"runs",st(e,"run"));function qo(e){ge(ce(e))&&Yt(N(ce(e),"heartbeat"),"")}var le=e=>N(W(),"batches",st(e,"batch"));function de(e){return N(W(),"workspaces",e.repoFolder,String(e.slot))}function Df(e){Oe(N(W(),"workspaces",e.repoFolder),{recursive:!0,mode:448}),Yt(N(W(),"workspaces",e.repoFolder,`${e.slot}.used`),"")}function qS(e){let t=N(W(),"workspaces");for(let n of ge(t)?ft(t):[]){let r=N(t,n),s=V(N(Kt(),n,"repo.json")),o=s!==null&&(s.path===""||!ge(s.path));for(let i of ft(r).filter(a=>/^\d+$/.test(a))){let a=N(r,i),c=ge(N(r,`${i}.used`))?N(r,`${i}.used`):a;e.has(a)||!(o||Do(c,OS))||(Ne(a,{recursive:!0,force:!0}),Ne(N(r,`${i}.used`),{force:!0}))}ft(r).some(i=>/^\d+$/.test(i))||Ne(r,{recursive:!0,force:!0})}}var ur=(e,t,n)=>n?N(le(e),"packs",st(t,"job"),`proof-${n}`):N(le(e),"packs",st(t,"job")),dr=e=>N(le(e),"scratch"),Qt=e=>N(le(e),"state.json");function Ff(e){Oe(N(W(),"batches"),{recursive:!0,mode:448}),Hf(e)&&Ne(le(e),{recursive:!0,force:!0});try{Oe(le(e),{mode:448})}catch(t){if(t.code==="EEXIST"){let n=V(Qt(e))?.left;throw n?new j("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 j("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=V(Qt(e));if(!t)throw new j("not_taken_here","This batch wasn't taken on this machine.",`Take it first: canary jobs take ${e}`);return Rf(Qt(e)),t}function fs(e){Pe(Qt(e.batchId),e)}function Q(){let e=N(W(),"batches");return ge(e)?ft(e).filter(t=>Af.test(t)).map(t=>V(Qt(t))).filter(t=>t!==null):[]}var ps=e=>Q().some(t=>t.setAside===!0&&t.checkout===e);function hr(e){st(e,"job");let t=Q().find(n=>n.jobs.some(r=>r.jobId===e));if(!t)throw new j("not_taken_here","No batch taken on this machine holds this job.","Use the job id take printed.");return Rf(Qt(t.batchId)),t}var Oc=e=>Fo("sha256").update(e).digest("hex").slice(0,16);function Tc(e,t,n){try{Oe(e,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r;if(!n(V(N(e,"owner.json"))))return!1;Ne(e,{recursive:!0,force:!0});try{Oe(e,{mode:448})}catch{return!1}}return Pe(N(e,"owner.json"),t),!0}var Bo=e=>!e?.batchId||Hf(e.batchId),BS=2*6e4;function Hf(e){return ge(le(e))?!ge(Qt(e))&&Do(le(e),BS):!0}function Uf(e,t){let n=N(W(),"slots");Oe(n,{recursive:!0,mode:448});for(let r=0;r<t;r++)if(Tc(N(n,String(r)),{batchId:e},s=>s?.batchId===e||Bo(s)))return r;return null}var qf=e=>V(N(W(),"slots",String(e),"owner.json"))?.batchId??null;function gs(e){let t=N(W(),"slots");for(let n=0;n<e;n++)if(!ge(N(t,String(n)))||Bo(V(N(t,String(n),"owner.json"))))return!0;return!1}var Bf=e=>N(W(),"waiting",`${st(e,"batch")}.json`);function ms(e,t,n){Oe(N(W(),"waiting"),{recursive:!0,mode:448}),Pe(Bf(e),{batchId:e,sessionId:t,checkout:n})}var tn=e=>Ne(Bf(e),{force:!0});function ys(e){let t=N(W(),"waiting");return ge(t)?ft(t).map(n=>V(N(t,n))).filter(n=>n!==null&&n.sessionId===e):[]}function Wo(e){for(let t of["slots","ports","locks"]){let n=N(W(),t);if(ge(n))for(let r of ft(n))V(N(n,r,"owner.json"))?.batchId===e&&Ne(N(n,r),{recursive:!0,force:!0})}for(let t of WS)for(let n of Nc(t,e))Ne(N(W(),t,n),{force:!0});Ne(Vo(e),{force:!0})}var WS=["verifiers","approval-waits"],Jo=e=>/^[A-Za-z0-9_-]{1,96}$/.test(e)?e:Fo("sha256").update(e).digest("hex").slice(0,32);function Wf(e,t,n){try{return ar(N(W(),e,t),"utf8").split(`
705
- `)[n]?.trim()||null}catch{return null}}var jc=(e,t)=>Wf(e,t,0);function Nc(e,t){let n=N(W(),e);return ge(n)?ft(n).filter(r=>jc(e,r)===t):[]}function Jf(e,t,n){Oe(N(W(),e),{recursive:!0,mode:448}),Yt(N(W(),e,t),n,{mode:384})}var Gf=(e,t)=>Jf("verifiers",Jo(e),t),it=e=>jc("verifiers",Jo(e)),Vf=e=>Nc("verifiers",e).length>0,Kf=(e,t,n,r="")=>Jf("approval-waits",`${Jo(e)}.${t}`,`${n}
706
- ${r}`);function Go(e){let t=N(W(),"approval-waits"),n=`${Jo(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 ws(e){for(let t of e)Ne(N(W(),"approval-waits",t),{force:!0})}var Vo=e=>N(W(),"approval-owed",st(e,"batch"));function Pc(e,t){Oe(N(W(),"approval-owed"),{recursive:!0,mode:448}),Pe(Vo(e),t)}var Mc=e=>V(Vo(e));function bs(e,t){(!t||Mc(e)?.call===t)&&Ne(Vo(e),{force:!0})}var Ot=e=>Nc("approval-waits",e),ks=e=>Wf("approval-waits",e,1),JS=e=>N(W(),"locks",Fo("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,24));function Yf(e,t,n){return Oe(N(W(),"locks"),{recursive:!0,mode:448}),Tc(JS(e),{batchId:t,jobId:n,target:e},r=>Bo(r)||r?.batchId===t)}function Lc(e,t){let n=N(W(),"locks");if(ge(n))for(let r of ft(n)){let s=V(N(n,r,"owner.json"));s?.batchId===e&&s.jobId===t&&Ne(N(n,r),{recursive:!0,force:!0})}}async function zf(e,t){let n=N(W(),"ports");Oe(n,{recursive:!0,mode:448});for(let r=0;r<Cf;r++){let s=jS+(t+r)%Cf*Ic;if(!Tc(N(n,String(s)),{batchId:e},i=>i?.batchId===e||Bo(i)))continue;let o=!0;for(let i=s;i<s+Ic&&o;i++)o=await GS(i);if(o)return[s,s+Ic-1];Ne(N(n,String(s)),{recursive:!0,force:!0})}throw new j("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 GS(e){return await $f(e,"127.0.0.1")&&await $f(e,"::1")}function $f(e,t){return new Promise((n,r)=>{let s=$S();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 j("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=Q();for(let s of t)sr(s.owner)||sr(ot(s.sessionId).owner)||!Do(Qt(s.batchId),RS)||await e(s).catch(()=>{});let n=Q();try{qS(new Set(n.map(de)))}catch{}let r=new Set(n.map(s=>s.runId));for(let s of FS())if(!sr(s.owner)){for(let o of ys(s.sessionId))tn(o.batchId);try{let o=!1;for(let i of Object.keys(s.runs)){let a=ce(i),c=ge(N(a,"heartbeat"))?N(a,"heartbeat"):a;r.has(i)||ge(a)&&!Do(c,ES)||(Ne(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`])Ne(i,{force:!0});else o&&Pe(or(s.sessionId),s)}catch{}}}Yr();De();Wt();Ro();Gt();var e0=ZS(VS),t0=1e5,n0=8*6e4,r0=3e4,s0=1440*6e4;function rp(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 o0=/^[ \t]*-{3,}[ \t]*from the user['’]s agent[ \t]*-{3,}[ \t\r]*$/i;function i0(e){let t=e.split(`
707
- `);for(let n=t.length-1;n>=0;n--)if(o0.test(t[n]))return{words:t.slice(0,n).join(`
1744
+ `).map(s=>s.trim()).filter(s=>s&&!r.has(s))}function Qt(e){try{let t=He(e),n=t&&/^\s*Verifiers at a time:\s*(\d+)\s*$/im.exec(ar(Xe(t).canaryMd,"utf8")),r=n?Number(n[1]):Lo;return r>=1&&r<=8?r:Lo}catch{return Lo}}var ce=e=>j(q(),"runs",st(e,"run"));function Uo(e){ge(ce(e))&&Kt(j(ce(e),"heartbeat"),"")}var le=e=>j(q(),"batches",st(e,"batch"));function de(e){return j(q(),"workspaces",e.repoFolder,String(e.slot))}function Ff(e){$e(j(q(),"workspaces",e.repoFolder),{recursive:!0,mode:448}),Kt(j(q(),"workspaces",e.repoFolder,`${e.slot}.used`),"")}function Uv(e){let t=j(q(),"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,$v))||(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",st(t,"job"),`proof-${n}`):j(le(e),"packs",st(t,"job")),dr=e=>j(le(e),"scratch"),Xt=e=>j(le(e),"state.json");function Df(e){$e(j(q(),"batches"),{recursive:!0,mode:448}),Wf(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 Ef(Xt(e)),t}function fs(e){Pe(Xt(e.batchId),e)}function X(){let e=j(q(),"batches");return ge(e)?ft(e).filter(t=>Tf.test(t)).map(t=>Y(Xt(t))).filter(t=>t!==null):[]}var ps=e=>X().some(t=>t.setAside===!0&&t.checkout===e);function hr(e){st(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 Ef(Xt(t.batchId)),t}var $c=e=>Do("sha256").update(e).digest("hex").slice(0,16);function Nc(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 Ho=e=>!e?.batchId||Wf(e.batchId),Hv=2*6e4;function Wf(e){return ge(le(e))?!ge(Xt(e))&&Fo(le(e),Hv):!0}function Bf(e,t){let n=j(q(),"slots");$e(n,{recursive:!0,mode:448});for(let r=0;r<t;r++)if(Nc(j(n,String(r)),{batchId:e},s=>s?.batchId===e||Ho(s)))return r;return null}var Uf=e=>Y(j(q(),"slots",String(e),"owner.json"))?.batchId??null;function gs(e){let t=j(q(),"slots");for(let n=0;n<e;n++)if(!ge(j(t,String(n)))||Ho(Y(j(t,String(n),"owner.json"))))return!0;return!1}var Hf=e=>j(q(),"waiting",`${st(e,"batch")}.json`);function ms(e,t,n){$e(j(q(),"waiting"),{recursive:!0,mode:448}),Pe(Hf(e),{batchId:e,sessionId:t,checkout:n})}var tn=e=>je(Hf(e),{force:!0});function ys(e){let t=j(q(),"waiting");return ge(t)?ft(t).map(n=>Y(j(t,n))).filter(n=>n!==null&&n.sessionId===e):[]}function qo(e){for(let t of["slots","ports","locks"]){let n=j(q(),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 qv)for(let n of jc(t,e))je(j(q(),t,n),{force:!0});je(Yo(e),{force:!0})}var qv=["verifiers","approval-waits"],Go=e=>/^[A-Za-z0-9_-]{1,96}$/.test(e)?e:Do("sha256").update(e).digest("hex").slice(0,32);function qf(e,t,n){try{return ar(j(q(),e,t),"utf8").split(`
1745
+ `)[n]?.trim()||null}catch{return null}}var _c=(e,t)=>qf(e,t,0);function jc(e,t){let n=j(q(),e);return ge(n)?ft(n).filter(r=>_c(e,r)===t):[]}function Gf(e,t,n){$e(j(q(),e),{recursive:!0,mode:448}),Kt(j(q(),e,t),n,{mode:384})}var Jf=(e,t)=>Gf("verifiers",Go(e),t),it=e=>_c("verifiers",Go(e)),Yf=e=>jc("verifiers",e).length>0,Vf=(e,t,n,r="")=>Gf("approval-waits",`${Go(e)}.${t}`,`${n}
1746
+ ${r}`);function Jo(e){let t=j(q(),"approval-waits"),n=`${Go(e)}.`;return ge(t)?ft(t).filter(r=>r.startsWith(n)).flatMap(r=>{let s=_c("approval-waits",r);return s?[{name:r,call:r.slice(n.length),batchId:s}]:[]}):[]}function ws(e){for(let t of e)je(j(q(),"approval-waits",t),{force:!0})}var Yo=e=>j(q(),"approval-owed",st(e,"batch"));function Pc(e,t){$e(j(q(),"approval-owed"),{recursive:!0,mode:448}),Pe(Yo(e),t)}var Mc=e=>Y(Yo(e));function bs(e,t){(!t||Mc(e)?.call===t)&&je(Yo(e),{force:!0})}var $t=e=>jc("approval-waits",e),ks=e=>qf("approval-waits",e,1),Gv=e=>j(q(),"locks",Do("sha256").update(e.trim().toLowerCase()).digest("hex").slice(0,24));function Kf(e,t,n){return $e(j(q(),"locks"),{recursive:!0,mode:448}),Nc(Gv(e),{batchId:t,jobId:n,target:e},r=>Ho(r)||r?.batchId===t)}function Lc(e,t){let n=j(q(),"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(q(),"ports");$e(n,{recursive:!0,mode:448});for(let r=0;r<Cf;r++){let s=_v+(t+r)%Cf*Rc;if(!Nc(j(n,String(s)),{batchId:e},i=>i?.batchId===e||Ho(i)))continue;let o=!0;for(let i=s;i<s+Rc&&o;i++)o=await Jv(i);if(o)return[s,s+Rc-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 Jv(e){return await If(e,"127.0.0.1")&&await If(e,"::1")}function If(e,t){return new Promise((n,r)=>{let s=Iv();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 Xf(e){let t=X();for(let s of t)sr(s.owner)||sr(ot(s.sessionId).owner)||!Fo(Xt(s.batchId),Ev)||await e(s).catch(()=>{});let n=X();try{Uv(new Set(n.map(de)))}catch{}let r=new Set(n.map(s=>s.runId));for(let s of Dv())if(!sr(s.owner)){for(let o of ys(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,Ov)||(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{}}}Kr();Fe();qt();Eo();Jt();var ex=Qv(Yv),tx=1e5,nx=8*6e4,rx=3e4,sx=1440*6e4;function rp(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 ox=/^[ \t]*-{3,}[ \t]*from the user['’]s agent[ \t]*-{3,}[ \t\r]*$/i;function ix(e){let t=e.split(`
1747
+ `);for(let n=t.length-1;n>=0;n--)if(ox.test(t[n]))return{words:t.slice(0,n).join(`
708
1748
  `),agentContext:t.slice(n+1).join(`
709
- `).trim()||null};return{words:e,agentContext:null}}function a0(e,t){return t?i0(e):{words:e,agentContext:null}}function c0(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(...sp(n)),o}function sp(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 l0(e,t){return[...e.split("\0").filter(Boolean).map(r=>({path:r,status:"added",added:null,removed:null})),...sp(t)]}async function nn(e,t,n={}){try{return(await e0("git",["-c","core.fsmonitor=false",...t],{cwd:e,env:{...no(),...n},timeout:r0,maxBuffer:64*1024*1024})).stdout}catch{return null}}async function u0(e){let t=(await nn(e,["rev-parse","--git-path","index"]))?.trim();if(!t||!ep(Xf(e,t)))return{env:{},dispose:()=>{}};let n=KS($e(XS(),"canary-index-"));return Zf(Xf(e,t),$e(n,"index")),{env:{GIT_INDEX_FILE:$e(n,"index")},dispose:()=>Dc(n,{recursive:!0,force:!0})}}async function d0(e,t){let n=await Yd(e).catch(()=>null),r=await u0(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?c0(a,c,i):l0(a,i)}}}var h0=500;async function f0(e,t){return t?(await nn(e,["log",`--max-count=${h0}`,"--format=%B%x00",`${t}..HEAD`])??"").split("\0").map(r=>r.trim()).filter(Boolean):[]}function p0(e){try{let t=$e(Y(),"requests");tp(t,{recursive:!0,mode:448}),Ko($e(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.
710
- `)}}var En=e=>$e(Y(),"requests",e);function g0(e,t,n,r){let s=En(e);tp(s,{recursive:!0,mode:448});let o=$e(Y(),"requests");for(let i of np(o,{withFileTypes:!0}))if(!(!i.isDirectory()||i.name===e))try{Date.now()-QS($e(o,i.name)).mtimeMs>s0&&Dc($e(o,i.name),{recursive:!0,force:!0})}catch{}try{zS(t.bundlePath,$e(s,"source.bundle"))}catch(i){if(i.code!=="EXDEV")throw i;Zf(t.bundlePath,$e(s,"source.bundle"))}Ko($e(s,"source.json"),JSON.stringify(t.manifest,null,2)+`
711
- `,{mode:384}),Ko($e(s,"request.json"),JSON.stringify({checkout:n,chat:r})+`
712
- `,{mode:384}),Ko($e(s,lr),JSON.stringify(Mf(n))+`
713
- `,{mode:384})}function Fc(e){let t=$e(Y(),"requests");for(let n of ep(t)?np(t,{withFileTypes:!0}):[]){if(!n.isDirectory())continue;let r=$e(t,n.name);try{JSON.parse(YS($e(r,"request.json"),"utf8")).chat===e&&Dc($e(r,"source.bundle"),{force:!0})}catch{}}}async function m0(){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 op(e,t){let{json:n}=t;tt({cwd:e,agent:n,mode:"request"});let r=ne();if(!r)return F(n,"not_logged_in","Not logged in","run `canary login` first",3);(await Promise.resolve().then(()=>(to(),sd))).installAgentSkill(),(await Promise.resolve().then(()=>(Aa(),td))).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,v0(n,i))},c);o=a(t0);try{let c=await w0(e,r,t,i);p0(c.answer.requestId);let l=S0(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?`
714
- `:""}Canary \xB7 more to come: canary wait ${l.requestId}`)),process.exitCode=l.exitCode}catch(c){if(s)return;s=!0,k0(n,c)}finally{clearTimeout(o)}}function y0(e,t){let n=yn();return{...n?{"x-canary-session":n}:{},...e?{"x-canary-verifier":"1","x-canary-verifiers":String(Zt(t))}:{}}}async function w0(e,t,n,r){let{words:s,agentContext:o}=n.words===null?a0(await m0(),n.json):{words:n.words,agentContext:null},i=new AbortController,a=_n(e,{signal:i.signal});a.catch(()=>{}),r.capturing=a;try{let c=await Sn(e,t),l=await vn({...c,token:t}),d={workspaceId:c.workspaceId,repositoryId:l.repositoryId,words:s,agentContext:o,...await d0(e,l.name)};r.creating=U("/api/v1/cli/requests",{method:"POST",token:t,body:d,headers:y0(n.verifier===!0,e)}).then(ss);let u=await r.creating;if(!u.needsCode)return{answer:u,codeMissing:!1};r.requestId=u.requestId,r.extend(n0);let h=n.verifier===!0?yn():null,p=await b0(e,u.requestId,a,{context:c,repositoryId:l.repositoryId,token:t,keepFor:h});return r.codeSent=!0,{answer:{...p.answer,say:rs([u.say,p.answer.say]),do:[...u.do,...p.answer.do]},codeMissing:p.codeMissing}}finally{i.abort(),a.then(c=>c.dispose(),()=>{})}}async function b0(e,t,n,r){let s=l=>U(`/api/v1/cli/requests/${t}/source`,{method:"POST",token:r.token,body:l}).then(ss).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 He?l.code:"capture_failed",u=l instanceof He&&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&&g0(t,o,e,r.keepFor);let c=await s({source:a,commitMessages:await f0(e,o.manifest.provenance.baseSha),...o.submodules.length?{submodules:[...o.submodules]}:{}});return ts(o.manifest,r.context,r.repositoryId,{requestKey:i,uploadId:a.uploadId}),{answer:c,codeMissing:!1}}function k0(e,t){if(t instanceof re)return F(e,t.code,t.message,void 0,3);if(t instanceof L)return t.status===413&&t.code==="commit_messages_too_large"?F(e,t.code,t.message,t.fix,3):t.status===413?F(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?F(e,"not_logged_in","Your Canary login is no longer valid.","run `canary login`",3):t.code==="source_upload_unavailable"?F(e,t.code,"Canary couldn't store your code just now.","run the same command again in a minute",2):F(e,t.code??"api_error",t.message,t.fix,be(t)||t.status>=500?2:3);let n=is(t);if(n)return F(e,"home_not_writable",n.message,n.fix,2);F(e,"internal_error",t instanceof Error?t.message:String(t),void 0,2)}async function v0(e,t){F(e,"timed_out","Canary didn't answer in time.","run the same command again",2);let n=[],r=s=>U(`/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 S0(e){let t=e.ending==="failed"?2:0;return{ok:!0,requestId:e.requestId,say:Jt(e.say),do:e.do,ended:e.ending!==null,exitCode:t}}Z();Wt();w();var Hc={session:"x-canary-session",batchKey:"x-canary-batch-key"},On=/^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}(\/[A-Za-z0-9_][A-Za-z0-9._-]{0,99}){0,7}$/;w();fe();Z();nt();import{randomUUID as x0}from"node:crypto";mn();function C0(){let e=K().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,_0=6e4;async function ap(e,t){let n=ne();if(!n)throw new j("not_logged_in","Not logged in to Canary.","Run canary login.");let r=ue().replace(/\/+$/,""),s={...C0(),authorization:`Bearer ${n}`,[Hc.session]:t.session};t.batchKey&&(s[Hc.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??_0),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 ip(r)}finally{clearTimeout(i)}if(c.ok)return c;let l=await c.json().catch(()=>null);throw typeof l?.error!="string"?ip(r):c.status>=500?new L(c.status,rn):c.status===401?new j("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 ip(e){let t=new URL(e).host,n=Cc()?_c()?`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 ${kf}.`:"Run it again in a minute.";return new L(0,"Couldn't reach Canary.",n)}async function oe(e,t){let n=await ap(e,t);return n.status===204?null:await n.json()}async function cp(e,t){return Buffer.from(await(await ap(e,t)).arrayBuffer())}var Tt=e=>be(e)||e instanceof L&&e.status>=500,$0=new Set(["batch_released","batch_ended","nothing_left","not_found"]),Yo=e=>e instanceof L&&!!e.code&&$0.has(e.code);async function We(e,t=0){let n=Date.now()+t;for(let r=1;;r++)try{return await e()}catch(s){if(!Tt(s)||r>=3&&Date.now()>=n)throw s;await new Promise(o=>setTimeout(o,Math.min(r*2e3,1e4)))}}function vs(e,t,n,r){let s=n instanceof Error?n.stack??n.message:String(n),o={reportId:x0(),...t.batchId?{batchId:t.batchId}:{},...t.jobId?{jobId:t.jobId}:{},cause:s.slice(0,8e3)};return We(()=>oe("/cli/jobs/internal-error",{session:e,batchKey:t.batchKey,json:o,timeoutMs:r}))}w();Z();import{execFile as B0,execFileSync as $s}from"node:child_process";import{readdirSync as Vp,readFileSync as W0,readlinkSync as Kp,realpathSync as Yp,rmSync as Jp}from"node:fs";import{basename as J0,join as Gp,sep as zp}from"node:path";import{promisify as G0}from"node:util";w();import{appendFileSync as M0,mkdirSync as Op,readFileSync as ei,rmSync as Ip,writeFileSync as L0}from"node:fs";import{createHash as Tp}from"node:crypto";import{basename as Ap,dirname as jp,join as ti}from"node:path";w();Z();import{execFileSync as I0}from"node:child_process";import{mkdirSync as A0,rmSync as R0}from"node:fs";import{basename as E0,join as dp}from"node:path";var hp="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."},fp={label:"Keep asking",description:"Claude Code asks you about each command, following your own settings."},Bc={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."},pp={label:"Don't use them",description:"The checks set up what they can themselves and ask you for any key they need."};function gp(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 Qo=e=>dp(Y(),"approvals",`${e}.json`);function mp(e,t){let n=Rn(e),r=V(Qo(n.id))??{repo:n.path};t(r),A0(dp(Y(),"approvals"),{recursive:!0,mode:448}),Pe(Qo(n.id),r)}function yp(e){let t=Be(e);return t&&V(Qo(t.id))}function Tn(e){let t=yp(e);return t?.commands?t:null}function wp(e,t){mp(e,n=>Object.assign(n,{commands:t.trim()===qc.label?"run":"ask",answer:t,at:new Date().toISOString()}))}var Xo=e=>yp(e)?.envFiles??null;function bp(e,t,n){mp(e,r=>{r.envFiles={use:n.trim()===Bc.label,files:t,answer:n,at:new Date().toISOString()}})}function kp(e){let t=Be(e);t&&R0(Qo(t.id),{force:!0})}var O0=/\.(example|sample|template|dist|defaults?)$/i;function T0(e){let t=[];try{t=I0("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(E0(n))&&!O0.test(n)).sort()}function vp(e){let t=T0(e),n=new Set(Xo(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===`
715
- `||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 j0=new Set(["cat","head","tail","ls","wc","stat","grep"]),N0=new Set(["head","tail","wc","grep","uniq"]);function Sp(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 xp(e,t){let n=e.replace(/\s2>\s?(?:\/dev\/null|&1)(?=\s|$)/g," ").split("|").map(Sp);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 j0.has(s[0])&&i.length>0&&i.every(t)&&o.every(a=>N0.has(a[0])&&r(a).length<=(a[0]==="grep"?1:0))}var P0=new Set(["echo","printf","sleep","true",":"]);function Cp(e){let t=e.split(/;|&&|\n/).map(n=>n.trim()).filter(Boolean).map(Sp);return t.length>0&&t.every(n=>n!==null&&n.length>0&&P0.has(n[0]))}var lp=(e,t)=>e.replace(/\s+/g," ").trim()===t.replace(/\s+/g," ").trim(),up=(e,...t)=>t.some(n=>n.label===e.trim());function _p(e,t){let n={commands:null,envFiles:null},r=!Tn(t),s=vp(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&&lp(a,hp)&&up(c,qc,fp)?n.commands??=c:s.length&&lp(a,gp(s))&&up(c,Bc,pp)&&(n.envFiles??={files:s,answer:c}))}return n}var zo=e=>`${JSON.stringify(e.label)} (${e.description})`;function Wc(e){let t=[];Tn(e)||t.push(`header "Approvals": ${JSON.stringify(hp)} Options, in this order: ${zo(qc)} and ${zo(fp)}`);let n=vp(e);return n.length&&t.push(`header "Env files": ${JSON.stringify(gp(n))} Options, in this order: ${zo(Bc)} and ${zo(pp)}`),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 $p(e){let t=[],n=Tn(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=Xo(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 Rp=500,D0=120,Np=256*1024,F0=3e4,H0=3e5,Ss=e=>ti(W(),"records",`${st(e,"batch")}.jsonl`),Vc=e=>ti(W(),"records",`${st(e,"batch")}.out`),Pp=(e,t)=>ti(Vc(e),/^[A-Za-z0-9_-]{1,96}$/.test(t)?t:Tp("sha256").update(t).digest("hex").slice(0,32)),Jc=e=>e.length>Rp?`${e.slice(0,Rp-1)}\u2026`:e;function Zo(e,t){if(e.length<=t)return e;let n=Math.floor(t/4);return`${e.slice(0,n)}
1749
+ `).trim()||null};return{words:e,agentContext:null}}function ax(e,t){return t?ix(e):{words:e,agentContext:null}}function cx(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(...sp(n)),o}function sp(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 lx(e,t){return[...e.split("\0").filter(Boolean).map(r=>({path:r,status:"added",added:null,removed:null})),...sp(t)]}async function nn(e,t,n={}){try{return(await ex("git",["-c","core.fsmonitor=false",...t],{cwd:e,env:{...no(),...n},timeout:rx,maxBuffer:64*1024*1024})).stdout}catch{return null}}async function ux(e){let t=(await nn(e,["rev-parse","--git-path","index"]))?.trim();if(!t||!ep(Zf(e,t)))return{env:{},dispose:()=>{}};let n=Vv(Ie(Zv(),"canary-index-"));return Qf(Zf(e,t),Ie(n,"index")),{env:{GIT_INDEX_FILE:Ie(n,"index")},dispose:()=>Fc(n,{recursive:!0,force:!0})}}async function dx(e,t){let n=await Kd(e).catch(()=>null),r=await ux(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?cx(a,c,i):lx(a,i)}}}var hx=500;async function fx(e,t){return t?(await nn(e,["log",`--max-count=${hx}`,"--format=%B%x00",`${t}..HEAD`])??"").split("\0").map(r=>r.trim()).filter(Boolean):[]}function px(e){try{let t=Ie(K(),"requests");tp(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.
1750
+ `)}}var On=e=>Ie(K(),"requests",e);function gx(e,t,n,r){let s=On(e);tp(s,{recursive:!0,mode:448});let o=Ie(K(),"requests");for(let i of np(o,{withFileTypes:!0}))if(!(!i.isDirectory()||i.name===e))try{Date.now()-Xv(Ie(o,i.name)).mtimeMs>sx&&Fc(Ie(o,i.name),{recursive:!0,force:!0})}catch{}try{zv(t.bundlePath,Ie(s,"source.bundle"))}catch(i){if(i.code!=="EXDEV")throw i;Qf(t.bundlePath,Ie(s,"source.bundle"))}Vo(Ie(s,"source.json"),JSON.stringify(t.manifest,null,2)+`
1751
+ `,{mode:384}),Vo(Ie(s,"request.json"),JSON.stringify({checkout:n,chat:r})+`
1752
+ `,{mode:384}),Vo(Ie(s,lr),JSON.stringify(Mf(n))+`
1753
+ `,{mode:384})}function Dc(e){let t=Ie(K(),"requests");for(let n of ep(t)?np(t,{withFileTypes:!0}):[]){if(!n.isDirectory())continue;let r=Ie(t,n.name);try{JSON.parse(Kv(Ie(r,"request.json"),"utf8")).chat===e&&Fc(Ie(r,"source.bundle"),{force:!0})}catch{}}}async function mx(){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 op(e,t){let{json:n}=t;tt({cwd:e,agent:n,mode:"request"});let r=ne();if(!r)return D(n,"not_logged_in","Not logged in","run `canary login` first",3);(await Promise.resolve().then(()=>(to(),sd))).installAgentSkill(),(await Promise.resolve().then(()=>(Ta(),td))).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,vx(n,i))},c);o=a(tx);try{let c=await wx(e,r,t,i);px(c.answer.requestId);let l=xx(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?`
1754
+ `:""}Canary \xB7 more to come: canary wait ${l.requestId}`)),process.exitCode=l.exitCode}catch(c){if(s)return;s=!0,kx(n,c)}finally{clearTimeout(o)}}function yx(e,t){let n=yn();return{...n?{"x-canary-session":n}:{},...e?{"x-canary-verifier":"1","x-canary-verifiers":String(Qt(t))}:{}}}async function wx(e,t,n,r){let{words:s,agentContext:o}=n.words===null?ax(await mx(),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 dx(e,l.name)};r.creating=B("/api/v1/cli/requests",{method:"POST",token:t,body:d,headers:yx(n.verifier===!0,e)}).then(ss);let u=await r.creating;if(!u.needsCode)return{answer:u,codeMissing:!1};r.requestId=u.requestId,r.extend(nx);let h=n.verifier===!0?yn():null,p=await bx(e,u.requestId,a,{context:c,repositoryId:l.repositoryId,token:t,keepFor:h});return r.codeSent=!0,{answer:{...p.answer,say:rs([u.say,p.answer.say]),do:[...u.do,...p.answer.do]},codeMissing:p.codeMissing}}finally{i.abort(),a.then(c=>c.dispose(),()=>{})}}async function bx(e,t,n,r){let s=l=>B(`/api/v1/cli/requests/${t}/source`,{method:"POST",token:r.token,body:l}).then(ss).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&&gx(t,o,e,r.keepFor);let c=await s({source:a,commitMessages:await fx(e,o.manifest.provenance.baseSha),...o.submodules.length?{submodules:[...o.submodules]}:{}});return ts(o.manifest,r.context,r.repositoryId,{requestKey:i,uploadId:a.uploadId}),{answer:c,codeMissing:!1}}function kx(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=is(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 vx(e,t){D(e,"timed_out","Canary didn't answer in time.","run the same command again",2);let n=[],r=s=>B(`/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 xx(e){let t=e.ending==="failed"?2:0;return{ok:!0,requestId:e.requestId,say:Gt(e.say),do:e.do,ended:e.ending!==null,exitCode:t}}Q();qt();w();var Wc={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();Q();nt();import{randomUUID as Sx}from"node:crypto";mn();function Cx(){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 Bc=45e3,Ax=6e4;async function ap(e,t){let n=ne();if(!n)throw new _("not_logged_in","Not logged in to Canary.","Run canary login.");let r=ue().replace(/\/+$/,""),s={...Cx(),authorization:`Bearer ${n}`,[Wc.session]:t.session};t.batchKey&&(s[Wc.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??Ax),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 ip(r)}finally{clearTimeout(i)}if(c.ok)return c;let l=await c.json().catch(()=>null);throw typeof l?.error!="string"?ip(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 ip(e){let t=new URL(e).host,n=Cc()?Ac()?`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 ${kf}.`:"Run it again in a minute.";return new L(0,"Couldn't reach Canary.",n)}async function oe(e,t){let n=await ap(e,t);return n.status===204?null:await n.json()}async function cp(e,t){return Buffer.from(await(await ap(e,t)).arrayBuffer())}var Nt=e=>be(e)||e instanceof L&&e.status>=500,Ix=new Set(["batch_released","batch_ended","nothing_left","not_found"]),Ko=e=>e instanceof L&&!!e.code&&Ix.has(e.code);async function qe(e,t=0){let n=Date.now()+t;for(let r=1;;r++)try{return await e()}catch(s){if(!Nt(s)||r>=3&&Date.now()>=n)throw s;await new Promise(o=>setTimeout(o,Math.min(r*2e3,1e4)))}}function vs(e,t,n,r){let s=n instanceof Error?n.stack??n.message:String(n),o={reportId:Sx(),...t.batchId?{batchId:t.batchId}:{},...t.jobId?{jobId:t.jobId}:{},cause:s.slice(0,8e3)};return qe(()=>oe("/cli/jobs/internal-error",{session:e,batchKey:t.batchKey,json:o,timeoutMs:r}))}w();Q();import{execFile as Hx,execFileSync as Is}from"node:child_process";import{readdirSync as Yp,readFileSync as qx,readlinkSync as Vp,realpathSync as Kp,rmSync as Gp}from"node:fs";import{basename as Gx,join as Jp,sep as zp}from"node:path";import{promisify as Jx}from"node:util";w();import{appendFileSync as Mx,mkdirSync as $p,readFileSync as ei,rmSync as Rp,writeFileSync as Lx}from"node:fs";import{createHash as Np}from"node:crypto";import{basename as Tp,dirname as _p,join as ti}from"node:path";w();Q();import{execFileSync as Rx}from"node:child_process";import{mkdirSync as Tx,rmSync as Ex}from"node:fs";import{basename as Ox,join as dp}from"node:path";var hp="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?",Uc={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."},fp={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."},pp={label:"Don't use them",description:"The checks set up what they can themselves and ask you for any key they need."};function gp(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=>dp(K(),"approvals",`${e}.json`);function mp(e,t){let n=En(e),r=Y(Xo(n.id))??{repo:n.path};t(r),Tx(dp(K(),"approvals"),{recursive:!0,mode:448}),Pe(Xo(n.id),r)}function yp(e){let t=He(e);return t&&Y(Xo(t.id))}function Nn(e){let t=yp(e);return t?.commands?t:null}function wp(e,t){mp(e,n=>Object.assign(n,{commands:t.trim()===Uc.label?"run":"ask",answer:t,at:new Date().toISOString()}))}var Zo=e=>yp(e)?.envFiles??null;function bp(e,t,n){mp(e,r=>{r.envFiles={use:n.trim()===Hc.label,files:t,answer:n,at:new Date().toISOString()}})}function kp(e){let t=He(e);t&&Ex(Xo(t.id),{force:!0})}var $x=/\.(example|sample|template|dist|defaults?)$/i;function Nx(e){let t=[];try{t=Rx("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(Ox(n))&&!$x.test(n)).sort()}function vp(e){let t=Nx(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===`
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 _x=new Set(["cat","head","tail","ls","wc","stat","grep"]),jx=new Set(["head","tail","wc","grep","uniq"]);function xp(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 Sp(e,t){let n=e.replace(/\s2>\s?(?:\/dev\/null|&1)(?=\s|$)/g," ").split("|").map(xp);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 _x.has(s[0])&&i.length>0&&i.every(t)&&o.every(a=>jx.has(a[0])&&r(a).length<=(a[0]==="grep"?1:0))}var Px=new Set(["echo","printf","sleep","true",":"]);function Cp(e){let t=e.split(/;|&&|\n/).map(n=>n.trim()).filter(Boolean).map(xp);return t.length>0&&t.every(n=>n!==null&&n.length>0&&Px.has(n[0]))}var lp=(e,t)=>e.replace(/\s+/g," ").trim()===t.replace(/\s+/g," ").trim(),up=(e,...t)=>t.some(n=>n.label===e.trim());function Ap(e,t){let n={commands:null,envFiles:null},r=!Nn(t),s=vp(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&&lp(a,hp)&&up(c,Uc,fp)?n.commands??=c:s.length&&lp(a,gp(s))&&up(c,Hc,pp)&&(n.envFiles??={files:s,answer:c}))}return n}var zo=e=>`${JSON.stringify(e.label)} (${e.description})`;function qc(e){let t=[];Nn(e)||t.push(`header "Approvals": ${JSON.stringify(hp)} Options, in this order: ${zo(Uc)} and ${zo(fp)}`);let n=vp(e);return n.length&&t.push(`header "Env files": ${JSON.stringify(gp(n))} Options, in this order: ${zo(Hc)} and ${zo(pp)}`),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 Ip(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 Ep=500,Fx=120,jp=256*1024,Dx=3e4,Wx=3e5,xs=e=>ti(q(),"records",`${st(e,"batch")}.jsonl`),Yc=e=>ti(q(),"records",`${st(e,"batch")}.out`),Pp=(e,t)=>ti(Yc(e),/^[A-Za-z0-9_-]{1,96}$/.test(t)?t:Np("sha256").update(t).digest("hex").slice(0,32)),Gc=e=>e.length>Ep?`${e.slice(0,Ep-1)}\u2026`:e;function Qo(e,t){if(e.length<=t)return e;let n=Math.floor(t/4);return`${e.slice(0,n)}
716
1756
  [... ${e.length-t} characters of this output not shown ...]
717
- ${e.slice(e.length-(t-n))}`}function xs(e,t){Op(jp(Ss(e)),{recursive:!0,mode:448}),M0(Ss(e),JSON.stringify(t)+`
718
- `,{mode:384})}var Cs=()=>new Date().toISOString(),Kc=e=>e.split(`
1757
+ ${e.slice(e.length-(t-n))}`}function Ss(e,t){$p(_p(xs(e)),{recursive:!0,mode:448}),Mx(xs(e),JSON.stringify(t)+`
1758
+ `,{mode:384})}var Cs=()=>new Date().toISOString(),Vc=e=>e.split(`
719
1759
  `).map(t=>t.trim()).find(t=>t&&!/^(source|\.|cd|set|export)\b/.test(t))??e.split(`
720
- `)[0],Gc=e=>e.say||(e.kind==="file"?`wrote ${Ap(jp(e.what))}/${Ap(e.what)}`:Kc(e.what));function Mp(e,t){let n;try{n=ei(Ss(e),"utf8")}catch{return[]}let r=[],s=new Map;for(let a of n.trimEnd().split(`
721
- `))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:Gc(a),command:a.kind==="command"?Kc(a.what):null,ended:a.bg?"background":s.get(a.call)??s.get(a.same)??"running"}))}var U0=500,ni=3e4;function ri(e,t){let n=r=>r.slice(0,U0);return Q().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}=q0(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 q0(e,t){let n=jn(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)||Cp(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?Gc(u):null,now:d?Gc(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 Lp=e=>jn(e).flatMap(t=>t.e==="asked"&&t.kind==="command"?[t.what]:[]),si=(e,t,n,r,s="",o=!1)=>xs(e,{at:Cs(),e:"asked",...t,kind:n,what:n==="command"?Zo(r,Np):Jc(r),...s?{say:Jc(s)}:{},...o?{bg:!0}:{}}),pr=(e,t,n,r="")=>xs(e,{at:Cs(),e:"ended",call:t.call??null,same:t.same??null,ended:n,detail:Jc(r.split(`
722
- `)[0]??"")}),Yc=(e,t,n,r)=>xs(e,{at:Cs(),e:t,jobId:n,proof:r}),Dp=(e,t,n)=>xs(e,{at:Cs(),e:"output",call:t,path:n}),zc=e=>Tp("sha256").update(e).digest("hex");function Fp(e,t,n){try{let r=ei(n);xs(e,{at:Cs(),e:"wrote",sha:zc(r)}),Qc(e,t,r.toString("utf8"))}catch{}}function Qc(e,t,n){n&&(Op(Vc(e),{recursive:!0,mode:448}),L0(Pp(e,t),Zo(n,Np),{mode:384}))}function Hp(e){Ip(Ss(e),{force:!0}),Ip(Vc(e),{recursive:!0,force:!0})}function Up(e){let t=new Set;for(let n of jn(e))n.e==="asked"?t.add(n.call):n.e==="ended"&&n.call&&t.delete(n.call);return t}var gr=e=>jn(e).some(t=>t.e==="start"),qp=e=>jn(e).find(t=>t.e==="start")?.at??null;function jn(e){try{return ei(Ss(e),"utf8").split(`
723
- `).filter(Boolean).flatMap(t=>{try{return[JSON.parse(t)]}catch{return[]}})}catch{return[]}}var Ep=e=>{try{return ei(e,"utf8")}catch{return""}};function Bp(e,t,n){let r=jn(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(-D0),l=Math.max(2e3,Math.min(F0,Math.floor(H0/Math.max(1,c.length))));c.forEach((u,h)=>{u.entry.id=`${n?`p${n}`:""}c${h+1}`,u.entry.what=Zo(u.entry.what,l),u.entry.ended!=="sent_back"&&(u.entry.output=Zo(Ep(Pp(e,u.call))||(u.elsewhere?Ep(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 Wp(e){let t=new Map,n=new Map,r=new Set;for(let s of jn(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 V0=G0(B0),mr=e=>`canary.batch=${e}`,yr=e=>`canary-${e}`;function Qp(e,t,n){try{let s=JSON.parse($s("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 _s(e,t){try{return $s("ps",["-o",`${e}=`,"-p",String(t)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function K0(e){try{return Kp(`/proc/${e}/cwd`)}catch{try{return $s("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).split(`
724
- `).find(n=>n.startsWith("n"))?.slice(1)??null}catch{return null}}}function Zc(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[Yp(r)]}catch{return[]}});for(let r=e,s=0;r>1&&s<64;s++){let o=K0(r);if(o!==null&&n.some(i=>o===i||o.startsWith(i+zp)))return!0;r=Number(_s("ppid",r)??0)}return!1}function Y0(e){return Number(_s("pgid",e))===e}async function z0(e,t){if(e.pid<=1)return!1;let n=Xt(e);return n!=="alive"?n==="gone":Zc(e.pid,t)?Xp(e):!1}async function Xp(e){let t=Y0(e.pid)?-e.pid:e.pid,n=r=>{try{process.kill(t,r)}catch{}};n("SIGTERM");for(let r=0;r<50&&Xt(e)==="alive";r++)await new Promise(s=>setTimeout(s,100));return Xt(e)==="alive"&&n("SIGKILL"),await new Promise(r=>setTimeout(r,200)),Xt(e)==="gone"}function Q0(){let e=new Map;try{for(let r of Vp("/proc").filter(s=>/^\d+$/.test(s)))try{e.set(Number(r),Kp(`/proc/${r}/cwd`))}catch{}if(e.size)return e}catch{}let t="";try{t=$s("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(`
725
- `))r.startsWith("p")?n=Number(r.slice(1)):r.startsWith("n")&&n&&e.set(n,r.slice(1));return e}function X0(e,t){let n;try{n=W0(`/proc/${e}/environ`,"utf8").replace(/\0/g," ")}catch{try{n=$s("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 Z0(e){let t=new Set;for(let n=e,r=0;n>1&&r<64;r++)t.add(n),n=Number(_s("ppid",n)??0);return t}async function ex(e){let n=[le(e.batchId),...qf(e.slot)===e.batchId?[de(e)]:[]].flatMap(i=>{try{return[Yp(i)]}catch{return[]}}),r=Z0(process.pid),s=[],o=[];for(let i=0;i<3&&n.length;i++){s=[],o=[];let a=0;for(let[c,l]of Q0()){if(c<=1||r.has(c)||!n.some(f=>l===f||l.startsWith(f+zp)))continue;let d=It(c);if(d===null)continue;let u=J0(_s("comm",c)??"a process"),h=X0(c,e.sessionId),p=_s("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 Xp({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 Xc(e,t){let{stdout:n}=await V0("docker",e,{timeout:t});return n.trim()}async function tx(e,t){let n=[],r=[`label=${mr(e)}`,`label=com.docker.compose.project=${yr(e)}`];try{await Xc(["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 Xc([...o,"--filter",a],t)).split(`
726
- `).filter(Boolean))];c.length&&await Xc([...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(`
727
- `)[0]:String(c)}`)}return n}async function Nn(e,t={}){let n=[],r=[];for(let a of e.processes)await z0(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 ex(e);n.push(...s.left);let o=e.left===void 0||e.dockerLeft===!0?await tx(e.batchId,t.dockerTimeoutMs??6e4):[];n.push(...o),Wo(e.batchId);let i=le(e.batchId);for(let a of nx(i).filter(c=>c!=="state.json"))try{Jp(Gp(i,a),{recursive:!0,force:!0})}catch(c){n.push(`${Gp(i,a)}: ${c instanceof Error?c.message.split(`
728
- `)[0]:String(c)}; it may hold files a container created as another user`)}return n.length?(fs({...e,processes:r,left:n,dockerLeft:o.length>0}),[...n,...s.others]):(Jp(i,{recursive:!0,force:!0}),Hp(e.batchId),s.others)}function nx(e){try{return Vp(e)}catch{return[]}}async function Zp(e){let t=[];for(let n of Q().filter(r=>r.left)){let r=e?await Nn(n,{dockerTimeoutMs:5e3}).catch(()=>n.left):n.left;t.push(...r.map(s=>`batch ${n.batchId}: ${s}`))}return t}w();import{execFile as rx}from"node:child_process";import{createHash as sx}from"node:crypto";import{appendFileSync as sg,copyFileSync as ox,createReadStream as ix,existsSync as tl,lstatSync as og,mkdirSync as nl,mkdtempSync as ax,readFileSync as cx,rmSync as el,statSync as eg,writeFileSync as ig}from"node:fs";import{tmpdir as lx}from"node:os";import{basename as ux,dirname as ag,isAbsolute as cg,join as Ue,relative as dx}from"node:path";import{promisify as hx}from"node:util";var rl=hx(rx),tg=1024*1024,ng=1024*1024,fx=".canary-cache",Is="refs/canary/head",lg=["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 ug(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 rl("git",[...lg.flatMap(s=>["-c",s]),"-C",e,...t],{env:ug(n),maxBuffer:67108864});return r}async function px(e){let t=sx("sha256"),n=0;for await(let r of ix(e))t.update(r),n+=r.length;return{hash:t.digest("hex"),bytes:n}}async function gx(e,t){let n=async o=>{try{return(await rl("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&&tl(r)&&ox(r,Ue(t,".git","info","exclude"));let s=await n(["config","--path","--get","core.excludesFile"]);s&&await me(t,["config","--local","core.excludesFile",s])}async function mx(e,t,n,r,s){await fg(t,n,r),await rl("git",["init","--quiet","--template=",s],{env:ug()}),await pg(e,t,n,s),await me(s,["checkout","--quiet","-B","canary-copy",n.headSha]),await gg(s,r)}async function dg(e,t,n,r,s){if(await fg(t,n,r),tl(Ue(s,".git")))try{await pg(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("/")&&ux(a).startsWith(".env")))el(Ue(s,i),{force:!0});return await gg(s,r),!0}catch{}return el(s,{recursive:!0,force:!0}),nl(ag(s),{recursive:!0,mode:448}),await mx(e,t,n,r,s),!1}var sl="canary-unset.invalid",rg=/(?<![\w.-])(?:(?:[\w-]+\.)*localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\]|host\.docker\.internal)(?![\w.-])|(?<![\w:.])::1(?![\w:.])/gi;function hg(e,t,n){let r=[];for(let s of n)if(!(cg(s)||s.split("/").includes("..")))try{let o=Ue(e,s);if(!eg(o).isFile())continue;if(tl(Ue(t,s))){r.push({file:s,repointed:[]});continue}let i=[],a=cx(o,"utf8").split(`
1760
+ `)[0],Jc=e=>e.say||(e.kind==="file"?`wrote ${Tp(_p(e.what))}/${Tp(e.what)}`:Vc(e.what));function Mp(e,t){let n;try{n=ei(xs(e),"utf8")}catch{return[]}let r=[],s=new Map;for(let a of n.trimEnd().split(`
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:Jc(a),command:a.kind==="command"?Vc(a.what):null,ended:a.bg?"background":s.get(a.call)??s.get(a.same)??"running"}))}var Bx=500,ni=3e4;function ri(e,t){let n=r=>r.slice(0,Bx);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}=Ux(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 Ux(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)||Cp(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?Jc(u):null,now:d?Jc(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("."),Vc(h.what)))}}var Lp=e=>_n(e).flatMap(t=>t.e==="asked"&&t.kind==="command"?[t.what]:[]),si=(e,t,n,r,s="",o=!1)=>Ss(e,{at:Cs(),e:"asked",...t,kind:n,what:n==="command"?Qo(r,jp):Gc(r),...s?{say:Gc(s)}:{},...o?{bg:!0}:{}}),pr=(e,t,n,r="")=>Ss(e,{at:Cs(),e:"ended",call:t.call??null,same:t.same??null,ended:n,detail:Gc(r.split(`
1762
+ `)[0]??"")}),Kc=(e,t,n,r)=>Ss(e,{at:Cs(),e:t,jobId:n,proof:r}),Fp=(e,t,n)=>Ss(e,{at:Cs(),e:"output",call:t,path:n}),zc=e=>Np("sha256").update(e).digest("hex");function Dp(e,t,n){try{let r=ei(n);Ss(e,{at:Cs(),e:"wrote",sha:zc(r)}),Xc(e,t,r.toString("utf8"))}catch{}}function Xc(e,t,n){n&&($p(Yc(e),{recursive:!0,mode:448}),Lx(Pp(e,t),Qo(n,jp),{mode:384}))}function Wp(e){Rp(xs(e),{force:!0}),Rp(Yc(e),{recursive:!0,force:!0})}function Bp(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"),Up=e=>_n(e).find(t=>t.e==="start")?.at??null;function _n(e){try{return ei(xs(e),"utf8").split(`
1763
+ `).filter(Boolean).flatMap(t=>{try{return[JSON.parse(t)]}catch{return[]}})}catch{return[]}}var Op=e=>{try{return ei(e,"utf8")}catch{return""}};function Hp(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(-Fx),l=Math.max(2e3,Math.min(Dx,Math.floor(Wx/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(Op(Pp(e,u.call))||(u.elsewhere?Op(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 qp(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 Yx=Jx(Hx),mr=e=>`canary.batch=${e}`,yr=e=>`canary-${e}`;function Xp(e,t,n){try{let s=JSON.parse(Is("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 As(e,t){try{return Is("ps",["-o",`${e}=`,"-p",String(t)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Vx(e){try{return Vp(`/proc/${e}/cwd`)}catch{try{return Is("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).split(`
1764
+ `).find(n=>n.startsWith("n"))?.slice(1)??null}catch{return null}}}function Qc(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[Kp(r)]}catch{return[]}});for(let r=e,s=0;r>1&&s<64;s++){let o=Vx(r);if(o!==null&&n.some(i=>o===i||o.startsWith(i+zp)))return!0;r=Number(As("ppid",r)??0)}return!1}function Kx(e){return Number(As("pgid",e))===e}async function zx(e,t){if(e.pid<=1)return!1;let n=Zt(e);return n!=="alive"?n==="gone":Qc(e.pid,t)?Zp(e):!1}async function Zp(e){let t=Kx(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 Xx(){let e=new Map;try{for(let r of Yp("/proc").filter(s=>/^\d+$/.test(s)))try{e.set(Number(r),Vp(`/proc/${r}/cwd`))}catch{}if(e.size)return e}catch{}let t="";try{t=Is("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(`
1765
+ `))r.startsWith("p")?n=Number(r.slice(1)):r.startsWith("n")&&n&&e.set(n,r.slice(1));return e}function Zx(e,t){let n;try{n=qx(`/proc/${e}/environ`,"utf8").replace(/\0/g," ")}catch{try{n=Is("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 Qx(e){let t=new Set;for(let n=e,r=0;n>1&&r<64;r++)t.add(n),n=Number(As("ppid",n)??0);return t}async function eS(e){let n=[le(e.batchId),...Uf(e.slot)===e.batchId?[de(e)]:[]].flatMap(i=>{try{return[Kp(i)]}catch{return[]}}),r=Qx(process.pid),s=[],o=[];for(let i=0;i<3&&n.length;i++){s=[],o=[];let a=0;for(let[c,l]of Xx()){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=Gx(As("comm",c)??"a process"),h=Zx(c,e.sessionId),p=As("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 Zp({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 Zc(e,t){let{stdout:n}=await Yx("docker",e,{timeout:t});return n.trim()}async function tS(e,t){let n=[],r=[`label=${mr(e)}`,`label=com.docker.compose.project=${yr(e)}`];try{await Zc(["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 Zc([...o,"--filter",a],t)).split(`
1766
+ `).filter(Boolean))];c.length&&await Zc([...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(`
1767
+ `)[0]:String(c)}`)}return n}async function jn(e,t={}){let n=[],r=[];for(let a of e.processes)await zx(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 eS(e);n.push(...s.left);let o=e.left===void 0||e.dockerLeft===!0?await tS(e.batchId,t.dockerTimeoutMs??6e4):[];n.push(...o),qo(e.batchId);let i=le(e.batchId);for(let a of nS(i).filter(c=>c!=="state.json"))try{Gp(Jp(i,a),{recursive:!0,force:!0})}catch(c){n.push(`${Jp(i,a)}: ${c instanceof Error?c.message.split(`
1768
+ `)[0]:String(c)}; it may hold files a container created as another user`)}return n.length?(fs({...e,processes:r,left:n,dockerLeft:o.length>0}),[...n,...s.others]):(Gp(i,{recursive:!0,force:!0}),Wp(e.batchId),s.others)}function nS(e){try{return Yp(e)}catch{return[]}}async function Qp(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 rS}from"node:child_process";import{createHash as sS}from"node:crypto";import{appendFileSync as sg,copyFileSync as oS,createReadStream as iS,existsSync as tl,lstatSync as og,mkdirSync as nl,mkdtempSync as aS,readFileSync as cS,rmSync as el,statSync as eg,writeFileSync as ig}from"node:fs";import{tmpdir as lS}from"node:os";import{basename as uS,dirname as ag,isAbsolute as cg,join as Be,relative as dS}from"node:path";import{promisify as hS}from"node:util";var rl=hS(rS),tg=1024*1024,ng=1024*1024,fS=".canary-cache",Rs="refs/canary/head",lg=["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 ug(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 rl("git",[...lg.flatMap(s=>["-c",s]),"-C",e,...t],{env:ug(n),maxBuffer:67108864});return r}async function pS(e){let t=sS("sha256"),n=0;for await(let r of iS(e))t.update(r),n+=r.length;return{hash:t.digest("hex"),bytes:n}}async function gS(e,t){let n=async o=>{try{return(await rl("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&&tl(r)&&oS(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 mS(e,t,n,r,s){await fg(t,n,r),await rl("git",["init","--quiet","--template=",s],{env:ug()}),await pg(e,t,n,s),await me(s,["checkout","--quiet","-B","canary-copy",n.headSha]),await gg(s,r)}async function dg(e,t,n,r,s){if(await fg(t,n,r),tl(Be(s,".git")))try{await pg(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("/")&&uS(a).startsWith(".env")))el(Be(s,i),{force:!0});return await gg(s,r),!0}catch{}return el(s,{recursive:!0,force:!0}),nl(ag(s),{recursive:!0,mode:448}),await mS(e,t,n,r,s),!1}var sl="canary-unset.invalid",rg=/(?<![\w.-])(?:(?:[\w-]+\.)*localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\]|host\.docker\.internal)(?![\w.-])|(?<![\w:.])::1(?![\w:.])/gi;function hg(e,t,n){let r=[];for(let s of n)if(!(cg(s)||s.split("/").includes("..")))try{let o=Be(e,s);if(!eg(o).isFile())continue;if(tl(Be(t,s))){r.push({file:s,repointed:[]});continue}let i=[],a=cS(o,"utf8").split(`
729
1769
  `).map(c=>{let l=/^(\s*(?:export\s+)?([A-Za-z_][\w.-]*)\s*=)(.*)$/.exec(c);return!l||!l[3].match(rg)?c:(i.push(l[2]),l[1]+l[3].replace(rg,sl))}).join(`
730
- `);nl(ag(Ue(t,s)),{recursive:!0}),sg(Ue(t,".git","info","exclude"),`/${s}
731
- `),ig(Ue(t,s),a,{mode:eg(o).mode&511}),r.push({file:s,repointed:i})}catch{}return r}async function fg(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 px(e);if(r!==t.sha256||s!==t.bytes)throw new Error("the kept snapshot doesn't match its receipt")}async function pg(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",Is,n.headSha]),nl(Ue(r,".git","info"),{recursive:!0}),ig(Ue(r,".git","info","attributes"),`* -text -eol -ident -filter -working-tree-encoding
732
- `);for(let s of lg){let o=s.indexOf("=");await me(r,["config","--local",s.slice(0,o),s.slice(o+1)])}await gx(e,r),sg(Ue(r,".git","info","exclude"),`
733
- /${fx}/
734
- `)}async function gg(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 mg(e,t){let n=[];for(let r of new Set(t)){let s=dx(e,r);if(!(!s||s.startsWith("..")||cg(s)))try{await me(e,["cat-file","-e",`${Is}:${s}`]),await me(e,["diff","--quiet",Is,"--",s]),n.push(s)}catch{}}return n}async function yg(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 og(Ue(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 wg(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 bg(e){let t=ax(Ue(lx(),"canary-diff-"));try{let n={GIT_INDEX_FILE:Ue(t,"index")};await me(e,["read-tree",Is],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=og(Ue(e,l));return d.isFile()&&d.size>ng&&s.push(`[new file ${l}, ${d.size} bytes, not included]`),!(d.isFile()&&d.size>ng)});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}`,Is],n),a=await i("a")+await i("A");return Buffer.byteLength(a)>tg&&(a=`${Buffer.from(a).subarray(0,tg).toString("utf8")}
1770
+ `);nl(ag(Be(t,s)),{recursive:!0}),sg(Be(t,".git","info","exclude"),`/${s}
1771
+ `),ig(Be(t,s),a,{mode:eg(o).mode&511}),r.push({file:s,repointed:i})}catch{}return r}async function fg(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 pS(e);if(r!==t.sha256||s!==t.bytes)throw new Error("the kept snapshot doesn't match its receipt")}async function pg(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",Rs,n.headSha]),nl(Be(r,".git","info"),{recursive:!0}),ig(Be(r,".git","info","attributes"),`* -text -eol -ident -filter -working-tree-encoding
1772
+ `);for(let s of lg){let o=s.indexOf("=");await me(r,["config","--local",s.slice(0,o),s.slice(o+1)])}await gS(e,r),sg(Be(r,".git","info","exclude"),`
1773
+ /${fS}/
1774
+ `)}async function gg(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 mg(e,t){let n=[];for(let r of new Set(t)){let s=dS(e,r);if(!(!s||s.startsWith("..")||cg(s)))try{await me(e,["cat-file","-e",`${Rs}:${s}`]),await me(e,["diff","--quiet",Rs,"--",s]),n.push(s)}catch{}}return n}async function yg(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 og(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 wg(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 bg(e){let t=aS(Be(lS(),"canary-diff-"));try{let n={GIT_INDEX_FILE:Be(t,"index")};await me(e,["read-tree",Rs],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=og(Be(e,l));return d.isFile()&&d.size>ng&&s.push(`[new file ${l}, ${d.size} bytes, not included]`),!(d.isFile()&&d.size>ng)});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}`,Rs],n),a=await i("a")+await i("A");return Buffer.byteLength(a)>tg&&(a=`${Buffer.from(a).subarray(0,tg).toString("utf8")}
735
1775
  [diff cut at 1 MB]
736
1776
  `),[a,...s].filter(Boolean).join(`
737
- `)||null}finally{el(t,{recursive:!0,force:!0})}}w();import{createHash as Ox}from"node:crypto";import{existsSync as Tx,lstatSync as jx,readFileSync as il,realpathSync as cl,statSync as Nx}from"node:fs";import{extname as _g,join as jt,sep as Px}from"node:path";w();import{execFileSync as yx}from"node:child_process";import{readFileSync as kg}from"node:fs";import{basename as wx,join as bx}from"node:path";var kx=/(^|[_.-])(KEY|SECRET|TOKEN|PASS|PASSWORD|PASSWD|PWD|CREDENTIALS?|SALT|DSN)($|[_.-])/i,vx=8,xg=/^[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 Sx(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>=vx&&!t.has(o)&&t.set(o,s)};try{let s=Be(e);if(s)for(let[o,i]of vg(kg(Qe(s).secrets,"utf8")))n(o,i)}catch{}let r=[];try{r=yx("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("/")&&wx(o).startsWith(".env"))){let o;try{o=kg(bx(e,s),"utf8")}catch{continue}for(let[i,a]of vg(o)){let c=Sx(a);for(let l of[kx.test(i)?a:null,c])l&&!xg.test(l)&&n(i,l)}}return[...t].map(([s,o])=>({name:o,value:s}))}var xx=[/\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],Cx=/\b(?:cnry_|gh[pousr]_|github_pat_|glpat-|npm_|whsec_|xox[abprs]-|sk-(?:ant-)?|[sr]k_(?:live|test)_)[\w+/=-]{16,}/g,_x=/(["']?)\b([A-Za-z_][\w.-]*)\1(\s*(?::|=(?!=))\s*["']?)([^\s"',;&}<>]{8,})/g,$x=/(secret|token|passw(or)?d|credentials?|(api|private|access|secret|signing|encryption)[_.-]?key)$/i,Sg=e=>/^[A-Za-z_]\w*(?:\??\.[A-Za-z_]\w*)*$/.test(e)&&/(secret|token|key|pass(w(or)?d)?|pwd?|credentials?)$/i.test(e),Ix=/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|token)\s+)?)([\w.~+/=-]{8,})/gi,Ax=/(\b(?:set-)?cookie["']?\s*[:=]\s*["']?)([^\r\n"']+)/gi,Rx=/(\b[a-z][a-z0-9+.-]*:\/\/[^:/@\s]*:)([^@\s/]{8,})(?=@)/gi,Ex=/([?&](?: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("<")||xg.test(i)?i:(n.has(i)||n.set(i,n.size+1),s.add(wr),`<hidden-${n.get(i)}>`);for(let i of xx)r=r.replace(i,o);r=r.replace(Cx,i=>/\d/.test(i)?o(i):i),r=r.replace(Ix,(i,a,c)=>a+(Sg(c)?c:o(c))),r=r.replace(Ax,(i,a,c)=>a+c.replace(/=([^;\s]{16,})/g,(l,d)=>`=${o(d)}`)),r=r.replace(Rx,(i,a,c)=>a+o(c)),r=r.replace(Ex,(i,a,c)=>a+o(c)),r=r.replace(_x,(i,a,c,l,d)=>$x.test(c)&&!/[$(){}[\]]/.test(d)&&(/["']$/.test(l)||!Sg(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 $g=32*1024*1024,Mx=256*1024*1024,As=e=>(t,n,r)=>{(typeof t!="string"||t.trim().length<e)&&r.push(`${n} must be ${e?"non-empty ":""}text`)},Lx=(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)},Xe=(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=As(1),Dx=at({steps:Xe(ee,1),files:Xe(ee),observe:ee}),Fx=at({id:ee,kind:sn("command","request","ui_action","test","other"),action:ee,output:As(0),files:Xe(ee)}),Hx=at({path:ee,mediaType:ee,bytes:Lx,caption:As(0),frames:Xe(ee)}),Ux=at({name:ee,kind:ee,class:sn("local","staging","production"),access:sn("read","write"),whyAllowed:ee}),qx=at({part:ee,by:ee,version:ee,cannotShow:ee}),Bx=at({asked:ee,answer:sn("granted","declined","unavailable"),source:sn("asked_this_run","canary_md")}),Wx=at({by:sn("normal_use","put_in_place"),how:ee}),Rg={steps:Xe(Fx),files:Xe(Hx),targets:Xe(Ux),standIns:Xe(qx),permissions:Xe(Bx),diff:ll(As(0)),reproduction:ll(Dx)},Jx=at({jobId:ee,claim:at({verdict:sn("broken","held","not_reproduced","cannot_run"),summary:ee,stepIds:Xe(ee)}),ranOn:at({where:sn("canary_computer","user_machine"),by:ee,environment:ee,commit:ee,target:As(0),services:Xe(ee)}),...Rg,couldNotRun:ll(at({tried:Xe(ee),proved:Xe(ee),missing:ee,whoCouldNotProvide:ee}))}),Gx=at({jobId:ee,answer:ee,...Rg});function Vx(e,t){let n=[];if((t==="pack"?Jx:Gx)(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&&Wx(r.claim.startingState,"claim.startingState",n)}return n}var Ig={".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"},Ag=e=>e.subarray(0,8e3).includes(0),Kx=new Set(["path","id","jobId","commit","mediaType","verdict","kind","class","access","source","where"]);function Eg(e,t,n,r,s){let o=t==="pack"?"pack.json":"delta.json",i;try{i=JSON.parse(il(jt(e,o),"utf8"))}catch(y){throw new j("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 j("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=On.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=Vx(i,t);if(a.length)throw new j("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),On.test(y)&&c.files.push({path:y,mediaType:Ig[_g(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)!On.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 j("invalid_pack",`The evidence doesn't hold together: ${a.slice(0,8).join("; ")}`);let u=[...l].sort().map(y=>{let k=il(jt(e,y)),T=Nx(jt(e,y)).mtimeMs,J=n.scripts.includes(y)?jt(n.scriptsFrom,y.slice(y.indexOf("/")+1)):null,ae=n.byHand.paths.get(cl(J&&Tx(J)?J:jt(e,y)))!==void 0||n.byHand.contents.has(zc(k))?"hand":n.startedAt&&T<n.startedAt-2e3?"before":"run";return{path:y,by:ae,text:!Ag(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 j("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 T=g(k);for(let J of T.hidden)f.push({name:J,path:y});return T.text},C=[...l].sort().map(y=>{let k=il(jt(e,y));return{path:y,data:k,text:k.length>$g||Ag(k)?null:k.toString("utf8")}}),_=new Set(c.steps.map(y=>y.id)),b=y=>JSON.parse(JSON.stringify(c),(k,T)=>typeof T!="string"||Kx.has(k)||l.has(T)||_.has(T)?T:y(T));for(let y of C)y.text!==null&&g(y.text);b(y=>g(y).text);let x=new Map;for(let{path:y,data:k,text:T}of C){let J=T===null?T:m(y,T);x.set(y,J===null||J===T?k:Buffer.from(J))}let S=b(y=>m(o,y));for(let y of S.files)y.bytes=x.get(y.path)?.length??y.bytes;let v=new Map([[o,Buffer.from(JSON.stringify(S,null,2))],...x]),$=[...v].map(([y,k])=>({path:y,mediaType:y===o?"application/json":p.get(y)??Ig[_g(y).toLowerCase()]??"application/octet-stream",bytes:k.length,sha256:Ox("sha256").update(k).digest("hex")})),O=$.filter(y=>y.bytes>$g).map(y=>y.path);if(O.length)throw new j("too_large",`Over 32 MB: ${O.join(", ")}.`,"Leave out what the scenario doesn't need, or trim long recordings.");if($.reduce((y,k)=>y+k.bytes,0)>Mx)throw new j("too_large","The evidence is over 256 MB in total.","Leave out what the scenario doesn't need, or trim long recordings.");return{pack:S,upload:{kind:t,proofRequestId:r,files:$},bytes:v,hidden:f}}function al(e,t){try{let n=cl(e);if(!cl(jt(e,t)).startsWith(n+Px))return null;let s=jx(jt(e,t));return s.isFile()?s.size:null}catch{return null}}var Og=`Evidence for one job: packs/<job>/pack.json in the batch folder, with any file it names beside it
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
738
1778
  (paths relative to that folder, plain names, no leading dot).
739
1779
 
740
1780
  What came back is not yours to write. Canary captures what every command you run prints, and notes
@@ -777,85 +1817,85 @@ reproduction may be null when nothing broke.
777
1817
  An answer to request <n>: packs/<job>/proof-<n>/delta.json, with only new steps and files; a file
778
1818
  needs a path not already sent with the job. Its reproduction, when not null, replaces the job's:
779
1819
  { "answer": "what was done, or why it couldn't be", "steps": [], "files": [], "targets": [], "standIns": [],
780
- "permissions": [], "reproduction": null }`;w();import{homedir as Yx}from"node:os";import{basename as oi,isAbsolute as zx,join as Qx,resolve as Xx}from"node:path";var Tg=e=>!/[$`*?]/.test(e);function jg(e,t){let n=e.indexOf("<<"),r=n===-1?e:e.slice(0,(e.indexOf(`
781
- `,n)+1||e.length+1)-1),s=[],o=t,i=[],a=null,c=null,l="word",d=f=>f.startsWith("~/")?Qx(Yx(),f.slice(2)):zx(f)?f:o===null?null:Xx(o,f),u=f=>{let g=Tg(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]&&Tg(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 _=i.findIndex(b=>oi(b)==="curl"||oi(b)==="wget");if(_!==-1){let b=oi(i[_])==="wget",x=b?"--output-document":"--output",S=b?/^-[a-zA-Z]*O$/:/^-[a-zA-Z]*o$/,v=i.slice(_+1);v.forEach(($,O)=>{$.startsWith(`${x}=`)?u($.slice(x.length+1)):($===x||S.test($))&&v[O+1]&&v[O+1]!=="-"&&u(v[O+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===`
782
- `||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 Zx,isAbsolute as ul,join as eC,resolve as ii,sep as dl}from"node:path";var Nt=e=>({reason:e,shared:!1}),hl=e=>({reason:e,shared:!0}),Lg=new Set(["sudo","env","command","exec","time","nohup","nice","xargs"]),Dg=new Set(["bash","sh","zsh","source","."]),Ng=new Set(["rm","rmdir","unlink","shred","trash"]),tC=new Set(["node","python","python3","ruby","perl","deno","bun"]),nC=/\b(rmSync|rmdirSync|unlinkSync|rmtree|removedirs|FileUtils\.rm\w*|File\.delete)\b|\b(fs|fsp|os|shutil)\.(rm|rmdir|unlink|remove)\b|\bunlink\s*\(/,rC=new Set(["psql","mysql","mariadb","mongosh","mongo","redis-cli","cockroach","clickhouse-client","sqlcmd"]),sC=new Set(["dropdb","dropuser"]),oC=/\b(drop\s+(table|database|schema|index|collection)|truncate(\s+table)?\s+\w+|delete\s+from|flushall|flushdb|dropdatabase|deletemany)\b|\.drop\(/i,iC={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/},aC=new Set(["-H","--host","--context","--config","-c","-l","--log-level"]),cC=new Set(["-p","--project-name","-f","--file","--profile","--env-file","--project-directory"]),Pg=new Set(["volume","network","container","image","system","builder"]),ai="",on="",lC=new Set(["export","local","readonly","declare","typeset"]),Mg=new Set(["{","}","then","do","else","elif","if","while","until","!","fi","done"]),ci=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;function fl(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=fl(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 uC(e){let t=e.split(`
783
- `),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)&&!Lg.has(br(a)));Dg.has(br(i??""))||(r=o)}return n.join(`
784
- `)}function dC(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=fl(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]!==`
1820
+ "permissions": [], "reproduction": null }`;w();import{homedir as KS}from"node:os";import{basename as oi,isAbsolute as zS,join as XS,resolve as ZS}from"node:path";var Ng=e=>!/[$`*?]/.test(e);function _g(e,t){let n=e.indexOf("<<"),r=n===-1?e:e.slice(0,(e.indexOf(`
1821
+ `,n)+1||e.length+1)-1),s=[],o=t,i=[],a=null,c=null,l="word",d=f=>f.startsWith("~/")?XS(KS(),f.slice(2)):zS(f)?f:o===null?null:ZS(o,f),u=f=>{let g=Ng(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]&&Ng(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===`
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 QS,isAbsolute as ul,join as e1,resolve as ii,sep as dl}from"node:path";var jt=e=>({reason:e,shared:!1}),hl=e=>({reason:e,shared:!0}),Lg=new Set(["sudo","env","command","exec","time","nohup","nice","xargs"]),Fg=new Set(["bash","sh","zsh","source","."]),jg=new Set(["rm","rmdir","unlink","shred","trash"]),t1=new Set(["node","python","python3","ruby","perl","deno","bun"]),n1=/\b(rmSync|rmdirSync|unlinkSync|rmtree|removedirs|FileUtils\.rm\w*|File\.delete)\b|\b(fs|fsp|os|shutil)\.(rm|rmdir|unlink|remove)\b|\bunlink\s*\(/,r1=new Set(["psql","mysql","mariadb","mongosh","mongo","redis-cli","cockroach","clickhouse-client","sqlcmd"]),s1=new Set(["dropdb","dropuser"]),o1=/\b(drop\s+(table|database|schema|index|collection)|truncate(\s+table)?\s+\w+|delete\s+from|flushall|flushdb|dropdatabase|deletemany)\b|\.drop\(/i,i1={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/},a1=new Set(["-H","--host","--context","--config","-c","-l","--log-level"]),c1=new Set(["-p","--project-name","-f","--file","--profile","--env-file","--project-directory"]),Pg=new Set(["volume","network","container","image","system","builder"]),ai="",on="",l1=new Set(["export","local","readonly","declare","typeset"]),Mg=new Set(["{","}","then","do","else","elif","if","while","until","!","fi","done"]),ci=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;function fl(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=fl(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 u1(e){let t=e.split(`
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)&&!Lg.has(br(a)));Fg.has(br(i??""))||(r=o)}return n.join(`
1824
+ `)}function d1(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=fl(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]!==`
785
1825
  `;)c++;i();continue}if(l===`
786
- `||l===";"||l==="|"||l==="&"){i();continue}if(l===" "||l===" "){o();continue}r=(r??"")+l}return i(),t}var hC=(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(dl)?g:g+dl)),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=fl(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,_,b)=>{let x=(C??b)==="PWD"?i:a.get(C??b);return typeof x=="string"?x:_===void 0?on:c(_)}).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&&!ul(C))return null;let _=ul(C)?ii(C):ii(i,C);return g[2]===void 0?_:Zx(_)},u=new Set,h=oC.test(e),p=[];for(let f of dC(uC(r?hC(e,r):e))){if(f[0]==="("){p.push(i);continue}if(f[0]===")"){i=p.pop()??i;continue}let g=f.slice(f.findIndex(A=>!Mg.has(A)));if(f.every(A=>Mg.has(A)))continue;if(g[0]==="for"&&g[2]==="in"&&g[1]){let A=g.slice(3).map(l);a.set(g[1],A.length>0&&A.every(M=>M!==null&&/^[\w@%+=:,-][\w.@%+=:,-]*$/.test(M))?A[0]:on);continue}let m=lC.has(g[0])?g.slice(1).filter(A=>!A.startsWith("-")):g,C=m.findIndex(A=>!ci.test(A)),_=new Map;for(let A of C<0?m:m.slice(0,C)){let[,M,R]=ci.exec(A),q=/^\$\(\s*mktemp\b/.test(R)?eC(t.roots[0]??t.cwd,".tmp"):c(R);C<0?a.set(M,q):q.includes(on)||_.set(M,q)}if(C<0)continue;let b=m.slice(C).map(A=>{let M=c(A),R=M.includes(on);return{text:R?A:M.split(ai).join("$"),opaque:R,known:R?M.slice(0,M.indexOf(on)):""}}),x=A=>{if(A.opaque)return null;let M=A.text.split(/[*?[{]/)[0],R=M==="~"||M.startsWith("~/")?t.home+M.slice(1):M;return ul(R)?ii(R):i===null?null:ii(i,R)},S=A=>{let M=A.opaque&&A.known&&!/(^|\/)\.\.(\/|$)/.test(A.text)?A.known.slice(0,A.known.lastIndexOf("/")+1)||".":null,R=x(M?{text:M,opaque:!1,known:""}:A);return R===null||!(o(R)||[...u].some(q=>R===q||R.startsWith(q+dl)))},v=b.filter((A,M)=>{let R=/^\d*>>?(.*)$/.exec(A.text),q=/^\d*>>?$/.test(b[M-1]?.text??""),G=R?.[1]?{...A,text:R[1]}:q?A:null,te=G&&x(G);return te&&te!=="/dev/null"&&u.add(te),!R&&!q&&!/^\d*<</.test(A.text)&&!/^\d*</.test(A.text)});if(v.length===0)continue;let $=v,O=!1;for(;$.length>1&&(Lg.has(br($[0].text))||ci.test($[0].text)||$!==v&&$[0].text.startsWith("-"));)O||=br($[0].text)==="xargs",$=$.slice(1);let y=br($[0].text),k=$.slice(1),T=k.filter(A=>!A.text.startsWith("-")),J=(...A)=>k.some(M=>A.includes(M.text)),Le=$.map(A=>A.text).join(" ");if(y==="cd"){i=T[0]?x(T[0]):null;continue}if(["touch","mkdir","tee","mkfifo"].includes(y)){for(let A of T){let M=x(A);M&&u.add(M)}continue}let Ce=()=>new Map(a);if(y==="trap"||y==="eval"){let A=m.slice(C+(v.length-$.length)+1).find(R=>!R.startsWith("-")),M=A===void 0?null:li(A.split(ai).join("$"),{...t,cwd:i??t.cwd},n+1,r,Ce());if(M)return M;continue}if(Dg.has(y)){let A=k.findIndex(G=>/^-[a-z]*c[a-z]*$/.test(G.text)),M=A<0&&T[0]?x(T[0]):null,R=A>=0?k[A+1]?.text??null:M&&o(M)&&n<2?t.read(M):null,q=R===null?null:li(R,{...t,cwd:i??t.cwd},n+1,A>=0?r:M,A>=0?Ce():_);if(q)return q;continue}if(Ng.has(y)){if(O)return Nt("it removes whatever files it is handed");let A=T.find(S);if(A)return Nt(`it removes ${A.text}, which isn't in the checks' own folders`);continue}if(y==="mv"){if(O)return Nt("it moves away whatever files it is handed");let A=J("-t","--target-directory"),M=(A?T:T.slice(0,-1)).find(S);if(M)return Nt(`it moves ${M.text} away, which isn't in the checks' own folders`);let R=A?null:T.at(-1)&&x(T.at(-1));R&&u.add(R);continue}if(y==="find"){let A=k.some((q,G)=>q.text==="-delete"||["-exec","-execdir","-ok"].includes(q.text)&&Ng.has(br(k[G+1]?.text??""))),M=k.findIndex(q=>q.text.startsWith("-")||q.text==="("||q.text==="!"),R=M<0?k:k.slice(0,M);if(A&&(R.length===0||R.some(S)))return Nt("it deletes files it finds outside the checks' own folders");continue}if(tC.has(y)){let A=k.findIndex(M=>["-e","-c","--eval","-p"].includes(M.text));if(A>=0&&nC.test(k[A+1]?.text??""))return Nt("it removes files from code given on the command line");continue}if(y==="git"){let A=k.findIndex(G=>G.text==="-C"),M=A>=0&&k[A+1]?x(k[A+1]):i,R=k.filter((G,te)=>!G.text.startsWith("-")&&!(A>=0&&te===A+1)).map(G=>G.text);if(R[0]==="push"&&(J("--delete","-d")||R.slice(1).some(G=>G.startsWith(":"))))return hl("it deletes a branch or tag on a remote");if((R[0]==="clean"||R[0]==="restore"||R[0]==="rm"||R[0]==="reset"&&J("--hard")||R[0]==="checkout"&&(J("--","-f","--force")||R.includes("."))||R[0]==="stash"&&["drop","clear"].includes(R[1]??"")||["branch","tag"].includes(R[0]??"")&&J("-D","-d","--delete")||R[0]==="worktree"&&R[1]==="remove")&&(M===null||!o(M)))return Nt("it discards or deletes git work outside the checks' own copy");continue}if(y==="docker"||y==="podman"||y==="docker-compose"){let A=k.findIndex((we,Un)=>!we.text.startsWith("-")&&!aC.has(k[Un-1]?.text??"")),M=y==="docker-compose"||k[A]?.text==="compose",R=M?cC:new Set(["--filter"]),q=A<0?[]:k.slice(y==="docker-compose"?0:M?A+1:A),G=q.filter((we,Un)=>!we.text.startsWith("-")&&!R.has(q[Un-1]?.text??"")),te=G.map(we=>we.text),Ve=M?["down","rm"].includes(te[0]??""):["rm","rmi","prune"].includes(te[0]??"")||Pg.has(te[0]??"")&&["rm","remove","prune"].includes(te[1]??""),xt=k.findIndex(we=>we.text==="-p"||we.text==="--project-name"),Ze=xt>=0?k[xt+1]?.text:k.find(we=>we.text.startsWith("--project-name="))?.text.slice(15),z=M&&(Ze===t.composeProject||Ze===void 0&&i!==null&&o(i)),gt=k.some(we=>we.text===`label=${t.label}`||we.text===`--filter=label=${t.label}`),Ct=Pg.has(te[0]??""),_t=M||(Ct?te[1]:te[0])==="prune"?null:te[0]==="rmi"||te[0]==="image"?"image":te[0]==="network"||te[0]==="volume"?te[0]:"container",Tr=G.slice(Ct?2:1),Hs=y==="docker"&&_t!==null&&Tr.length>0&&Tr.every(we=>!we.opaque&&t.dockerOwn?.(_t,we.text)===!0);if(Ve&&!z&&!gt&&!Hs)return Nt("it removes Docker containers, images or volumes that may not be the checks' own");continue}let ae=sC.has(y)||y==="mysqladmin"&&T.some(A=>A.text==="drop");if(rC.has(y)||y==="sqlite3"||ae){let A=y==="sqlite3"?T.length>0&&!S(T[0]):fC(Le,t.ports)&&!/(?:\s-h|--host)[= ]+(?!localhost\b|127\.0\.0\.1\b)\S/.test(Le);if((h||ae)&&!A)return y==="sqlite3"?Nt("it drops or deletes data in a database file that isn't the checks' own"):hl("it drops or deletes data in a database the checks didn't start");continue}if(iC[y]?.test(k.map(A=>A.text).join(" ")))return hl(`it deletes something with ${y}`)}return null}function fC(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 Fg(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 Hg=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 pC,mkdirSync as Ug,readdirSync as qg,writeFileSync as pl}from"node:fs";import{join as kr}from"node:path";var gl=e=>kr(ce(e),"questions");function ct(e){let t=[];for(let{runId:n}of e){let r=gl(n);if(pC(r))for(let s of qg(r).filter(o=>/^Q\d+\.json$/.test(o))){let o=V(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 Bg(e,t){let n=kr(Qe(Rn(e)).dir,"question-ids");Ug(n,{recursive:!0}),Ug(gl(t.runId),{recursive:!0});for(let r=0;r<100;r++){let s=Math.max(0,...qg(n).map(a=>Number(/^Q(\d+)$/.exec(a)?.[1]??0)))+1+r;try{pl(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(gl(t.runId),`${o.id}.json`);return pl(i,JSON.stringify(o,null,2)+`
787
- `,{flag:"wx"}),{...o,path:i}}throw new j("question_ids","Couldn't number a new question; run the command again.")}function Wg(e,t){let n=ct(e).find(r=>r.id.toLowerCase()===t.toLowerCase());if(!n)throw new j("no_such_question",`No question ${t} among this session's checks.`,"Use the id the listener printed.");return n}function Jg(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 ml(e){let t=V(e),r=(t?.status==="answered"?[t.answer??"",...(t.more??[]).map(s=>s.text)]:[]).flatMap((s,o)=>{try{return pl(`${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 ct(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 Gg(e){return V(e)}var Je=6e4,xC=9.5*Je,CC=9*Je,_C=5*Je,vr=5e3,Ln=2*Je,Xg=5*Je,Os=5e3,$C=1500,IC=e=>6e4+Math.ceil(e/131),Sr=e=>e.slice(0,8),Il=e=>`verifier-${Sr(e)}`,an=e=>new Promise(t=>setTimeout(t,e)),I=e=>void process.stdout.write(`${e}
1826
+ `||l===";"||l==="|"||l==="&"){i();continue}if(l===" "||l===" "){o();continue}r=(r??"")+l}return i(),t}var h1=(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(dl)?g:g+dl)),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=fl(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&&!ul(C))return null;let A=ul(C)?ii(C):ii(i,C);return g[2]===void 0?A:QS(A)},u=new Set,h=o1.test(e),p=[];for(let f of d1(u1(r?h1(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=>!Mg.has(T)));if(f.every(T=>Mg.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=l1.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)?e1(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 ul(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+dl)))},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,te=J&&S(J);return te&&te!=="/dev/null"&&u.add(te),!E&&!U&&!/^\d*<</.test(T.text)&&!/^\d*</.test(T.text)});if(v.length===0)continue;let I=v,$=!1;for(;I.length>1&&(Lg.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(Fg.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(jg.has(y)){if($)return jt("it removes whatever files it is handed");let T=N.find(x);if(T)return jt(`it removes ${T.text}, which isn't in the checks' own folders`);continue}if(y==="mv"){if($)return jt("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 jt(`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)&&jg.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 jt("it deletes files it finds outside the checks' own folders");continue}if(t1.has(y)){let T=k.findIndex(M=>["-e","-c","--eval","-p"].includes(M.text));if(T>=0&&n1.test(k[T+1]?.text??""))return jt("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,te)=>!J.text.startsWith("-")&&!(T>=0&&te===T+1)).map(J=>J.text);if(E[0]==="push"&&(G("--delete","-d")||E.slice(1).some(J=>J.startsWith(":"))))return hl("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 jt("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("-")&&!a1.has(k[Bn-1]?.text??"")),M=y==="docker-compose"||k[T]?.text==="compose",E=M?c1: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??"")),te=J.map(we=>we.text),Ye=M?["down","rm"].includes(te[0]??""):["rm","rmi","prune"].includes(te[0]??"")||Pg.has(te[0]??"")&&["rm","remove","prune"].includes(te[1]??""),St=k.findIndex(we=>we.text==="-p"||we.text==="--project-name"),Qe=St>=0?k[St+1]?.text:k.find(we=>we.text.startsWith("--project-name="))?.text.slice(15),z=M&&(Qe===t.composeProject||Qe===void 0&&i!==null&&o(i)),gt=k.some(we=>we.text===`label=${t.label}`||we.text===`--filter=label=${t.label}`),Ct=Pg.has(te[0]??""),At=M||(Ct?te[1]:te[0])==="prune"?null:te[0]==="rmi"||te[0]==="image"?"image":te[0]==="network"||te[0]==="volume"?te[0]:"container",Nr=J.slice(Ct?2:1),Ws=y==="docker"&&At!==null&&Nr.length>0&&Nr.every(we=>!we.opaque&&t.dockerOwn?.(At,we.text)===!0);if(Ye&&!z&&!gt&&!Ws)return jt("it removes Docker containers, images or volumes that may not be the checks' own");continue}let ae=s1.has(y)||y==="mysqladmin"&&N.some(T=>T.text==="drop");if(r1.has(y)||y==="sqlite3"||ae){let T=y==="sqlite3"?N.length>0&&!x(N[0]):f1(Le,t.ports)&&!/(?:\s-h|--host)[= ]+(?!localhost\b|127\.0\.0\.1\b)\S/.test(Le);if((h||ae)&&!T)return y==="sqlite3"?jt("it drops or deletes data in a database file that isn't the checks' own"):hl("it drops or deletes data in a database the checks didn't start");continue}if(i1[y]?.test(k.map(T=>T.text).join(" ")))return hl(`it deletes something with ${y}`)}return null}function f1(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 Dg(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 Wg=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 p1,mkdirSync as Bg,readdirSync as Ug,writeFileSync as pl}from"node:fs";import{join as kr}from"node:path";var gl=e=>kr(ce(e),"questions");function ct(e){let t=[];for(let{runId:n}of e){let r=gl(n);if(p1(r))for(let s of Ug(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 Hg(e,t){let n=kr(Xe(En(e)).dir,"question-ids");Bg(n,{recursive:!0}),Bg(gl(t.runId),{recursive:!0});for(let r=0;r<100;r++){let s=Math.max(0,...Ug(n).map(a=>Number(/^Q(\d+)$/.exec(a)?.[1]??0)))+1+r;try{pl(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(gl(t.runId),`${o.id}.json`);return pl(i,JSON.stringify(o,null,2)+`
1827
+ `,{flag:"wx"}),{...o,path:i}}throw new _("question_ids","Couldn't number a new question; run the command again.")}function qg(e,t){let n=ct(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 Gg(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 ml(e){let t=Y(e),r=(t?.status==="answered"?[t.answer??"",...(t.more??[]).map(s=>s.text)]:[]).flatMap((s,o)=>{try{return pl(`${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 ct(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 Jg(e){return Y(e)}var Ge=6e4,S1=9.5*Ge,C1=9*Ge,A1=5*Ge,vr=5e3,Ln=2*Ge,Zg=5*Ge,$s=5e3,I1=1500,R1=e=>6e4+Math.ceil(e/131),xr=e=>e.slice(0,8),Rl=e=>`verifier-${xr(e)}`,an=e=>new Promise(t=>setTimeout(t,e)),R=e=>void process.stdout.write(`${e}
788
1828
  `),di=460;function Mn(e){for(let t of e.split(`
789
- `)){let n=t;for(;n.length>di;){let r=n.lastIndexOf(" ",di),s=r>di/2?r:di;I(`${n.slice(0,s)} \u2026`),n=`\u2026 ${n.slice(s).trimStart()}`}I(n)}}var hi=e=>e.map(t=>t.trim().replace(/[.!?]+$/,n=>n.includes("?")?"?":"")).join(" | ").replace(/([^?])$/,"$1.");function Ir(e=process.cwd()){try{return Yg("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}),Ge=e=>Object.entries(ot(e).runs).map(([t,{checkout:n}])=>({runId:t,checkout:n}));function Zg(e){try{if(!Ae(P(ce(e),"source.bundle")))return[];let t=P(ce(e),"results");return yi(t).filter(n=>n.endsWith(".json")).flatMap(n=>{let r=V(P(t,n));return r?.verdict==="blocked"?[`${JSON.stringify(r.scenario.title)} [${r.jobId}]`]:[]})}catch{return[]}}var Ts=e=>Zg(e).length>0;async function AC(){let e=process.env.CLAUDE_CODE_SESSION_ID?.trim();if(!e)return;let t=Ge(e).filter(({runId:r})=>Ae(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)&&!Ts(r)&&Fn(P(ce(r),"source.bundle"),{force:!0})}function ye(e,t={}){return async(...n)=>{try{if(t.sweep!==!1){If(),t.urgent||await Qf(async r=>void await Nn(r,{dockerTimeoutMs:5e3}));for(let r of await Zp(!t.urgent&&!t.local))console.error(`Canary left in place from ${r}`);t.local||await AC().catch(()=>{})}await e(...n)}catch(r){if(r instanceof j||r instanceof L)console.error(`${Yo(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 vs(s,{},r,5e3).catch(()=>{})}process.exitCode=1}}}function St(e,t){let n=en(e);return t(n),fs(n),n}var RC=["environment_missing","information_unavailable","approval_declined","target_unreachable","tool_install_failed","auto_mode_blocked"],EC={broken:"failed",held:"passed",not_reproduced:"unclear",inconclusive:"unclear",blocked:"couldn't run"},Al=e=>e&&EC[e]||"no verdict",em=e=>e.blockedReason?.kind==="stopped_by_user"?"stopped by the user":e.blockedReason?.kind==="to_prove"?"not tried yet":Al(e.verdict),Rs=(e,t)=>t.verdict==="blocked"?em(V(P(ce(e),"results",`${t.jobId}.json`))??{verdict:t.verdict,blockedReason:null}):Al(t.verdict);function Rl(e){let t=Be(e);return(t&&V(P(Qe(t).scripts,pi)))??{}}function bl(e){let t=Ge(_e()).find(r=>r.runId===e)?.checkout,n=Object.entries(t?Rl(t):{}).map(([r,s])=>`${r} (${s.what})`);return n.length?` Another try starts setup from what earlier tries kept: ${n.join("; ")}.`:""}function tm(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 nm(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}${OC(t,e.whereToLook)}`]:[]]}function OC(e,t){let n=/^(.+?):(\d+)(?:-(\d+))?$/.exec(t.trim()),r=V(P(ce(e),"source.json")),s=Ge(_e()).find(a=>a.runId===e)?.checkout,o=s?Be(s):null;if(!n||!r?.baseTreeHash||!r.treeHash||r.baseTreeHash===r.treeHash||!o)return"";let i=P(W(),"workspaces",ir(o));for(let a of Ae(i)?yi(i).filter(c=>/^\d+$/.test(c)):[]){let c;try{c=Yg("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 El(e,t){let n=e.scenario.claim,r=em(e),s=e.verdict==="held"&&e.scenario.claim!==null?" It didn't happen.":"",o=[`# ${r[0].toUpperCase()}${r.slice(1)}: ${e.scenario.title}${s}`,"",tm(e),...nm(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(`
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 Kg("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(ot(e).runs).map(([t,{checkout:n}])=>({runId:t,checkout:n}));function Qg(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 Ns=e=>Qg(e).length>0;async function T1(){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)&&!Ns(r)&&Dn(P(ce(r),"source.bundle"),{force:!0})}function ye(e,t={}){return async(...n)=>{try{if(t.sweep!==!1){Rf(),t.urgent||await Xf(async r=>void await jn(r,{dockerTimeoutMs:5e3}));for(let r of await Qp(!t.urgent&&!t.local))console.error(`Canary left in place from ${r}`);t.local||await T1().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 vs(s,{},r,5e3).catch(()=>{})}process.exitCode=1}}}function xt(e,t){let n=en(e);return t(n),fs(n),n}var E1=["environment_missing","information_unavailable","approval_declined","target_unreachable","tool_install_failed","auto_mode_blocked"],O1={broken:"failed",held:"passed",not_reproduced:"unclear",inconclusive:"unclear",blocked:"couldn't run"},Tl=e=>e&&O1[e]||"no verdict",em=e=>e.blockedReason?.kind==="stopped_by_user"?"stopped by the user":e.blockedReason?.kind==="to_prove"?"not tried yet":Tl(e.verdict),Es=(e,t)=>t.verdict==="blocked"?em(Y(P(ce(e),"results",`${t.jobId}.json`))??{verdict:t.verdict,blockedReason:null}):Tl(t.verdict);function El(e){let t=He(e);return(t&&Y(P(Xe(t).scripts,pi)))??{}}function bl(e){let t=Je(Ae()).find(r=>r.runId===e)?.checkout,n=Object.entries(t?El(t):{}).map(([r,s])=>`${r} (${s.what})`);return n.length?` Another try starts setup from what earlier tries kept: ${n.join("; ")}.`:""}function tm(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 nm(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}${$1(t,e.whereToLook)}`]:[]]}function $1(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?He(s):null;if(!n||!r?.baseTreeHash||!r.treeHash||r.baseTreeHash===r.treeHash||!o)return"";let i=P(q(),"workspaces",ir(o));for(let a of Te(i)?yi(i).filter(c=>/^\d+$/.test(c)):[]){let c;try{c=Kg("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 Ol(e,t){let n=e.scenario.claim,r=em(e),s=e.verdict==="held"&&e.scenario.claim!==null?" It didn't happen.":"",o=[`# ${r[0].toUpperCase()}${r.slice(1)}: ${e.scenario.title}${s}`,"",tm(e),...nm(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(`
790
1830
  `)}
791
- `}function kl(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))/Je);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 TC=4*Je;async function jC(){let e=_e(),t=cr(),n=Ef(e),r=Ir();vt(e,y=>({...y,owner:t??y.owner??null}));let s=y=>ot(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&&I("Canary: reachable again."),l=null,d=!1,k}catch(k){if(!Tt(k))throw k;return l??=Date.now(),!d&&Date.now()-l>Xg&&(d=!0,I("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 T of[...k.batches.flatMap(J=>J.jobs),...k.computer??[]])o.set(T.jobId,T.title)}return vt(e,k=>{for(let T of y.runs)k.runs[T.runId]??={checkout:r};return k}),!0};for(;!await h();)await an(vr);vl(a.runs.map(y=>s(y.runId)));let p=new Set,f=new Map,g=new Map,m=new Map,C=!1,_=async y=>{if(!C){C=!0;try{for(let[k,T]of[...g]){let J=m.get(k)??Ln;if(!y&&Date.now()-T<J)continue;g.delete(k);let Le=Q().find(A=>A.batchId===k&&A.sessionId===e&&!A.left);if(!Le)continue;let Ce=await Nn(Le),ae=m.has(k)?"finished its setup":"cleaned up";Mn(`Canary: the verifier for batch ${k} hadn't ${ae} ${Math.round(J/Je)} 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=>rm(y,a),x=!1,S=async()=>{if(!x){x=!0;try{for(let y of Q().filter(k=>k.sessionId===e&&k.claimed&&!k.ended)){let k=Mc(y.batchId);k&&await M_(y,k)}}finally{x=!1}}},v=0,$=async()=>{let y=new Map;for(let k of Q().filter(T=>T.sessionId===e))y.set(k.runId,[...y.get(k.runId)??[],k.batchId]);for(let[k,T]of y){let J=ri(e,T);J.length>0&&await oe(`/cli/jobs/runs/${k}/setups`,{session:e,method:"POST",json:{setups:J}}).catch(()=>{})}};for(let y of ct(Ge(e)).filter(b))f.set(y.path,Date.now()),Mn(kl(y,!0,o));let O=setInterval(()=>{if(n()){for(let y of ct(Ge(e)).filter(b)){let k=f.get(y.path);k!==void 0&&Date.now()-k<TC||(f.set(y.path,Date.now()),Mn(kl(y,k!==void 0,o)))}_(!1),S(),Date.now()-v>=ni&&(v=Date.now(),$());for(let y of ys(e)){let k=a.runs.flatMap(T=>T.batches).find(T=>T.batchId===y.batchId);if(!k||k.state!=="queued"){tn(y.batchId);continue}!gs(Zt(y.checkout))||ps(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 Ot(y.batchId)){let T=ks(k);!T||p.has(k)||(p.add(k),Mn(`Canary: a check is waiting for the user to approve a command, because ${T}. Tell them so in a line now: the approval prompt itself doesn't say why they are asked.`))}}},2e3);try{for(;;){if(!n())return I("Canary: this listener was replaced by a newer one.");if(t&&!sr(t))return I("Canary: the Claude Code session ended; this listener stops.");let y=ot(e).cursors,k=Object.entries(y).map(([R,q])=>`${R}:${q}`).join(","),T=Date.now(),J=await u(()=>oe(`/cli/jobs/events${k?`?cursors=${k}`:""}`,{session:e,timeoutMs:Uc}));if(!J){await an(vr);continue}if(!n())return I("Canary: this listener was replaced by a newer one.");let Le=0,Ce=0,ae=J.events.filter(R=>R.type==="jobs");ae.length&&(await h(),vl(ae.map(R=>s(R.runId))),[...new Set(ae.map(R=>s(R.runId)))].some(R=>Wc(R))&&Mn(NC));for(let R of J.events){if(R.type==="wait_over"&&R.batchId&&Pn(Ge(e),R.batchId,R.jobId),R.type==="batch_ended"&&R.batchId){let G=R.batchId;g.set(G,Date.now());let te=Q().find(Ve=>Ve.batchId===G&&Ve.sessionId===e);R.reason==="set_aside"&&m.set(G,(te?.setupMinutes??30)*Je),te&&js([G],(m.get(G)??Ln)+3e4)}let q=PC(R,o);q&&Mn(q),R.type==="result"&&Le++,R.type==="report"&&R.final&&(Ce++,Ts(R.runId)||Fn(P(ce(R.runId),"source.bundle"),{force:!0}))}vt(e,R=>{for(let[q,G]of Object.entries(J.cursors))R.cursors[q]=Math.max(R.cursors[q]??0,G);return R});for(let{runId:R}of Ge(e))qo(R);Le>0&&await MC(J.events,i,s);let A=J.events.length===0,M=A&&Date.now()-T<vr;if(M&&await an(vr),(Ce>0||M||A&&Date.now()-c>2*Je)&&await h(),a.runs.length===0&&(A||Ce>0)){let R=()=>[...g].filter(([q])=>Q().some(G=>G.batchId===q&&G.sessionId===e&&!G.left));for(;R().some(([,q])=>Date.now()-q<Ln);)await an(vr);if(await _(!0),!n())return I("Canary: this listener was replaced by a newer one.");if(await h(),a.runs.length>0)continue;return I(Ce>0?"Canary: every check for this session has finished.":"Canary: no open checks for this session.")}}}finally{clearInterval(O)}}var NC="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 rm(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 PC(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 ${Sr(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(`
792
- `);case"result":{let r=P(ce(e.runId),"results",`${e.record.jobId}.json`);Dn(pt(r),{recursive:!0}),Es(r,JSON.stringify(e.record,null,2)+`
793
- `);let s=r.replace(/\.json$/,".md");if(Es(s,El(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: ${Al(e.record.verdict)}${o}. Check: ${JSON.stringify(e.record.scenario.title)}. Full record: ${s}`,tm(e.record),...nm(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${RC.includes(e.record.blockedReason?.kind??"")?", once what it lacked is in place":""}: canary jobs retry ${e.runId} ${e.record.jobId}.${bl(e.runId)}`]:[]].join(`
794
- `)}case"report":{let r=new Map;for(let l of e.finished)r.set(Rs(e.runId,l),(r.get(Rs(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 ${Sr(e.runId)}: no part of this run called for a check.`;let o=e.finished.map(l=>`${JSON.stringify(l.title)}: ${Rs(e.runId,l)}`).join("; "),i=new Map;for(let l of e.finished.filter(d=>d.verdict==="broken")){let d=V(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?`
1831
+ `}function kl(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 N1=4*Ge;async function _1(){let e=Ae(),t=cr(),n=Of(e),r=Rr();vt(e,y=>({...y,owner:t??y.owner??null}));let s=y=>ot(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(!Nt(k))throw k;return l??=Date.now(),!d&&Date.now()-l>Zg&&(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);vl(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=>rm(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=Mc(y.batchId);k&&await MC(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 ct(Je(e)).filter(b))f.set(y.path,Date.now()),Mn(kl(y,!0,o));let $=setInterval(()=>{if(n()){for(let y of ct(Je(e)).filter(b)){let k=f.get(y.path);k!==void 0&&Date.now()-k<N1||(f.set(y.path,Date.now()),Mn(kl(y,k!==void 0,o)))}A(!1),x(),Date.now()-v>=ni&&(v=Date.now(),I());for(let y of ys(e)){let k=a.runs.flatMap(N=>N.batches).find(N=>N.batchId===y.batchId);if(!k||k.state!=="queued"){tn(y.batchId);continue}!gs(Qt(y.checkout))||ps(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 $t(y.batchId)){let N=ks(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=ot(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:Bc}));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(),vl(ae.map(E=>s(E.runId))),[...new Set(ae.map(E=>s(E.runId)))].some(E=>qc(E))&&Mn(j1));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 te=X().find(Ye=>Ye.batchId===J&&Ye.sessionId===e);E.reason==="set_aside"&&m.set(J,(te?.setupMinutes??30)*Ge),te&&_s([J],(m.get(J)??Ln)+3e4)}let U=P1(E,o);U&&Mn(U),E.type==="result"&&Le++,E.type==="report"&&E.final&&(Ce++,Ns(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 M1(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 j1="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 rm(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 P1(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(`
1832
+ `);case"result":{let r=P(ce(e.runId),"results",`${e.record.jobId}.json`);Fn(pt(r),{recursive:!0}),Os(r,JSON.stringify(e.record,null,2)+`
1833
+ `);let s=r.replace(/\.json$/,".md");if(Os(s,Ol(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: ${Tl(e.record.verdict)}${o}. Check: ${JSON.stringify(e.record.scenario.title)}. Full record: ${s}`,tm(e.record),...nm(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${E1.includes(e.record.blockedReason?.kind??"")?", once what it lacked is in place":""}: canary jobs retry ${e.runId} ${e.record.jobId}.${bl(e.runId)}`]:[]].join(`
1834
+ `)}case"report":{let r=new Map;for(let l of e.finished)r.set(Es(e.runId,l),(r.get(Es(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)}: ${Es(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?`
795
1835
  Where the confirmed problems point: ${[...i].map(([l,d])=>`${l} (${d})`).join(", ")}.`:"",c=e.finished.some(l=>l.verdict==="blocked")?`
796
- 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.${bl(e.runId)}`:"";return`Canary final report for run ${Sr(e.runId)}: all ${e.finished.length} checks have ended: ${s}. Each check's full record is in ${P(ce(e.runId),"results")}.
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.${bl(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")}.
797
1837
  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:
798
- ${e.say}`}}async function MC(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 Xr(n(s),{likeClone:!0})).treeHash)return I("Canary: your files have changed since these checks were requested; their results are for the code as it was then.")}catch{}}var Vg=new Set;function vl(e){for(let t of new Set(e))if(Ae(t))try{let n=Uo(t);if(Vg.has(n.dir))continue;Vg.add(n.dir),I(`Canary: this repository's notes for Canary are in ${n.canaryMd}, and its test secrets in ${n.secrets}.`)}catch(n){n instanceof j&&I(`Canary: ${n.message} ${n.fix??""}`.trim())}}async function LC(){let e=_e(),t=await bi(e),n=new Map(Ge(e).map(c=>[c.runId,c.checkout]));vl(t.runs.flatMap(c=>n.get(c.runId)??[]));let r=new Map(Q().map(c=>[Oc(c.key),Il(c.batchId)])),s=c=>c===null?"nobody":r.get(c)?`${r.get(c)} on this machine`:"another verifier",o=ct(Ge(e)).filter(c=>rm(c,t));for(let{runId:c}of Ge(e).filter(({runId:l})=>!t.runs.some(d=>d.runId===l))){let l=Zg(c);l.length&&I(`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){Ge(e).some(({runId:c})=>Ts(c))||I("No open Canary checks for this session.");return}for(let c of t.runs){I(`Run ${c.runId} (${c.kind}, ${c.coverage.run} of ${c.coverage.considered} finished)`);for(let l of c.batches){let d=Ot(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}`:""}`:"";I(` Batch ${l.batchId} (${l.environment}): ${l.state}, held by ${s(l.holder)}${h}`);let p=l.state==="ended"?void 0:Q().find(g=>g.batchId===l.batchId),f=p?(()=>{try{return _r(le(l.batchId)).birthtimeMs}catch{return null}})():null;if(p&&f!==null){let g=O=>Math.max(0,Math.round((Date.now()-O)/Je)),m=Mp(l.batchId,3),C=qp(l.batchId),_=l.jobs.every(O=>O.state==="queued")?`setting up for ${g(f)} min; `:"",b=C?`set up in ${Math.max(0,Math.round((Date.parse(C)-f)/Je))} min; `:"",x=l.jobs.find(O=>O.state==="queued"),S=l.jobs.some(O=>["running","waiting","stopping","proof"].includes(O.state)),v=!_&&!S&&x?`between checks, the next in order being ${JSON.stringify(x.title)}; `:"",$=m.map(O=>`${O.step} (${O.ended==="background"?"started in the background":O.ended==="running"?"still running":O.ended==="ran"?"ran":O.ended==="failed"?"failed":O.ended==="blocked"?"blocked by Claude Code's auto mode":"didn't run"}, ${g(Date.parse(O.at))} min ago)`);I(` ${_}${b}${v}${$.length?`its verifier's latest steps, oldest first: ${$.join("; ")}`:"no step recorded yet"}`)}l.state==="queued"&&l.questions.length&&I(` Questions to settle first: ${hi(l.questions)}`),l.state==="queued"&&l.permissions.length&&I(` Access to ask for: ${hi(l.permissions)}`);for(let g of l.jobs)I(` ${g.jobId} ${g.state}${g.verdict?` (${Rs(c.runId,g)})`:""} ${g.title}`)}if(c.computer?.length){I(" On Canary's computer:");let l=u=>Math.max(0,Math.round((Date.now()-Date.parse(u))/Je)),d=u=>u.map(h=>`${h.step} (${l(h.at)} min ago)`).join("; ");for(let u of c.computerSandboxes??[])u.readyAt?I(` Sandbox ${u.sandbox}: set up in ${Math.max(0,Math.round((Date.parse(u.readyAt)-Date.parse(u.since))/Je))} min`):I(` 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)I(` ${u.jobId} ${u.state}${u.verdict?` (${Rs(c.runId,u)})`:""} ${u.title}${u.sandbox?` (sandbox ${u.sandbox})`:""}`),(u.state==="running"||u.state==="proof")&&u.steps?.length&&I(` 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)I(kl(c,!0,i));let a;for(let c of new Set(t.runs.flatMap(l=>n.get(l.runId)??[]))){for(let d of $p(c))I(d);let l=a?null:Wc(c);l&&(I(l),a=c)}vt(e,c=>({...c,asking:a}))}var Sl=e=>e instanceof j||e instanceof L&&!!e.code&&!Tt(e),xr=45e3,xl=e=>String(e?.code??""),Cl=e=>["ENOSPC","EDQUOT"].includes(xl(e))||/No space left on device|Disk quota exceeded/.test(String(e?.message));function sm(e){if(["EACCES","EPERM","EROFS"].includes(xl(e)))return xl(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 DC(e){let t=_e(),r=(await We(()=>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 j("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 j("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 FC(r,o)}catch(i){await HC(o,i)}}async function FC(e,t){let{batchId:n,session:r}=t,s=e.batches.find(S=>S.batchId===n),o=ot(r).runs[e.runId]?.checkout??Ir(),i=Ae(P(le(n),"state.json"))?en(n):null;i&&!i.claimed&&i.sessionId===r&&(!i.taker||Xt(i.taker)==="gone")&&Object.assign(t,{resuming:!0,folder:!0,state:i});let a=Uo(o),c=ir(Rn(o)),l=t.receipt=V(P(ce(e.runId),"source.json")),d=P(ce(e.runId),"source.bundle");if(!l||!Ae(d))throw new Error("the run's snapshot isn't on this machine");let u=S=>Rc(l.bytes,Ae(P(de({repoFolder:c,slot:S}),".git"))),h,p={pid:process.pid,startedAt:It(process.pid)??Date.now()};if(t.resuming){let S=u(i.slot);S&&await _l(n,r,S,!0),h=t.state=St(n,v=>{v.taker=p,v.owner=cr()??v.owner})}else{if(ps(o))throw ms(n,r,o),new j("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.");Ff(n),t.folder=!0;let S=Zt(o),v=Uf(n,S);if(v===null)throw ms(n,r,o),new j("machine_busy",`${S} 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 $=u(v);$&&await _l(n,r,$,!1),h={batchId:n,runId:e.runId,sessionId:r,checkout:o,repoFolder:c,key:mC(24).toString("base64url"),owner:cr(),slot:v,ports:await zf(n,v),code:e.code,jobs:s.jobs.map(O=>({jobId:O.jobId,title:O.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,Df(h),tn(n);let m=Xo(o),C=m&&{use:m.use,at:m.at,placed:m.use?hg(o,f,m.files):[]};Dn(dr(n),{recursive:!0});let _=JC(h,a,f);t.claimSent=!0;let b=await We(()=>oe(`/cli/jobs/batches/${n}/claim`,{session:r,batchKey:h.key,json:{treeHash:e.code.treeHash}}));h=t.state=St(n,S=>{S.claimed=!0,S.cursor=b.cursor,S.code=b.code,S.warm=g,S.keptScripts=_.scripts.map(v=>`${Se}/${v.name}`),S.jobMinutes=b.limits.jobMinutes,S.setupMinutes=b.limits.batchSetupMinutes,S.targets=Object.fromEntries(b.jobs.flatMap(({job:v})=>v.scenario.target?.address?[[v.id,v.scenario.target.address]]:[]))}),ws(Ot(n));let x=new Set(b.jobs.map(({job:S})=>S.id));for(let S of Q().filter(v=>v.batchId!==n&&v.jobs.some($=>x.has($.jobId))))St(S.batchId,v=>{v.jobs=v.jobs.filter($=>!x.has($.jobId))});vt(r,S=>(S.runs[e.runId]??={checkout:o},S)),zC(b,h,a,await wg(f),g,C,_,V(P(ce(e.runId),lr)))}async function HC(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||(Fn(le(n),{recursive:!0,force:!0}),Wo(n))};if(Sl(t))throw(!o||e.claimSent)&&i(),t;if(e.claimSent&&Cl(t))throw new j("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>Ec())){a&&Fn(a,{recursive:!0,force:!0}),e.resuming||i();let u=Rc(e.receipt.bytes,!!e.state&&e.copied,c?.bytes??null);throw u&&await _l(n,r,u,e.resuming),new j("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 Ho(l)}if(t instanceof L&&Tt(t)&&t.status<500)throw o?new j("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 Sl(u)?(s||i(),u):s?new j("internal_error",rn,`Hand the batch back once Canary can be reached: canary jobs finish ${n} --give-back`):o?new j("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 j("internal_error",rn,`Run canary jobs take ${n} again.`))}throw i(!0),new j("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 _l(e,t,n,r){if(r)throw new j("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(Q().some(i=>i.sessionId===t&&!i.left))throw new j("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 We(()=>oe(`/cli/jobs/batches/${e}/decline`,{session:t,json:s}).then(()=>!0)).catch(()=>!1)?new j("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 j("not_enough_disk",hs(n),"Tell the user how much space the checks need. Take the batch again once they have freed some.")}var Se="canary-scripts",UC=new RegExp(`${Se}/([\\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(`
799
- `).find(r=>n.test(r)&&!/--label\b|CANARY_DOCKER_LABEL/.test(r))}function qC(e,t){let n=e.map(r=>r.name).filter(r=>om(Pt(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 BC(e){let t=P(de(e),Se),n=jf(e.repoFolder);return[...new Set(Lp(e.batchId).flatMap(s=>[...s.matchAll(UC)].map(o=>o[1])).filter(s=>!s.split("/").includes("..")))].filter(s=>Ae(P(t,s))&&!(Ae(P(n,s))&&Pt(P(n,s)).equals(Pt(P(t,s)))))}var Cr="canary-run.env",WC=/^[\w.-]+(\/[\w.-]+)*$/;function JC(e,t,n){let r=P(n,Se);Fn(r,{recursive:!0,force:!0}),Dn(r,{recursive:!0});let s=P(r,Cr);Es(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=${Sr(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(`
800
- `)),yC(P(n,".git","info","exclude"),`/${Se}/${Cr}
801
- `);let o=V(P(t.scripts,pi))??{},i=[];for(let[a,c]of Object.entries(o))!WC.test(a)||a.split("/").includes("..")||Ae(P(r,a))||!Ae(P(t.scripts,a))||(Dn(pt(P(r,a)),{recursive:!0}),bC(P(t.scripts,a),P(r,a)),i.push({name:a,...c}));return{values:s,scripts:i}}function GC(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 VC(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 KC(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 YC(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 zC(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(I(`You hold batch ${c} (run ${e.runId}) as ${Il(c)}: ${e.batch.environment}.`),I(`Copy of the code the checks were planned on: ${de(t)}. Work only there; it is outside the user's checkout.`),I(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."),I(`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"}.${GC(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.`),I(`Ports for this batch: ${t.ports[0]}-${t.ports[1]}. Use only these for anything you start.`),I(`Scratch files and folders, and the data folders of services you start, go in ${dr(c)}: it is removed with the batch.`),o?.use){I(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&&I(`Every value in them that pointed at this machine now names ${sl}, 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&&I(`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&&I(`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.`),I(`Read first: ${n.canaryMd}. Test secrets: ${n.secrets} (canary.md names them).`);let u=a?Lf(a,n.canaryMd):[];u.length&&I(`Added to the user's part of canary.md since this run began; an answer among these was given during this run:
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 U1(e,t){let n=e.map(r=>r.name).filter(r=>om(Pt(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=_f(e.repoFolder);return[...new Set(Lp(e.batchId).flatMap(s=>[...s.matchAll(B1)].map(o=>o[1])).filter(s=>!s.split("/").includes("..")))].filter(s=>Te(P(t,s))&&!(Te(P(n,s))&&Pt(P(n,s)).equals(Pt(P(t,s)))))}var Cr="canary-run.env",q1=/^[\w.-]+(\/[\w.-]+)*$/;function G1(e,t,n){let r=P(n,xe);Dn(r,{recursive:!0,force:!0}),Fn(r,{recursive:!0});let s=P(r,Cr);Os(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(`
1840
+ `)),y1(P(n,".git","info","exclude"),`/${xe}/${Cr}
1841
+ `);let o=Y(P(t.scripts,pi))??{},i=[];for(let[a,c]of Object.entries(o))!q1.test(a)||a.split("/").includes("..")||Te(P(r,a))||!Te(P(t.scripts,a))||(Fn(pt(P(r,a)),{recursive:!0}),b1(P(t.scripts,a),P(r,a)),i.push({name:a,...c}));return{values:s,scripts:i}}function J1(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 Y1(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 V1(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 K1(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 z1(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 ${Rl(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"}.${J1(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 ${sl}, 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?Lf(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:
802
1842
  ${u.map(h=>` ${h}`).join(`
803
- `)}`),I(`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.`),I(i.scripts.length?`Setup scripts earlier checks of this repository kept are in ${P(de(t),Se)}: ${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.${qC(i.scripts,P(de(t),Se))}`:"No setup script has been kept for this repository yet: yours will be the first."),I(`When a setup script of yours has run clean, keep it for the checks after you: canary jobs keep ${c} ${Se}/<file> --what "<what it sets up>"`),I(`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.`),I(`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()&&I(`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.`),I(`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.`),I(`Keep your listener running as a background command, and start it again each time it returns: canary jobs listen ${c}`),I(`Evidence for a job goes in ${P(le(c),"packs","<job>")}/pack.json; the format: canary jobs schema`),I(""),I("Jobs, one at a time, in this order:"),e.jobs.forEach(({job:h,brief:p,state:f,earlierFiles:g,earlier:m},C)=>{I(`${C+1}. Job ${h.id}: ${h.scenario.title} [${f}]`),I(` What must hold: ${h.scenario.assertion}`);for(let _ of KC(h.scenario.target))I(` ${_}`);h.scenario.target&&I(` ${YC(h.scenario.target)}`),h.scenario.claim&&I(` Claim, where the wrong outcome is the failure: ${Object.entries(h.scenario.claim).filter(([,_])=>_).map(([_,b])=>`${_}: ${b}`).join("; ")}`),I(` How to prove it (${p.method}): ${p.plan}`),I(` Data to set up: ${p.dataSetup}`),I(` Must run for real: ${p.reasons.dependsOn.join("; ")}`),p.reasons.faked.length&&I(` May be faked, only to set up or observe: ${p.reasons.faked.map(_=>`${_.part} (${_.why})`).join("; ")}`),p.reasons.limits.length&&I(` Known limits: ${p.reasons.limits.map(_=>`${_.part} (${_.why})`).join("; ")}`),p.questions.length&&I(` Expected questions: ${p.questions.join(" | ")}`),p.permissions.length&&I(` Access to ask for: ${p.permissions.join(" | ")}`),h.scenario.relatedFiles.length&&I(` Related files: ${h.scenario.relatedFiles.join(", ")}`),h.recheckOf?(I(` Re-check of an earlier result. Last time, ${VC(h.recheckOf.verdict)}.${h.recheckOf.reasoning?` Earlier reasoning: ${h.recheckOf.reasoning}`:""}`),h.recheckOf.reproduction&&I(` Earlier reproduction: ${h.recheckOf.reproduction.steps.join(" Then ")} Look for: ${h.recheckOf.reproduction.observe}`),g.length&&I(` Earlier files (fetch each into the copy with canary jobs earlier ${h.id} <path>): ${g.join(", ")}`)):m&&(I(` 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&&I(` Its scripts (fetch each into the copy with canary jobs earlier ${h.id} <path>, and reuse what still fits): ${g.join(", ")}`))})}function QC(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} ${Se}/<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 XC(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(()=>{}),I(s.first?`Canary: ${am(r)}`:`Canary: more on ${r.id} from the coding agent: ${s.texts.join(" | ")}`),n=!0)}return n}async function ZC(e){let t=_e(),n=en(e),r=Date.now(),s=null,o=!1;for(setInterval(()=>void XC(n,t).then(a=>{a&&process.exit(0)}).catch(()=>{}),2e3).unref();;){if(n.owner&&!sr(n.owner))return I("Canary: the Claude Code session ended; this listener stops.");if(Date.now()-r>CC){if(s)return I("Canary: can't reach Canary right now; run the listener again.");let c=gr(e)?[]:BC(n);return I(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} ${Se}/<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&&I("Canary: reachable again."),s=null,o=!1}catch(c){if(Yo(c))return St(e,l=>{l.ended=!0}),I(`Canary: stop working on batch ${e}: ${c.message} Clean up what you started and run: canary jobs finish ${e}`);if(!Tt(c))throw c;s??=Date.now(),!o&&Date.now()-s>Xg&&(o=!0,I("Canary: can't reach Canary right now; still trying.")),await an(vr);continue}n=St(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)I(QC(c,n));if(a.events.length>0)return}}var Ol=(e,t)=>{if(e.stopped[t])throw new j("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 j("usage","--proof takes the request's number, as the listener printed it.");return Number(e)};async function e_(e,t){let n=hr(e);Ol(n,e),await dm(n);let r=im(t.proof);await We(()=>oe(`/cli/jobs/${e}/start`,{session:_e(),batchKey:n.key,json:{proofRequestId:r}}),xr).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);Yc(n.batchId,"start",e,r),s&&!n.kept?.length&&I(`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} ${Se}/<file> --what "<what it sets up>"`),I(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 t_(e,t){let n=_e(),r,s;if(t.wait){let a=Q().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 j("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 j("usage","Ask about one job (--job <job>) or about setting up (--setup <batch>), with the question text.");if(e.length>Kg)throw new j("question_too_long",`A question is one need, in a line or two: this one is ${e.length} characters, and ${Kg} 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 j("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=()=>We(()=>oe(`/cli/jobs/batches/${a.batchId}/pause`,{session:n,batchKey:a.key,json:{jobId:t.job??null}}),xr);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=Bg(s.checkout,{runId:s.runId,batchId:s.batchId,jobId:t.job??null,verifier:Il(s.batchId),text:e})}catch(l){throw await oe(`/cli/jobs/batches/${s.batchId}/resume`,{session:n,batchKey:s.key,method:"POST"}).catch(()=>{}),l}I(`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()+xC;for(;;){let i=Q().find(c=>c.batchId===s.batchId);if(!i||i.ended)return Pn([{runId:s.runId}],s.batchId,"all"),I(`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=Gg(r.path);if(a?.status==="answered"){let c=ml(r.path).first,l=am(a),d=!0;try{c&&({resumed:d}=await We(()=>oe(`/cli/jobs/batches/${s.batchId}/resume`,{session:n,batchKey:s.key,method:"POST"})))}catch(u){if(!Yo(u))return I(`${l} Couldn't restart the clock with Canary; run canary jobs ask --wait ${r.id} to try again.`)}return I(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 I(`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 I(`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 Kg=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=>Ge(_e()).find(t=>t.runId.startsWith(e))?.runId??e;async function n_(e){let t=cm(e),{stopped:n}=await oe(`/cli/jobs/runs/${t}/stop`,{session:_e(),method:"POST"});js(Q().filter(r=>r.runId===t&&r.sessionId===_e()).map(r=>r.batchId),Ln+3e4),I(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 r_(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:_e(),method:"POST",json:{jobIds:s}});I(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 s_(e,t){let n=_e(),r=Wg(Ge(n),e);if(r.status==="expired")return I(`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";Jg(r,t,s,o),I(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 o_(e,t){let n=_e(),r=hr(e);if(r.finalSent.includes(e))throw new j("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(Ae(a)&&cn(a)!==c)throw new j("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(!Vf(r.batchId))throw new Error("the plugin's hooks saw nothing of this batch's verifier");l=Bp(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:_,answer:b,userSpoke:x})=>({id:g,jobId:m,text:C,status:_,answer:b,userSpoke:x??!1})),f=l.calls.filter(g=>g.kind==="file"&&g.ended==="ran").map(g=>g.what);d=Eg(a,s?"delta":"pack",{jobId:e,commit:r.code.commit,tree:r.code.treeHash,uncommitted:r.code.uncommitted??null,scripts:i_(de(r),r.batchId,e,s),scriptsFrom:P(de(r),Se),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:Wp(r.batchId)},s,ol(r.checkout))}catch(h){if(h instanceof j)throw h;if(Cl(h))throw new j("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?Ho(p):await fi(r,e,h,o,i)}c_(r,e,d.pack),a_(r,e,s,d.pack,l);let u={session:n,batchKey:r.key};try{let h=await We(()=>oe(`/cli/jobs/${e}/evidence`,{...u,json:d.upload}),xr);for(let p of h.missing){let f=d.bytes.get(p);await We(()=>oe(`/cli/jobs/${e}/evidence/${h.uploadId}?path=${encodeURIComponent(p)}`,{...u,method:"PUT",bytes:f,timeoutMs:IC(f.length)}),xr)}await We(()=>oe(`/cli/jobs/${e}/evidence/${h.uploadId}/complete`,{...u,method:"POST"}),xr)}catch(h){throw h instanceof L&&h.status>=500?await fi(r,e,h,o,i):h}if(r.stopped[e]&&St(r.batchId,h=>void h.finalSent.push(e)),Yc(r.batchId,"sent",e,s),Lc(r.batchId,e),I(`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);I(`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 Sl(i)?i:new j("internal_error",rn,`Run it again in a minute: ${s}`)}return o.requeued?new j("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 j("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 j("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 i_(e,t,n,r){let s=P(e,Se),o=P(ur(t,n),Se),i=r?P(ur(t,n,r),`proof-${r}-scripts`):o,a=[],c=l=>{for(let d of Ae(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>=h_)continue;if(d.isDirectory()){c(u);continue}if(!d.isFile()||_r(u).size>lm||!On.test(`${wl(i)}/${h}`))continue;let p=Pt(u);if(p.subarray(0,8e3).includes(0)||r&&Ae(P(o,h))&&Pt(P(o,h)).equals(p))continue;Dn(pt(P(i,h)),{recursive:!0}),Es(P(i,h),p);let{atime:f,mtime:g}=_r(u);vC(P(i,h),f,g),a.push(`${wl(i)}/${h}`)}};return c(s),a}function a_(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 St(e.batchId,u=>void(u.sentBack=[...u.sentBack??[],o])),new j("nothing_run",d[0],d[1])}function c_(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&&l_(o)===`${i[0].replace(/:\d+$/,"").toLowerCase()}:${a}`))throw new j("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 l_(e){try{let t=new URL(e);return`${t.hostname.toLowerCase()}:${t.port||(t.protocol==="https:"?"443":"80")}`}catch{return null}}async function u_(e,t){let n=hr(e);if(Ol(n,e),!On.test(t))throw new j("usage",`${t} isn't a path from the earlier evidence.`,"Use a path take printed under earlier files.");let r=await We(()=>cp(`/cli/jobs/${e}/earlier?path=${encodeURIComponent(t)}`,{session:_e(),batchKey:n.key})),s=cn(de(n)),o=pt(P(s,t));for(;!Ae(o);)o=pt(o);if(cn(o)!==s&&!cn(o).startsWith(s+wi))throw new j("outside_copy",`${t} leads outside the copy through a link.`);Dn(pt(P(s,t)),{recursive:!0});let i=P(s,t);Ae(i)&&(i=`${i}.earlier`);let a=kC(i,ui.O_WRONLY|ui.O_CREAT|ui.O_EXCL|ui.O_NOFOLLOW,420);try{SC(a,r)}finally{wC(a)}I(`Wrote ${t} from the earlier evidence to ${i}.`)}async function d_(e,t){let n=en(e),r=Number(t.pid),s=Number.isInteger(r)&&r>1?It(r):null;if(s===null)throw new j("no_such_process",`No running process ${t.pid}.`);if(!Zc(r,n))throw new j("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.");St(e,o=>void o.processes.push({pid:r,startedAt:s,what:t.what??"background process"})),I(`Recorded process ${r}; finish stops it with the batch.`)}var pi="kept.json",lm=256*1024,h_=80;async function f_(e,t,n){let r=en(e),s=cn(de(r)),o=Uo(r.checkout),i=ol(r.checkout),a=[];for(let l of t){let d=Ie($l(s,l));if(!$r(d,[P(s,Se)])||!_r(d).isFile()||_r(d).size>lm||wl(d)===Cr)throw new j("not_a_setup_script",`${l} isn't a script in ${P(s,Se)}.`,"Keep the setup script, and any file it runs, from that folder.");let u=Pt(d,"utf8"),h=[...[r.batchId,Sr(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 j("holds_this_batch",`${l} holds ${h.join(", ")}, so the next verifier would have to rewrite it.`,`Read those from ${Se}/${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 j("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 ${Se}/${Cr}), run it clean once more, and keep it again.`);a.push({name:Qg(P(s,Se),d).split(wi).join("/"),text:u})}let c=V(P(o.scripts,pi))??{};for(let{name:l,text:d}of a)Dn(pt(P(o.scripts,l)),{recursive:!0,mode:448}),Es(P(o.scripts,l),d,{mode:384}),c[l]={what:n.what,keptAt:new Date().toISOString()};Pe(P(o.scripts,pi),c),St(e,l=>void(l.kept=[...new Set([...l.kept??[],...a.map(d=>d.name)])])),I(`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 p_(e){St(e,t=>void(t.readyAt??=new Date().toISOString())),I("Noted: the app is up. The user now sees that setup is over and that you are getting the checks ready.")}async function g_(e,t){let n=hr(e);Ol(n,e);let r=Date.now()+_C;for(;!Yf(t,n.batchId,e);){if(Date.now()>=r)throw new j("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)}I(`You may write to ${t}; the lock is released when this job's evidence is sent or the batch finishes.`)}async function m_(e,t){if(!Ae(P(le(e),"state.json")))return Fn(le(e),{recursive:!0,force:!0}),I(`Nothing of batch ${e} is on this machine.`);let n=en(e),r=_e();if(n.sessionId!==r)throw new j("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===Oc(n.key)){if(!t.giveBack)throw new j("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 We(()=>oe(`/cli/jobs/batches/${e}/give-back`,{session:r,batchKey:n.key,method:"POST"}),xr).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 j("internal_error",rn,`Run it again in a minute: canary jobs finish ${e} --give-back`)})});I(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 Nn(n);I(`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)I(`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 y_(){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 I(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:O_}}));if(n==="PostToolUse"&&e.tool_name==="AskUserQuestion"&&typeof e.session_id=="string"){let v=ot(e.session_id).asking;if(v&&Ae(v)){let $=_p(e,v);$.commands!==null&&wp(v,$.commands),$.envFiles&&bp(v,$.envFiles.files,$.envFiles.answer)}return await mi(e.session_id,Os,P_(e))}if(n==="UserPromptSubmit"&&typeof e.session_id=="string")return typeof e.prompt=="string"&&b_.test(e.prompt)?void 0:await mi(e.session_id,$C,typeof e.prompt=="string"?[e.prompt]:[]);let s=e.agent_type==="canary:verifier"&&typeof t=="string"?t:null,o=gC("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"?__(e):null;if(a===!0)return I(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),I(JSON.stringify({hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"deny",message:E_(a.reason)}}}))}if(!s)return;if(n==="PermissionRequest")return await j_(s,o,a?a.reason:"");if(n==="PermissionDenied")return w_(s,i,e);await N_(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",v_(e)),u!==null?Qc(v,i.call,S_(e)):typeof d=="string"&&n==="PostToolUse"&&Fp(v,i.call,Ie(d));return}if(n==="PostToolBatch")return x_(s,e);if(n!=="PreToolUse")return;let p=(v,$,O)=>{v&&pr(v,i,"sent_back",O),I(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$}}))};if(typeof d=="string"){let v=it(s);v&&si(v,i,"file",Ie(d));let $=I_(s,e);$&&p(v,$,$.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&&Gf(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?Q().find(v=>v.batchId===g):void 0,C=m?.checkout??(typeof e.cwd=="string"?e.cwd:null),_=C&&Tn(C)?.commands==="run"?null:Fg(u),b=m?C_(u,ki(m,m.checkout),m.checkout):null,x=m?R_(u,m,typeof e.cwd=="string"?e.cwd:m.checkout):null,S=T_(s,u);S?p(g,S,"the job moved to another batch"):k_.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"):x?p(g,x,"it writes a file outside the verifier's own folders"):_&&p(g,Hg(_),_)}catch{}}function w_(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 b_=/^\s*(?:<task-notification>|<agent-message\b|Another Claude session sent a message)/,gi=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),k_=/\bcanary\s+jobs\s+(?:answer|approvals|stop|retry)\b/;function v_(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 S_(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 x_(e,t){let n=it(e),r=Array.isArray(t.tool_calls)?t.tool_calls:[];if(!n||r.length===0)return;let s=Up(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?Dp(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 C_(e,t,n){let r=Be(n),s=r?[Qe(r).dir]:[];for(let o of new Set([W(),Ie(W()),P(pt(W()),"approvals"),Ie(P(pt(W()),"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(Ie(a))&&!$r(Ie(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 __(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"?Ie(s):null;if(typeof e.agent_id!="string"){let d=typeof e.cwd=="string"?Ir(e.cwd):null,u=d&&Be(d);if(!d||!u)return!1;let h=Qe(u),p=[h.dir,P(W(),"runs")];return r!==null?xp(r,f=>$r(Ie(f.startsWith("~/")?P(yl(),f.slice(2)):$l(e.cwd,f)),p)):o===null?!1:$_.has(n)?$r(o,p):gi.has(n)&&[h.canaryMd,h.secrets].map(Ie).includes(o)&&Tn(d)?.commands==="run"}if(e.agent_type!=="canary:verifier")return!1;let i=it(e.agent_id),a=i?Q().find(d=>d.batchId===i):void 0,c=a?.checkout??(typeof e.cwd=="string"?e.cwd:null);if(!c||Tn(c)?.commands!=="run")return!1;let l=ki(a,c);if(r!==null){let d=u=>{try{return _r(u).size<=262144?Pt(u,"utf8"):null}catch{return null}};return li(r,{roots:l.folders.flatMap(u=>[...new Set([u,Ie(u)])]),cwd:c,home:yl(),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 $_=new Set(["Read","Grep","Glob"]);function Ie(e){let t=$l(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 $r=(e,t)=>t.map(Ie).some(n=>e===n||e.startsWith(n+wi));function ki(e,t){let n=Be(t),r=n&&Qe(n),s=e?[de(e),le(e.batchId)]:[],o=e?Ie(P(le(e.batchId),"state.json")):null;return{folders:s,holds:i=>$r(i,s)&&i!==o||r!==null&&i===Ie(r.canaryMd)}}function I_(e,t){let n=t.tool_input,r=n?.file_path??n?.notebook_path,s=it(e),o=s?Q().find(i=>i.batchId===s):void 0;return!o||typeof r!="string"?null:ki(o,o.checkout).holds(Ie(r))?A_(o,Ie(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 A_(e,t,n){let r=Be(e.checkout);if(!r||t!==Ie(Qe(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 R_(e,t,n){let r=ki(t,t.checkout).folders,s=jg(e,n).find(o=>!o.startsWith("/dev/")&&!$r(Ie(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 E_=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.`,O_="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 T_(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=Q(),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 j_(e,t,n=""){let r=it(e),s=r?Q().find(o=>o.batchId===r&&o.claimed):void 0;if(s){Kf(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:Os}),bs(s.batchId)}catch(o){o instanceof L&&!Tt(o)?(ws(Go(e).filter(i=>i.call===t).map(i=>i.name)),bs(s.batchId)):Pc(s.batchId,{call:"pause"})}}}async function N_(e,t,n,r){let s=t==="PostToolUse"||t==="PostToolUseFailure";if(!s&&t!=="PostToolBatch"&&t!=="SubagentStop")return;let o=Go(e).filter(a=>!s||a.call===n),i=Q().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=Q().find(d=>d.batchId===a);!l||Go(e).some(d=>d.batchId===a)||await hm(l,s?r:0).catch(()=>{})}}function P_(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=Os,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){Ot(e.batchId).length&&await mi(e.sessionId),await hm(e),ws(Ot(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:Os})}catch(n){if(!(n instanceof L)||Tt(n))throw Pc(e.batchId,{call:"resume",since:Date.now()-t}),n}bs(e.batchId)}async function M_(e,t){let n=Ot(e.batchId).length>0,r={session:e.sessionId,batchKey:e.key,timeoutMs:Os};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)||Tt(s))return}bs(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 L_(e,t){await an(Number(t.after)||0);let n=_e();for(let r of Q().filter(s=>e.includes(s.batchId)&&s.sessionId===n&&!s.left))await Nn(r).catch(()=>{})}async function D_(e){await F_(e).catch(()=>{})}async function F_(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 Fc(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 We(()=>oe("/cli/jobs/session-end",{session:t,method:"POST",timeoutMs:1e4})).catch(()=>{});for(let n of Q().filter(r=>r.sessionId===t))await Nn(n).catch(()=>{});for(let{runId:n}of Ge(t))Fn(P(ce(n),"source.bundle"),{force:!0});Fc(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(jC)),t.command("list").description("this session's checks, batches and open questions").action(ye(LC)),t.command("take <batch>").description("take a batch: build its copy and claim it").action(ye(DC)),t.command("listen <batch>").description("the verifier's listener: returns after the next news, or about 9 minutes").action(ye(ZC,{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(e_,{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(t_,{urgent:!0})),t.command("stop <run>").description("stop a run's checks that haven't finished, at the user's word").action(ye(n_)),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(r_)),t.command("answer <question> <text>").description("answer a verifier's question").action(ye(s_,{local:!0})),t.command("submit <job>").option("--proof <n>","send the answer to request <n>").description("send a job's evidence").action(ye(o_,{urgent:!0})),t.command("earlier <job> <path>").description("fetch a file of the earlier evidence for a re-check").action(ye(u_)),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(d_,{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(f_,{local:!0})),t.command("ready <batch>").description("say the app is up, so the user sees that setup is over").action(ye(p_,{local:!0})),t.command("lock <job> <target>").description("write to a target marked safe for writes, one verifier at a time").action(ye(g_,{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(m_)),t.command("session-end").option("--end <session>").description("called by the plugin's session-end hook").action(ye(D_,{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(L_,{sweep:!1,local:!0})),t.command("hook").description("called by the plugin's hooks on a verifier's tool calls").action(y_),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 j("usage","The only action is reset.");kp(Ir()),I("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()=>I(Og),{sweep:!1}))}w();Z();ro();nt();Wt();import{appendFileSync as f$,existsSync as p$}from"node:fs";import{join as Rm}from"node:path";w();ja();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,H_=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(H_.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}}):""}_o();w();fe();var Hn=(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 Hn("mode_off");if(!e.trigger)return Hn("not_a_trigger");if(!e.login)return null;if(!e.login.ok)return Hn(e.login.cause);if(e.chat===void 0)return null;if(e.chat===null)return Hn("no_chat");if(!e.lookup)return null;if(!e.lookup.ok)return Hn(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"?Hn("clear"):t.state==="remind"?{decision:"deny",cause:t.state,message:t.agent}:e.skip===void 0?null:e.skip?Hn("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 U_=new Set(["clear","none","running","open","remind"]);async function bm(e,t,n,r={}){let s=AbortSignal.timeout(r.timeoutMs??An);try{let o=new URLSearchParams({workspaceId:e.workspaceId,chat:t,...n?{raised:n}:{}}),i=await U(`/api/v1/cli/hold?${o.toString()}`,{token:e.token,baseUrl:e.apiUrl,signal:Sc(s,r.signal)});return!i||typeof i!="object"||!U_.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??An)/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();Z();import{randomUUID as q_}from"node:crypto";import{mkdirSync as B_,readFileSync as W_,renameSync as J_,rmSync as G_,writeFileSync as V_}from"node:fs";import{dirname as K_,join as Y_}from"node:path";var Tl=()=>Y_(Y(),"hold","raised.json"),z_=720*60*60*1e3,Q_=100,X_=8e3;function km(e){let t;try{t=JSON.parse(W_(Tl(),"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<z_&&(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>X_;)n.shift();return n.length>0?n.join(","):void 0}function Sm(e,t,n=Date.now()){try{Pr(`${Tl()}.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(-Q_),at:new Date(n).toISOString()};let o=Tl(),i=`${o}.${q_()}.tmp`;B_(K_(o),{recursive:!0,mode:448});try{V_(i,JSON.stringify({version:1,chats:r},null,2)+`
804
- `,{flag:"wx",mode:384}),J_(i,o)}catch(a){throw G_(i,{force:!0}),a}})}catch{}}oc();w();import{homedir as Z_}from"node:os";import{basename as e$,isAbsolute as t$,resolve as n$}from"node:path";var r$=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),s$=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,xm=e=>e.replace(/\\(.)/g,(t,n)=>n==="n"?`
805
- `:n==="t"?" ":n);function Im(e,t){for(let n of e)for(let r of n.matchAll(s$)){let s=r[4]!==void 0?[...r[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(i=>xm(i[1]??i[2]??"")).join(" "):xm(r[1]??r[2]??r[3]??""),o=Pl(s,t);if(o)return o}return null}function Am(e,t){let n=!e.includes("__");if(!n&&!e.startsWith("mcp__"))return null;let r=r$.get(n?e:e.slice(e.lastIndexOf("__")+2));return r?{action:r,via:"mcp",dir:t}:null}function o$(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=xi(e,n+r,r===2?")":"`");t.push(s.tokens),n=s.end-1}return t}var Si=!1;function xi(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=xi(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==="\\"&&!Si){g===`
806
- `||(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]==="\\"&&!Si&&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]!==`
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}),GC(i,o)}catch(a){throw JC(i,{force:!0}),a}})}catch{}}oc();w();import{homedir as QC}from"node:os";import{basename as eA,isAbsolute as tA,resolve as nA}from"node:path";var rA=new Map([["create_pull_request","pr_create"],["push_files","push"],["create_or_update_file","push"]]),sA=/exec_command\s*\(\s*\{(?:[^{}]|\{[^{}]*\})*?\bcmd\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|`((?:[^`\\]|\\.)*)`|\[([^\]]*)\])/g,Sm=e=>e.replace(/\\(.)/g,(t,n)=>n==="n"?`
1845
+ `:n==="t"?" ":n);function Rm(e,t){for(let n of e)for(let r of n.matchAll(sA)){let s=r[4]!==void 0?[...r[4].matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g)].map(i=>Sm(i[1]??i[2]??"")).join(" "):Sm(r[1]??r[2]??r[3]??""),o=Pl(s,t);if(o)return o}return null}function Tm(e,t){let n=!e.includes("__");if(!n&&!e.startsWith("mcp__"))return null;let r=rA.get(n?e:e.slice(e.lastIndexOf("__")+2));return r?{action:r,via:"mcp",dir:t}:null}function oA(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
+ `||(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]!==`
807
1847
  `;)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===`
808
1848
  `){h(`
809
1849
  `),l++;for(let m of s.splice(0))for(;;){let C=e.indexOf(`
810
- `,l),_=e.slice(l,C<0?void 0:C);if(l=C<0?e.length:C+1,(m.stripTabs?_.replace(/^\t+/,""):_)===m.end||C<0)break;if(!m.literal)for(let b of o$(_))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 _=l;for(;l<e.length&&!/[\s;&|()<>`]/.test(e[l]);)l++;if(m&&!C){let b=e.slice(_,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 i$=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),a$=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),Cm=e=>/^(\/dev\/|\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\$TMPDIR|\$\{TMPDIR)/.test(e),un=!1,c$=new Set(["if","then","else","elif","fi","do","done","while","until","for","!","{","}","time"]),_m=new Set(["command","exec","builtin","nohup","noglob","nice","sudo","env"]),l$=new Set(["sh","bash","zsh","dash","ksh"]),$m=6,u$=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("~/"))?Z_()+e.word.slice(1):e.word;return e.bare&&n.startsWith("~")?null:t$(n)?n:n$(t,n)}function d$(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(u$.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 h$(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 Nl(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&&(c$.has(m.word)||_m.has(m.word)||!!C&&_m.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=e$(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=d$(f,r);if(m)return g("push",m.dir);let C=f.find(b=>!b.word.startsWith("-"))?.word,_=(C==="checkout"||C==="switch")&&f.some(b=>/^-(b|B|c|C|-orphan)$/.test(b.word));return C&&a$.has(C)&&!_&&(un=!0),l(null)}if(p==="gh")return h$(f)?g("pr_create",r):l(null);if(p==="tee"?f.some(m=>!m.word.startsWith("-")&&!Cm(m.word))&&(un=!0):(i$.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<$m&&(l$.has(p)||p==="eval")){let m=p==="eval"?0:f.findIndex(_=>/^-[a-zA-Z]*c[a-zA-Z]*$/.test(_.word))+1,C=p==="eval"?f.map(_=>_.word).join(" "):m>0?f[m]?.word:void 0;if(C)return l(Nl(xi(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||!Cm(a.write);continue}if("sub"in a){let l=n<$m?Nl(a.sub,r,n+1):null;if(l)return l;continue}let c=i();if(c)return c}return i()}function Pl(e,t,n={}){if(!/\bpush\b/.test(e)&&!/\bpr\b/.test(e))return null;Si=n.shell==="powershell",un=!1;try{return Nl(xi(e,0,null).tokens,t,0)}finally{Si=!1,un=!1}}var g$=8e3,m$=64*1024*1024;async function y$(e,t={}){let n=e.kind==="shell"?Pl(e.command,e.cwd,{shell:e.shell}):e.kind==="script"?Im(e.texts,e.cwd):Am(e.toolName,e.cwd);if(!n)return e.chat&&e.kind!=="tool"&&ad(e.kind==="shell"?[e.command]:e.texts)&&ld(e.cwd,e.chat),vi({mode:"on",trigger:null});let r={mode:wn(),trigger:n},s,o=()=>Math.max(250,Math.min(An,t.deadline?t.deadline-Date.now()-500:An)),i=[async()=>{tt({cwd:e.cwd,agent:!0});let l=ne(),d=K().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 bm(s,e.chat,vm(e.chat),{timeoutMs:o(),signal:t.signal})},async()=>{r.skip=pf(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&&Sm(e.chat,c),a}async function w$(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>m$)throw new Error("event too large");t.push(s)}return JSON.parse(Buffer.concat(t).toString("utf8").replace(/^\uFEFF/,""))}var b$={claude:"claude-code",codex:"codex",cursor:"cursor"};async function k$(e,t){tt({harness:b$[e]});let n=t.ceilingMs??g$;pu(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 w$(t.stdin);try{p$(Rm(Y(),"hook-debug"))&&f$(Rm(Y(),"hook-events.log"),`${new Date().toISOString()} ${e} ${JSON.stringify(d)}
811
- `)}catch{}let u=mm(e,d);return u?y$(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=ym(e,c);return l&&await t.write(l),c.cause!=="not_a_trigger"&&t.note(`canary hook: ${c.decision} (${c.cause})`),await uh(c,i.target),c}function Em(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(pm.includes(t)){let n=Number(process.env.CANARY_HOOK_CEILING_MS)>0?Number(process.env.CANARY_HOOK_CEILING_MS):void 0;await k$(t,{stdin:process.stdin,ceilingMs:n,note:r=>process.stderr.write(r+`
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 oA(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 iA=new Set(["patch","mv","cp","rm","rsync","truncate","install"]),aA=new Set(["apply","pull","merge","rebase","cherry-pick","checkout","restore","switch","stash","reset","revert","am","mv","rm","clean"]),Cm=e=>/^(\/dev\/|\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\$TMPDIR|\$\{TMPDIR)/.test(e),un=!1,cA=new Set(["if","then","else","elif","fi","do","done","while","until","for","!","{","}","time"]),Am=new Set(["command","exec","builtin","nohup","noglob","nice","sudo","env"]),lA=new Set(["sh","bash","zsh","dash","ksh"]),Im=6,uA=new Set(["-c","--exec-path","--namespace","--super-prefix","--config-env","--attr-source"]);function _l(e,t){if(t===null||/[$`*?[]/.test(e.word))return null;let n=e.bare&&(e.word==="~"||e.word.startsWith("~/"))?QC()+e.word.slice(1):e.word;return e.bare&&n.startsWith("~")?null:tA(n)?n:nA(t,n)}function dA(e,t){let n=t,r=0;for(;r<e.length;r++){let o=e[r].word;if(o==="-C"){n=e[r+1]?_l(e[r+1],n):null,r++;continue}if(o.startsWith("-C")&&o.length>2){n=_l({...e[r],word:o.slice(2)},n);continue}if(/^--(git-dir|work-tree)(=|$)/.test(o)){n=null,o.includes("=")||r++;continue}if(uA.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 hA(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 jl(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&&(cA.has(m.word)||Am.has(m.word)||!!C&&Am.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=eA(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("-")?_l(f[0],r):null,l(null);let g=(m,C)=>({action:m,via:"shell",dir:C,...un?{editsFirst:!0}:{}});if(p==="git"){let m=dA(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&&aA.has(C)&&!A&&(un=!0),l(null)}if(p==="gh")return hA(f)?g("pr_create",r):l(null);if(p==="tee"?f.some(m=>!m.word.startsWith("-")&&!Cm(m.word))&&(un=!0):(iA.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<Im&&(lA.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(jl(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||!Cm(a.write);continue}if("sub"in a){let l=n<Im?jl(a.sub,r,n+1):null;if(l)return l;continue}let c=i();if(c)return c}return i()}function Pl(e,t,n={}){if(!/\bpush\b/.test(e)&&!/\bpr\b/.test(e))return null;xi=n.shell==="powershell",un=!1;try{return jl(Si(e,0,null).tokens,t,0)}finally{xi=!1,un=!1}}var gA=8e3,mA=64*1024*1024;async function yA(e,t={}){let n=e.kind==="shell"?Pl(e.command,e.cwd,{shell:e.shell}):e.kind==="script"?Rm(e.texts,e.cwd):Tm(e.toolName,e.cwd);if(!n)return e.chat&&e.kind!=="tool"&&ad(e.kind==="shell"?[e.command]:e.texts)&&ld(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()=>{tt({cwd:e.cwd,agent:!0});let l=ne(),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 bm(s,e.chat,vm(e.chat),{timeoutMs:o(),signal:t.signal})},async()=>{r.skip=pf(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&&xm(e.chat,c),a}async function wA(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>mA)throw new Error("event too large");t.push(s)}return JSON.parse(Buffer.concat(t).toString("utf8").replace(/^\uFEFF/,""))}var bA={claude:"claude-code",codex:"codex",cursor:"cursor"};async function kA(e,t){tt({harness:bA[e]});let n=t.ceilingMs??gA;pu(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 wA(t.stdin);try{pA(Em(K(),"hook-debug"))&&fA(Em(K(),"hook-events.log"),`${new Date().toISOString()} ${e} ${JSON.stringify(d)}
1851
+ `)}catch{}let u=mm(e,d);return u?yA(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=ym(e,c);return l&&await t.write(l),c.cause!=="not_a_trigger"&&t.note(`canary hook: ${c.decision} (${c.cause})`),await uh(c,i.target),c}function Om(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(pm.includes(t)){let n=Number(process.env.CANARY_HOOK_CEILING_MS)>0?Number(process.env.CANARY_HOOK_CEILING_MS):void 0;await kA(t,{stdin:process.stdin,ceilingMs:n,note:r=>process.stderr.write(r+`
812
1852
  `),write:r=>new Promise(s=>process.stdout.write(r+`
813
- `,()=>s()))})}process.exit(0)})}w();fe();Z();function Om(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=ne();if(r)try{await U("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}bu();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();fe();Z();nt();import{createHash as $$}from"node:crypto";import{mkdirSync as I$,readdirSync as A$}from"node:fs";import{dirname as R$,join as qm}from"node:path";w();import{copyFileSync as Tm,existsSync as Ps,mkdirSync as Pm,renameSync as v$,rmSync as Ml,writeFileSync as jm}from"node:fs";import{dirname as S$,join as qe}from"node:path";Wt();var Ci=()=>({runs:{},told:{},said:[],endedAt:{}}),x$=4*6e4;function Nm(e){let t=V(qe(En(e.requestId),"request.json"));return e.session!==null&&t?.chat===e.session}function _i(e){let t=V(qe(En(e),"request.json"));return Ir(typeof t?.checkout=="string"&&Ps(t.checkout)?t.checkout:process.cwd())}function C$(e,t,n){let r=ce(t);Pm(r,{recursive:!0,mode:448});let s=En(e),o=qe(r,"source.bundle");if(!Ps(o)&&Ps(qe(s,"source.bundle")))try{v$(qe(s,"source.bundle"),o)}catch{Tm(qe(s,"source.bundle"),o),Ml(qe(s,"source.bundle"),{force:!0})}for(let a of["source.json",lr])!Ps(qe(r,a))&&Ps(qe(s,a))&&Tm(qe(s,a),qe(r,a));let i=_i(e);vt(n,a=>(a.owner=cr()??a.owner??null,a.runs[t]??={checkout:i},a))}var Ns=e=>typeof e=="string"&&e?e:null,_$=e=>{try{return st(e,"job"),!0}catch{return!1}};function Mm(e,t,n){let r=Ns(e.data.checksRun),s=n.session;if(e.type==="ended"&&s&&Nm(n)&&Ml(qe(En(n.requestId),"source.bundle"),{force:!0}),!r||!s)return[];if(!Object.hasOwn(t.runs,r)){if(e.type==="ended"||!Nm(n))return[];C$(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=>Ns(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(Rl(_i(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||!_$(i.jobId))return[];let a=qe(ce(r),"results",`${i.jobId}.json`);Pm(S$(a),{recursive:!0}),jm(a,JSON.stringify(i,null,2)+`
814
- `);let c=a.replace(/\.json$/,".md");return jm(c,El(i,r)),i.verdict==="broken"?[{type:"read_record",path:c}]:[]}case"batch_ended":{let i=Ns(e.data.batchId);if(!i)return[];t.said.includes(`ended:${i}`)||t.said.push(`ended:${i}`),tn(i);let a=Q().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=Ns(e.data.batchId);return i&&Pn([{runId:r}],i,Ns(e.data.jobId)),[]}case"ended":{let i=e.data.result?.running;return!(Array.isArray(i)&&i.length>0)&&!Ts(r)&&Ml(qe(ce(r),"source.bundle"),{force:!0}),[]}default:return[]}}var Lm=e=>e.asks.length>0||e.approvals.length>0||e.changed||(e.setups?.length??0)>0;function Dm(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)qo(l);let i=[],a=l=>e.said.includes(`ended:${l}`);for(let l of ct(s.map(d=>({runId:d})))){if(l.status!=="open"||a(l.batchId))continue;let d=e.told[l.path];d!==void 0&&n-d<x$||(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 Ot(l)){let u=ks(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}`)||Q().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=_i(t.requestId);for(let f of u)e.said.push(`start:${f}`),gs(Zt(p))?i.push({type:"start_verifier",batchId:f}):ms(f,o,p)}for(let l of ys(o))!c.includes(l.batchId)||!gs(Zt(l.checkout))||ps(l.checkout)||(tn(l.batchId),i.push({type:"start_verifier",batchId:l.batchId}));return{tell:r,do:i}}async function Fm(e,t){if(e.said.includes("changed")||Object.keys(e.runs).length===0)return!1;let n=V(qe(En(t.requestId),"source.json"))?.treeHash;if(typeof n!="string")return!1;try{if((await Xr(_i(t.requestId))).treeHash===n)return!1}catch{return!1}return!0}Gt();var E$=25,Dl=45e3,O$=9*6e4,T$=9e4,j$=5,N$=200,Ll=(e,t)=>qm(Y(),"requests",t===null?`${e}.json`:`${e}.${$$("sha256").update(t).digest("hex").slice(0,16)}.json`);function Hm(e,t){let n=V(Ll(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 Um(e,t,n){I$(R$(Ll(e,t)),{recursive:!0,mode:448}),Pe(Ll(e,t),n)}function Bm(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(`
815
- `):"";return{result:t.data.result??null,more:Jt(n),do:t.do}}var Fl=()=>yn();function Wm(e,t,n,r){let s=Fl();return U(`/api/v1/cli/requests/${e}/events?after=${n}&wait=${r}`,{token:t,signal:AbortSignal.timeout(Dl),...s?{headers:{"x-canary-session":s}}:{}}).then(o=>({...o,events:o.events.map(ss)}))}function P$(e,t,n){return U(`/api/v1/cli/requests/${e}/here`,{method:"POST",token:t,body:n,signal:AbortSignal.timeout(Dl)})}var M$=new Set(["start_verifier","stop_verifier","keep_late_answer"]),L$={read:Wm,pause:e=>new Promise(t=>setTimeout(t,e)),onEvent:Mm,localNews:Dm,changedFiles:Fm,here:P$,session:Fl};async function D$(e,t,n,r,s=L$){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?j$:E$,Math.floor(u/1e3)))),i=null}catch(_){if(!be(_)||(i??=Date.now(),Date.now()-i>T$))throw _;await s.pause(2e3);continue}let f=[],g=a.cursor;for(let _ of p.events){let b=s.onEvent(_,c,l),x=W$(_.data.checksRun),S=new Set(Object.values(c.held??{}).flat()),v=(x===null||Object.hasOwn(c.runs,x)?_.do:_.do.filter($=>!M$.has($.type))).filter($=>$.type!=="start_verifier"||!S.has($.batchId));(_.part||b.length>0)&&f.push({seq:_.seq,say:Jt(_.say),do:[...v,...b]}),a={cursor:_.seq,ending:_.type==="ended"&&typeof _.data.ending=="string"?_.data.ending:a.ending}}if(!p.ended){let _=s.localNews(c,l);p.events.some(x=>x.type==="verdict")&&await s.changedFiles(c,l)&&(_.tell.changed=!0);let b=Lm(_.tell)?await F$(s,e,t,_.tell):"";b&&_.tell.changed&&c.said.push("changed"),(b||_.do.length>0)&&f.push({seq:null,say:Jt(b),do:_.do})}let m=p.ended&&!p.events.some(_=>_.type==="ended")&&g>0,C=Bm(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 F$(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.
816
- `),""}}function H$(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 U$(e,t){let n=[];for(;;){let r=await Wm(e,t,n.at(-1)?.seq??0,0);if(n.push(...r.events),r.ended||r.events.length<N$)return{events:n,ended:r.ended}}}function Jm(e,t,n){if(n instanceof L)return n.status===404?F(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?F(e,"not_logged_in","Your Canary login is no longer valid.","run `canary login`",3):be(n)?F(e,"unreachable","Canary couldn't be reached.",`run \`canary wait ${t}\` again in a minute`,2):F(e,n.code??"api_error",n.message,n.fix,n.status>=500?2:3);let r=is(n);if(r)return F(e,"home_not_writable",r.message,r.fix,2);F(e,"internal_error",n instanceof Error?n.message:String(n),void 0,2)}function Ms(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?`
817
- `:""}Canary \xB7 more to come: canary wait ${t}`)),process.exitCode=o}function q$(e){if(ht.test(e))return e;if(!/^[0-9a-f][0-9a-f-]{5,34}$/i.test(e))return null;let t;try{t=A$(qm(Y(),"requests"))}catch{return null}let n=new Set(t.map(r=>r.slice(0,36)).filter(r=>ht.test(r)&&r.toLowerCase().startsWith(e.toLowerCase())));return n.size===1?[...n][0]:null}async function B$(e,t){tt({cwd:process.cwd(),agent:t,mode:"wait"});let n=ne();if(!n)return F(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!ht.test(e))return F(t,"invalid_request_id","That isn't a request id.","use the id Canary gave when you asked",3);let r=Fl(),s=Hm(e,r);if(s.held){Ms(t,e,"",s.held.do,!0,s.held.exitCode,s.held.result),Um(e,r,{cursor:s.cursor,ending:s.ending,...s.checks?{checks:s.checks}:{}});return}let o;try{o=await D$(e,n,s,O$)}catch(p){return Jm(t,e,p)}let i=Hm(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:H$(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=rs(a.map(p=>p.say)),h=c.ending==="failed"?2:0;i.held?(Ms(t,e,u,d,!1,0),c={...c,held:i.held}):t&&o.ended&&u&&d.some(p=>p.type==="ask")?(Ms(t,e,u,[],!1,0),c={...c,held:{do:d,...o.result?{result:o.result}:{},exitCode:h}}):Ms(t,e,u,d,o.ended,h,o.result);try{Um(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.
818
- `)}}var W$=e=>typeof e=="string"&&e.trim()?e.trim():null;async function J$(e,t,n=!1){tt({cwd:process.cwd(),agent:t,mode:"show"});let r=ne();if(!r)return F(t,"not_logged_in","Not logged in","run `canary login` first",3);let s=q$(e);if(!s)return F(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 U$(s,r),a=Bm(o),c=n?Jt((await U(`/api/v1/cli/requests/${s}/repro`,{token:r,signal:AbortSignal.timeout(Dl)})).say):rs([...o.map(l=>l.say),a?.more??""]);Ms(t,s,c,a?.do.filter(l=>l.type==="fix"||l.type==="pr_section")??[],i,0,a?.result??void 0)}catch(o){Jm(t,s,o)}}function Gm(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)=>B$(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)=>J$(t,n.json===!0,n.repro===!0))}w();fe();Z();Gt();w();fe();Gt();var G$={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"},V$=15e3;function K$(e){return e&&G$[e]||"Other"}var Y$=e=>{let t=e?.finding?.nextActionCodeRef??e?.codeRefs?.[0]??e?.checkReadback?.codeRefs?.[0]??null;return t?{file:t.file,line:t.startLine??null}:null},z$=e=>(Array.isArray(e?.evidence)?e.evidence:[]).filter(t=>t&&t.media&&typeof t.media.url=="string").map(t=>({kind:D(t.modality)||"evidence",caption:D(t.caption),url:t.media.url,expiresAt:t.media.expiresAt??null}));function Q$(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=D(r?.assertion)||null;return{checkRunId:e.checkRunId,checkUrl:`${n}/checks/${e.checkRunId}`,scenarioId:e.stageBCheckId??e.checkRunId,category:K$(r?.lane),title:D(e.title),proof:s,status:o,whatWasTried:s==="source"?D(r?.finding?.whatWasTested)||null:D(r?.finding?.reproduce??r?.finding?.whatWasTested)||null,expected:i||D(r?.finding?.whatWasTested)||null,observed:D(r?.finding?.headline??r?.verdict?.reasonOneLiner)||null,assertion:i,location:Y$(r),evidence:z$(r),fix:s==="source"&&D(r?.finding?.reproduce)||null,reason:o==="could_not_run"&&(D(r?.verdict?.reasonOneLiner)||os[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 U(`/api/v1/red-team/runs/${e}/checks/${o.checkRunId}/finding`,{token:n.token,signal:AbortSignal.timeout(V$),...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=>Q$(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 Xm=new Set(["completed","failed","cancelled"]);function Ym(e){return Xm.has(e.status)?null:e.status==="queued"?"queued":e.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function zm(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 Hl(e,t,n,r,s={}){let o=ne();if(!o)return F(e,"not_logged_in","Not logged in","run `canary login` first",3),null;if(t.some(i=>!ht.test(i)))return F(e,"bad_id","ids are the UUIDs from the verify document (`runId`, `findings[].checkRunId`)",void 0,3),null;try{return await U(n,{token:o,...r?{baseUrl:r}:{},...s})}catch(i){if(i instanceof L){if(i.status===404)return F(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 F(e,"api_error",i.message,c,a?3:2,{httpStatus:i.status}),null}throw i}}var Qm=e=>{if(!e?.file)return"";let t=e.startLine?`:${e.startLine}`:"",n=e.startLine&&e.endLine&&e.endLine>e.startLine?`-${e.endLine}`:"";return`${D(e.file)}${t}${n}`};async function X$(e,t,n){let r=await Hl(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:D(p.title),status:zm(p)})),d={runId:s.runId,status:s.status,progress:Ym(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=ne();if(Xm.has(s.status)&&h){let p=await Vm(e,s.stageC.checks,{token:h,...n?{baseUrl:n}:{}});u=Km(s,p,{runUrl:`${At().replace(/\/+$/,"")}/runs/${e}`,repo:o,files:null})}return void console.log(JSON.stringify({ok:!0,...d,...u}))}let i=Ym(s),a=[`run ${D(s.runId)} \xB7 ${D(s.status)}${i?` \xB7 ${i}`:""}${s.target.treeHash?` \xB7 tree ${D(s.target.treeHash).slice(0,12)}`:""}`];s.failure?.publicMessage&&a.push(` ${D(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=zm(l),u=d==="could_not_run"?"could not verify":d,h=l.result==="blocked"?os[l.blockedReason??""]:void 0;a.push(` ${kt(l.materiality)??"P3"} ${u.padEnd(16)} ${D(l.title)} ${D(l.checkRunId)}${h?` (${h})`:""}`)}console.log(a.join(`
819
- `))}async function Z$(e,t,n,r){let s=await Hl(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(D(s.finding?.headline)||"(no finding written for this check yet)"),s.verdict&&o.push(`verdict: ${D(s.verdict.result)}${s.verdict.reasonOneLiner?` \u2014 ${D(s.verdict.reasonOneLiner)}`:""}${s.isStatic?" (reasoned from the code, not run)":""}`),s.assertion&&o.push(`assertion: ${D(s.assertion)}`),s.observable&&o.push(`observable: ${D(s.observable)}`),s.checkReadback?.whyThisCheck&&o.push(`why this check: ${D(s.checkReadback.whyThisCheck)}`),s.finding?.whatWasTested&&o.push(`tested: ${D(s.finding.whatWasTested)}`),s.finding?.reproduce&&o.push(`reproduce: ${D(s.finding.reproduce)}`),s.finding?.nextActionCodeRef&&o.push(`\u2192 ${Qm(s.finding.nextActionCodeRef)}`);for(let i of s.codeRefs??[])o.push(` ref ${Qm(i)}${i.reason?` \u2014 ${D(i.reason)}`:""}`);for(let i of s.evidence??[])o.push(` evidence ${D(i.modality)}: ${D(i.caption)}${i.media?` ${D(i.media.url)}`:i.failureReason?` (${D(i.failureReason)})`:""}`);for(let i of s.verdict?.limitations??[])o.push(` limitation: ${D(i)}`);s.network?.failures?.length&&o.push(` network failures: ${s.network.failures.length}`),console.log(o.join(`
820
- `))}async function eI(e,t,n,r,s,o){if(await Hl(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?`: ${D(r)}`:""}`)}}async function tI(e,t,n){let r=ne();if(!r)return F(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!ht.test(e))return F(t,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let s;try{s=await dc(e,r,{...n?{baseUrl:n}:{},onProgress:i=>console.error(` ${i}`)})}catch(i){if(i instanceof bt)return F(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 F(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 F(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=hc(s.run,s.run.target?.treeHash??"",s.findings,s.run.reverify);console.log(t?JSON.stringify(o):fc(o)),process.exitCode=o.exitCode}function Zm(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 F(r.json===!0,"bad_id","pass the run id `canary verify` printed","canary run <runId>",3);await X$(n,r.json===!0)}catch(s){F(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 tI(n,o)}catch(i){F(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 F(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?F(s.json===!0,"bad_report",`--${o[0]} needs a reason`,void 0,3):await eI(n,r,o[0],i,s.json===!0)}await Z$(n,r,s.json===!0)}catch(o){F(s.json===!0,"internal_error",o instanceof Error?o.message:String(o),void 0,2)}})}w();to();$n();fe();mn();Z();nt();import{readFileSync as lI,unlinkSync as uI,writeFileSync as dI}from"node:fs";import{basename as hI,join as fI}from"node:path";import{setTimeout as pI}from"node:timers/promises";w();import{emitKeypressEvents as nI}from"node:readline";var rI=36,sI=12,ey=64*1024,Ul=new Intl.Segmenter(void 0,{granularity:"grapheme"}),oI={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},iI={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function $i(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 aI(e,t){let n="";for(let{segment:r}of[...Ul.segment(ie(e))].reverse()){if(ls(r+n)>t)break;n=r+n}return n}function ty(e,t,n){let r=e.question,s=Math.max(1,t-5),o=(c,l="text")=>` ${us(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):aI(e.input??"",Math.max(1,s-2));return[o("CANARY \xB7 SETUP","gold"),o(`${e.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${$i(e.seconds)}`),o(`CLI workspace ${e.workspace}`,"muted"),"",o(r.key,"gold"),...Vt(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 cI(e,t,n,r){let s=Math.max(1,t-5),o=Math.max(1,n-2),i=e.outcome?iI[e.outcome.status]:e.question?"Your input is needed":oI[e.status],a=e.outcome?.status==="green"?"green":"gold",c=(u,h="text")=>us(ie(u),h,r),l;if(o<=3)l=[c(i,a),c(`Elapsed ${$i(e.seconds)}`,"muted")].slice(0,o);else if(e.question&&!e.outcome)l=ty(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 ${$i(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 ${$i(e.seconds)}`,"muted")}`];l.push("",` ${c(`Repository ${e.repository}`)}`,` ${c(`CLI workspace ${e.workspace}`)}`),e.detail&&!e.outcome&&l.push(...Vt(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=>jo(u,Math.max(1,t-1)))}function ny(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:T}=p();try{s.render(cI(i,k,T,r))}catch{S()}}function C(){let{columns:k,rows:T}=p();return n.isTTY&&k>=rI&&T>=sI&&ty(i,k,!1).length<=T-2}function _(){let k=i.question;if(!k)return;d=!0;try{s.render([])}catch{}let T=Math.max(1,p().columns-3);f(`
1853
+ `,()=>s()))})}process.exit(0)})}w();fe();Q();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=ne();if(r)try{await B("/api/v1/cli/auth/logout",{method:"POST",token:r})}catch{}bu();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();fe();Q();nt();import{createHash as IA}from"node:crypto";import{mkdirSync as RA,readdirSync as TA}from"node:fs";import{dirname as EA,join as Um}from"node:path";w();import{copyFileSync as Nm,existsSync as Ps,mkdirSync as Pm,renameSync as vA,rmSync as Ml,writeFileSync as _m}from"node:fs";import{dirname as xA,join as Ue}from"node:path";qt();var Ci=()=>({runs:{},told:{},said:[],endedAt:{}}),SA=4*6e4;function jm(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"&&Ps(t.checkout)?t.checkout:process.cwd())}function CA(e,t,n){let r=ce(t);Pm(r,{recursive:!0,mode:448});let s=On(e),o=Ue(r,"source.bundle");if(!Ps(o)&&Ps(Ue(s,"source.bundle")))try{vA(Ue(s,"source.bundle"),o)}catch{Nm(Ue(s,"source.bundle"),o),Ml(Ue(s,"source.bundle"),{force:!0})}for(let a of["source.json",lr])!Ps(Ue(r,a))&&Ps(Ue(s,a))&&Nm(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 js=e=>typeof e=="string"&&e?e:null,AA=e=>{try{return st(e,"job"),!0}catch{return!1}};function Mm(e,t,n){let r=js(e.data.checksRun),s=n.session;if(e.type==="ended"&&s&&jm(n)&&Ml(Ue(On(n.requestId),"source.bundle"),{force:!0}),!r||!s)return[];if(!Object.hasOwn(t.runs,r)){if(e.type==="ended"||!jm(n))return[];CA(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=>js(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(El(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||!AA(i.jobId))return[];let a=Ue(ce(r),"results",`${i.jobId}.json`);Pm(xA(a),{recursive:!0}),_m(a,JSON.stringify(i,null,2)+`
1854
+ `);let c=a.replace(/\.json$/,".md");return _m(c,Ol(i,r)),i.verdict==="broken"?[{type:"read_record",path:c}]:[]}case"batch_ended":{let i=js(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&&_s([i],(a.setupMinutes??30)*6e4+3e4),[]):((t.endedAt??={})[i]??=Date.now(),a&&_s([i],Ln+3e4),[])}case"wait_over":{let i=js(e.data.batchId);return i&&Pn([{runId:r}],i,js(e.data.jobId)),[]}case"ended":{let i=e.data.result?.running;return!(Array.isArray(i)&&i.length>0)&&!Ns(r)&&Ml(Ue(ce(r),"source.bundle"),{force:!0}),[]}default:return[]}}var Lm=e=>e.asks.length>0||e.approvals.length>0||e.changed||(e.setups?.length??0)>0;function Fm(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 ct(s.map(d=>({runId:d})))){if(l.status!=="open"||a(l.batchId))continue;let d=e.told[l.path];d!==void 0&&n-d<SA||(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 $t(l)){let u=ks(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}`),gs(Qt(p))?i.push({type:"start_verifier",batchId:f}):ms(f,o,p)}for(let l of ys(o))!c.includes(l.batchId)||!gs(Qt(l.checkout))||ps(l.checkout)||(tn(l.batchId),i.push({type:"start_verifier",batchId:l.batchId}));return{tell:r,do:i}}async function Dm(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 Zr(Ai(t.requestId))).treeHash===n)return!1}catch{return!1}return!0}Jt();var OA=25,Fl=45e3,$A=9*6e4,NA=9e4,_A=5,jA=200,Ll=(e,t)=>Um(K(),"requests",t===null?`${e}.json`:`${e}.${IA("sha256").update(t).digest("hex").slice(0,16)}.json`);function Wm(e,t){let n=Y(Ll(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 Bm(e,t,n){RA(EA(Ll(e,t)),{recursive:!0,mode:448}),Pe(Ll(e,t),n)}function Hm(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(`
1855
+ `):"";return{result:t.data.result??null,more:Gt(n),do:t.do}}var Dl=()=>yn();function qm(e,t,n,r){let s=Dl();return B(`/api/v1/cli/requests/${e}/events?after=${n}&wait=${r}`,{token:t,signal:AbortSignal.timeout(Fl),...s?{headers:{"x-canary-session":s}}:{}}).then(o=>({...o,events:o.events.map(ss)}))}function PA(e,t,n){return B(`/api/v1/cli/requests/${e}/here`,{method:"POST",token:t,body:n,signal:AbortSignal.timeout(Fl)})}var MA=new Set(["start_verifier","stop_verifier","keep_late_answer"]),LA={read:qm,pause:e=>new Promise(t=>setTimeout(t,e)),onEvent:Mm,localNews:Fm,changedFiles:Dm,here:PA,session:Dl};async function FA(e,t,n,r,s=LA){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?_A:OA,Math.floor(u/1e3)))),i=null}catch(A){if(!be(A)||(i??=Date.now(),Date.now()-i>NA))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=qA(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=>!MA.has(I.type))).filter(I=>I.type!=="start_verifier"||!x.has(I.batchId));(A.part||b.length>0)&&f.push({seq:A.seq,say:Gt(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=Lm(A.tell)?await DA(s,e,t,A.tell):"";b&&A.tell.changed&&c.said.push("changed"),(b||A.do.length>0)&&f.push({seq:null,say:Gt(b),do:A.do})}let m=p.ended&&!p.events.some(A=>A.type==="ended")&&g>0,C=Hm(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 DA(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.
1856
+ `),""}}function WA(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 BA(e,t){let n=[];for(;;){let r=await qm(e,t,n.at(-1)?.seq??0,0);if(n.push(...r.events),r.ended||r.events.length<jA)return{events:n,ended:r.ended}}}function Gm(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=is(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 Ms(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?`
1857
+ `:""}Canary \xB7 more to come: canary wait ${t}`)),process.exitCode=o}function UA(e){if(ht.test(e))return e;if(!/^[0-9a-f][0-9a-f-]{5,34}$/i.test(e))return null;let t;try{t=TA(Um(K(),"requests"))}catch{return null}let n=new Set(t.map(r=>r.slice(0,36)).filter(r=>ht.test(r)&&r.toLowerCase().startsWith(e.toLowerCase())));return n.size===1?[...n][0]:null}async function HA(e,t){tt({cwd:process.cwd(),agent:t,mode:"wait"});let n=ne();if(!n)return D(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!ht.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=Wm(e,r);if(s.held){Ms(t,e,"",s.held.do,!0,s.held.exitCode,s.held.result),Bm(e,r,{cursor:s.cursor,ending:s.ending,...s.checks?{checks:s.checks}:{}});return}let o;try{o=await FA(e,n,s,$A)}catch(p){return Gm(t,e,p)}let i=Wm(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:WA(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=rs(a.map(p=>p.say)),h=c.ending==="failed"?2:0;i.held?(Ms(t,e,u,d,!1,0),c={...c,held:i.held}):t&&o.ended&&u&&d.some(p=>p.type==="ask")?(Ms(t,e,u,[],!1,0),c={...c,held:{do:d,...o.result?{result:o.result}:{},exitCode:h}}):Ms(t,e,u,d,o.ended,h,o.result);try{Bm(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.
1858
+ `)}}var qA=e=>typeof e=="string"&&e.trim()?e.trim():null;async function GA(e,t,n=!1){tt({cwd:process.cwd(),agent:t,mode:"show"});let r=ne();if(!r)return D(t,"not_logged_in","Not logged in","run `canary login` first",3);let s=UA(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 BA(s,r),a=Hm(o),c=n?Gt((await B(`/api/v1/cli/requests/${s}/repro`,{token:r,signal:AbortSignal.timeout(Fl)})).say):rs([...o.map(l=>l.say),a?.more??""]);Ms(t,s,c,a?.do.filter(l=>l.type==="fix"||l.type==="pr_section")??[],i,0,a?.result??void 0)}catch(o){Gm(t,s,o)}}function Jm(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)=>GA(t,n.json===!0,n.repro===!0))}w();fe();Q();Jt();w();fe();Jt();var JA={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"},YA=15e3;function VA(e){return e&&JA[e]||"Other"}var KA=e=>{let t=e?.finding?.nextActionCodeRef??e?.codeRefs?.[0]??e?.checkReadback?.codeRefs?.[0]??null;return t?{file:t.file,line:t.startLine??null}:null},zA=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 XA(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:VA(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:KA(r),evidence:zA(r),fix:s==="source"&&F(r?.finding?.reproduce)||null,reason:o==="could_not_run"&&(F(r?.verdict?.reasonOneLiner)||os[e.blockedReason??""])||null}}async function Ym(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 B(`/api/v1/red-team/runs/${e}/checks/${o.checkRunId}/finding`,{token:n.token,signal:AbortSignal.timeout(YA),...n.baseUrl?{baseUrl:n.baseUrl}:{}}))}catch{r.set(o.checkRunId,null)}return r}function Vm(e,t,n){let r=e.stageC.checks.map(s=>XA(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 Zm=new Set(["completed","failed","cancelled"]);function Km(e){return Zm.has(e.status)?null:e.status==="queued"?"queued":e.stageB.status==="completed"?"verifying in sandboxes":"analyzing the change"}function zm(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 Wl(e,t,n,r,s={}){let o=ne();if(!o)return D(e,"not_logged_in","Not logged in","run `canary login` first",3),null;if(t.some(i=>!ht.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 B(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 Xm=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 ZA(e,t,n){let r=await Wl(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:zm(p)})),d={runId:s.runId,status:s.status,progress:Km(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=ne();if(Zm.has(s.status)&&h){let p=await Ym(e,s.stageC.checks,{token:h,...n?{baseUrl:n}:{}});u=Vm(s,p,{runUrl:`${Tt().replace(/\/+$/,"")}/runs/${e}`,repo:o,files:null})}return void console.log(JSON.stringify({ok:!0,...d,...u}))}let i=Km(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=zm(l),u=d==="could_not_run"?"could not verify":d,h=l.result==="blocked"?os[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(`
1859
+ `))}async function QA(e,t,n,r){let s=await Wl(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 ${Xm(s.finding.nextActionCodeRef)}`);for(let i of s.codeRefs??[])o.push(` ref ${Xm(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(`
1860
+ `))}async function eI(e,t,n,r,s,o){if(await Wl(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 tI(e,t,n){let r=ne();if(!r)return D(t,"not_logged_in","Not logged in","run `canary login` first",3);if(!ht.test(e))return D(t,"bad_id","the run id is the UUID `canary verify` printed",void 0,3);let s;try{s=await dc(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=hc(s.run,s.run.target?.treeHash??"",s.findings,s.run.reverify);console.log(t?JSON.stringify(o):fc(o)),process.exitCode=o.exitCode}function Qm(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 ZA(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 tI(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 eI(n,r,o[0],i,s.json===!0)}await QA(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();Q();nt();import{readFileSync as lI,unlinkSync as uI,writeFileSync as dI}from"node:fs";import{basename as hI,join as fI}from"node:path";import{setTimeout as pI}from"node:timers/promises";w();import{emitKeypressEvents as nI}from"node:readline";var rI=36,sI=12,ey=64*1024,Bl=new Intl.Segmenter(void 0,{granularity:"grapheme"}),oI={submitting:"Preparing setup",pending:"Queued for a clean sandbox",running:"Verifying in a clean sandbox",retrying:"Recovering verification",answering:"Continuing verification"},iI={green:"Clean sandbox boot verified",red:"Setup verification failed",error:"Verification encountered an error",paused:"Verification needs your input"};function Ii(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 aI(e,t){let n="";for(let{segment:r}of[...Bl.segment(ie(e))].reverse()){if(ls(r+n)>t)break;n=r+n}return n}function ty(e,t,n){let r=e.question,s=Math.max(1,t-5),o=(c,l="text")=>` ${us(ie(c),l,n)}`,i=0;if(r.secret){for(let c of Bl.segment(e.input??""))if(++i===24)break}let a=r.secret?"\u2022".repeat(i):aI(e.input??"",Math.max(1,s-2));return[o("CANARY \xB7 SETUP","gold"),o(`${e.inputSubmitted?"Input received locally":"Input needed"} \xB7 ${Ii(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 cI(e,t,n,r){let s=Math.max(1,t-5),o=Math.max(1,n-2),i=e.outcome?iI[e.outcome.status]:e.question?"Your input is needed":oI[e.status],a=e.outcome?.status==="green"?"green":"gold",c=(u,h="text")=>us(ie(u),h,r),l;if(o<=3)l=[c(i,a),c(`Elapsed ${Ii(e.seconds)}`,"muted")].slice(0,o);else if(e.question&&!e.outcome)l=ty(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 ${Ii(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 ${Ii(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 ny(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(cI(i,k,N,r))}catch{x()}}function C(){let{columns:k,rows:N}=p();return n.isTTY&&k>=rI&&N>=sI&&ty(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(`
821
1861
  Input needed: ${ie(k.key)}
822
- ${Vt(k.prompt,T).join(`
1862
+ ${Yt(k.prompt,N).join(`
823
1863
  `)}
824
1864
 
825
1865
  Answer with: canary setup --answer '<value>'
826
- `)}function b(){h&&!C()?h.settle(null,!0):m()}function x(){!a||h||c||(c=!0,process.off("SIGINT",$),process.off("SIGTERM",O),process.off("exit",S),g(),l!==void 0&&(f(`
1866
+ `)}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(`
827
1867
  Stopped watching. Run canary setup to resume verification.
828
- `),process.exit(l)))}function S(){a||(a=!0,clearInterval(u),t.off("resize",b),h?.settle(null),x())}function v(k){l=k,S(),x()}function $(){h?h.settle(null):v(130)}function O(){v(143)}async function y(k,T){return a||h||T?.aborted?null:(i.question={...k},i.input="",i.inputActive=!0,i.inputSubmitted=!1,i.inputNotice=void 0,d=!1,C()?new Promise(J=>{let Le=n.isRaw,Ce=n.readableFlowing===!0,ae="",A="",M=!1,R=!1,q="",G=!1,te=!1,Ve=!1,xt=!1,Ze;function z(Re,se=!1){xt||(Ze={answer:Ze&&Re!==null?Ze.answer:Re,showStatic:se||Ze?.showStatic||!1},te||=!!q&&!R,ae=A="",i.input="",(M||R||q||te)&&(i.inputNotice="Finishing clipboard input.",m()),gt())}function gt(){if(xt||!Ze||G||M||R||q||te)return;let{answer:Re,showStatic:se}=Ze;xt=!0,n.off("keypress",Un),n.off("data",Tr),n.off("data",Hs),n.off("end",_t),n.off("error",_t),n.off("close",_t),T?.removeEventListener("abort",Ct);try{n.setRawMode(Le)}catch{}Ce||n.pause(),f(`${ve}?2004l`),ae="",A="",i.input="",i.inputActive=!1,i.inputSubmitted=Re!==null,i.inputNotice=Re===null?"You can provide this value later.":"Input received locally.",h=void 0,se&&!a?_():m(),g(),x(),J(Re)}function Ct(){z(null)}function _t(){M=R=G=te=!1,q="",z(null)}function Tr(Re){G=!0;for(let se of typeof Re=="string"?Re:Re.toString("utf8")){let qn=R?`${ve}201~`:`${ve}200~`;q=se===qn[q.length]?q+se:se==="\x1B"?se:"",q===qn&&(R=!R,q="")}}function Hs(){G=!1,gt()}function we(Re){ae.length+Re.length>ey?(Ve=!0,i.inputNotice="Too long. Ctrl+U clears input."):(ae+=Re,Ve||(i.inputNotice=void 0))}function Un(Re,se){if(!(xt||!se))try{if(!G&&se.name==="escape"&&(q=""),!q&&se.sequence?.startsWith("\x1B")&&(te=!1),Ze){se.name==="paste-start"?M=!0:se.name==="paste-end"&&(M=!1),gt();return}if(se.name==="paste-start"){M=!0,A="";return}if(se.name==="escape"||se.ctrl&&["c","d"].includes(se.name??"")){Ct();return}if(se.name==="paste-end")M=!1,we(A.replace(/\r\n?/g,`
829
- `)),A="";else if(M){let qn=(Re||se.sequence||"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"");(se.sequence??"").includes("\x1B")||(A.length+qn.length<=ey?A+=qn:(Ve=!0,i.inputNotice="Too long. Ctrl+U clears input."));return}else if(se.ctrl&&se.name==="u")ae="",Ve=!1,i.inputNotice=void 0;else if(se.name==="backspace")ae=[...Ul.segment(ae)].slice(0,-1).map(Cy=>Cy.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(!Ve){z(ae);return}}else!se.ctrl&&!se.meta&&Re&&we(Re.replace(/[\x00-\x1f\x7f-\x9f]/g,""));i.input=ae,m()}catch{Ct()}}h={settle:z};try{if(n.prependListener("data",Tr),nI(n),n.on("keypress",Un),n.on("data",Hs),n.once("end",_t),n.once("error",_t),n.once("close",_t),T?.addEventListener("abort",Ct,{once:!0}),T?.aborted){Ct();return}n.setRawMode(!0),n.resume(),f(`${ve}?2004h${ve}?25l`),m()}catch{Ct()}}):(i.inputActive=!1,_(),null))}return t.on("resize",b),process.on("SIGINT",$),process.on("SIGTERM",O),process.once("exit",S),u=setInterval(m,80),u.unref(),f(`${ve}?25l`),m(),{update(k,T){a||(i.status=k,i.detail=T,h||(i.question=void 0,i.input=void 0,d=!1),f(`${ve}?25l`),m())},warn(k){if(!a)try{s.render([])}catch{S()}f(`
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,te=!1,Ye=!1,St=!1,Qe;function z(Ee,se=!1){St||(Qe={answer:Qe&&Ee!==null?Qe.answer:Ee,showStatic:se||Qe?.showStatic||!1},te||=!!U&&!E,ae=T="",i.input="",(M||E||U||te)&&(i.inputNotice="Finishing clipboard input.",m()),gt())}function gt(){if(St||!Qe||J||M||E||U||te)return;let{answer:Ee,showStatic:se}=Qe;St=!0,n.off("keypress",Bn),n.off("data",Nr),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=te=!1,U="",z(null)}function Nr(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>ey?(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")&&(te=!1),Qe){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,`
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<=ey?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=[...Bl.segment(ae)].slice(0,-1).map(Cy=>Cy.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",Nr),nI(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(`
830
1870
  Warning: ${k.split(/\r?\n/).map(ie).join(`
831
1871
  `)}
832
1872
 
833
- `),m()},ask:y,finish(k){if(a)return;h?.settle(null),i.question=void 0,i.outcome=k,d=!1,m(),S();let T=[k.message,...k.updatedFiles?.length?[`Updated locally: ${k.updatedFiles.join(", ")}`]:[],...k.warning?[`Warning: ${k.warning}`]:[],...k.next?[`Next: ${k.next}`]:[]].filter(J=>!!J);T.length&&f(`
834
- ${T.flatMap(J=>J.split(/\r?\n/).map(ie)).join(`
1873
+ `),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
+ ${N.flatMap(G=>G.split(/\r?\n/).map(ie)).join(`
835
1875
  `)}
836
- `)},stop:S}}Ha();Yr();De();Wt();Ro();ac();var Ar=3e3,Ii=2,gI=9e4,ry=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=>fI(e,".canary","verify-job.json");function Ls(e){try{let t=JSON.parse(lI(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||!Ao(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 Ye("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 mI(e){return Ls(e)?.jobId??null}var sy=(e,t)=>dI(ql(e),JSON.stringify(t)+`
837
- `);function Ai(e){try{uI(ql(e))}catch{}}var Rr=(e,t)=>pI(e,void 0,{signal:t});function yI(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 wI(e,t){let n,r;try{n=Ht(e),Vr(e),r=Qn(e).name}catch(u){if(u instanceof Ye||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?`
1876
+ `)},stop:x}}Wa();Kr();Fe();qt();Eo();ac();var Tr=3e3,Ri=2,gI=9e4,ry=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 Ul=e=>fI(e,".canary","verify-job.json");function Ls(e){try{let t=JSON.parse(lI(Ul(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 Ke("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 mI(e){return Ls(e)?.jobId??null}var sy=(e,t)=>dI(Ul(e),JSON.stringify(t)+`
1877
+ `);function Ti(e){try{uI(Ul(e))}catch{}}var Er=(e,t)=>pI(e,void 0,{signal:t});function yI(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 wI(e,t){let n,r;try{n=Wt(e),Yr(e),r=Xn(e).name}catch(u){if(u instanceof Ke||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?`
838
1878
  Fix: ${u.fix}`:""}`),process.exitCode=1;return}throw u}let s=r??null,o=n.setupSh.trim().split(`
839
- `).length,i=yI(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 oy(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(Ht(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 _n(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(Ht(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}`)}Ai(e);let d=[];if(t.approved?.healed&&l)try{d=_d(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(`
840
- `)||void 0,next:`Open Canary: ${At().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"){Ai(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?`
1879
+ `).length,i=yI(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}=Fa(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 oy(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(Wt(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(Wt(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}`)}Ti(e);let d=[];if(t.approved?.healed&&l)try{d=Ad(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(`
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"){Ti(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?`
841
1881
 
842
1882
  ${o.log.slice(-2e3)}`:""}`,warning:r.warnings.join(`
843
1883
  `)||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(`
844
1884
  ${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(`
845
- Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function iy(e,t){return e.status==="needs_input"&&e.needsInput?.questionId===t.questionId}async function bI(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 Rr(Ar,s.signal);let a=await n(s.signal);if(!iy(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 kI(e,t,n,r,s,o){let i="",a=null;async function c(d){for(;;)try{let u=await U(`/api/v1/cli/verify/${t}`,{token:n,baseUrl:s.context?.apiUrl,signal:d});if(!u||!ry.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<gI)){await Rr(Ar,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 Rr(Ar);continue}if(d.status==="needs_input"&&d.needsInput&&s.display){let u=d.needsInput,h=await bI({...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(!iy(f,u)){l=f;continue}s.display.update("answering","Sending your answer to the verifier.");try{await ly(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 Rr(Ar);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 oy(e,d,r,s))return"terminal";await Rr(Ar)}}async function Ri(e,t,n,r,s,o){Vn();let i=t;for(let a=0;;){if(await kI(e,i,n,r,s,o)==="terminal")return;if(Ai(e),s.freshUpload=!0,a>=Ii){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:Ii})):s.display?s.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${Ii}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${Ii})`);let l=await cy(e,n,r,s);if(l===null)return;i=l,o=void 0}}async function ay(e,t,n,r){let s=r.context??=await Sn(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,ts(n.source,s,o.repositoryId,{requestKey:`setup:${n.recipeHash}`,uploadId:n.sourceUploadId})}async function cy(e,t,n,r){let s=Ht(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 Sn(e,t),a=await vn({...i,token:t}),c=await _n(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 U("/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 sy(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}}),ts(c.manifest,i,a.repositoryId,{requestKey:`setup:${l}`,uploadId:d.uploadId}),u.jobId}finally{await c.dispose()}}async function vI(e,t,n){let r=ne();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 ay(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 U(`/api/v1/cli/verify/${o}`,{token:r,baseUrl:n.context?.apiUrl}),!a||!ry.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 Rr(Ar);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 Ri(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(Ht(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.
846
- `+(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 oy(e,a,t,n,{writeBack:!d,recipeChanged:d});return}}Ai(e),n.freshUpload=!0}let i=await cy(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 Ri(e,i,r,t,n))}async function ly(e,t,n,r,s,o,i){if(r.secret&&s&&i.secrets.add(s),await U(`/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(Ht(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.");Fa(e,[{name:r.key,value:s,class:"external_boot",why:r.prompt.slice(0,200)||"asked during cloud verification"}]),c&&a&&sy(e,{...a,recipeHash:bn(Ht(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 SI(e,t,n,r){let s=ne(),o=mI(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 ay(e,s,i,r);let a=await U(`/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 Ri(e,o,s,n,r);return}let c=a.needsInput;r.display?.update("answering","Sending your answer to the verifier."),await ly(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 Ri(e,o,s,n,r,{questionId:c.questionId,until:Date.now()+3e4})}function uy(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();tt({cwd:n});let r=t.json===!0;if(t.check){wI(n,r);return}let s={secrets:new Set(t.answer?[t.answer]:[]),warnings:[],baseRef:t.base};try{let o=K().team;s.display=ny({json:r,animation:t.animation!==!1,repository:hI(n),workspace:o?.name||(o?.id?"Saved workspace":"Select a workspace")}),t.answer!==void 0?await SI(n,t.answer,r,s):await vI(n,r,s)}catch(o){if(o instanceof Ye||o instanceof He||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?`
1885
+ Answer with: canary setup --answer '<value>'`)),process.exitCode=3,!0}return!1}function iy(e,t){return e.status==="needs_input"&&e.needsInput?.questionId===t.questionId}async function bI(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 Er(Tr,s.signal);let a=await n(s.signal);if(!iy(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 kI(e,t,n,r,s,o){let i="",a=null;async function c(d){for(;;)try{let u=await B(`/api/v1/cli/verify/${t}`,{token:n,baseUrl:s.context?.apiUrl,signal:d});if(!u||!ry.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<gI)){await Er(Tr,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 Er(Tr);continue}if(d.status==="needs_input"&&d.needsInput&&s.display){let u=d.needsInput,h=await bI({...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(!iy(f,u)){l=f;continue}s.display.update("answering","Sending your answer to the verifier.");try{await ly(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 Er(Tr);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 oy(e,d,r,s))return"terminal";await Er(Tr)}}async function Ei(e,t,n,r,s,o){Yn();let i=t;for(let a=0;;){if(await kI(e,i,n,r,s,o)==="terminal")return;if(Ti(e),s.freshUpload=!0,a>=Ri){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:Ri})):s.display?s.display.update("retrying",`The cloud worker stopped. Resubmitting (${a} of ${Ri}).`):console.log(` \u2026 the cloud service restarted mid-verify \u2014 resubmitting (attempt ${a} of ${Ri})`);let l=await cy(e,n,r,s);if(l===null)return;i=l,o=void 0}}async function ay(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,ts(n.source,s,o.repositoryId,{requestKey:`setup:${n.recipeHash}`,uploadId:n.sourceUploadId})}async function cy(e,t,n,r){let s=Wt(e);Yr(e);let{missing:o}=Fa(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 B("/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 sy(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}}),ts(c.manifest,i,a.repositoryId,{requestKey:`setup:${l}`,uploadId:d.uploadId}),u.jobId}finally{await c.dispose()}}async function vI(e,t,n){let r=ne();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}Gr();let s=Ls(e);s?.scope&&await ay(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 B(`/api/v1/cli/verify/${o}`,{token:r,baseUrl:n.context?.apiUrl}),!a||!ry.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 Er(Tr);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 Ei(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(Wt(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.
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 oy(e,a,t,n,{writeBack:!d,recipeChanged:d});return}}Ti(e),n.freshUpload=!0}let i=await cy(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 Ei(e,i,r,t,n))}async function ly(e,t,n,r,s,o,i){if(r.secret&&s&&i.secrets.add(s),await B(`/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(Wt(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.");Da(e,[{name:r.key,value:s,class:"external_boot",why:r.prompt.slice(0,200)||"asked during cloud verification"}]),c&&a&&sy(e,{...a,recipeHash:bn(Wt(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 xI(e,t,n,r){let s=ne(),o=mI(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 ay(e,s,i,r);let a=await B(`/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 Ei(e,o,s,n,r);return}let c=a.needsInput;r.display?.update("answering","Sending your answer to the verifier."),await ly(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 Ei(e,o,s,n,r,{questionId:c.questionId,until:Date.now()+3e4})}function uy(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();tt({cwd:n});let r=t.json===!0;if(t.check){wI(n,r);return}let s={secrets:new Set(t.answer?[t.answer]:[]),warnings:[],baseRef:t.base};try{let o=V().team;s.display=ny({json:r,animation:t.animation!==!1,repository:hI(n),workspace:o?.name||(o?.id?"Saved workspace":"Select a workspace")}),t.answer!==void 0?await xI(n,t.answer,r,s):await vI(n,r,s)}catch(o){if(o instanceof Ke||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?`
847
1887
  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?`
848
- 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 cs({json:r})})}Gt();w();Z();nt();import{lstatSync as xI,mkdirSync as CI,readFileSync as dy,writeFileSync as hy}from"node:fs";import{join as Bl}from"node:path";var _I=5e3,$I=/^[a-z0-9][a-z0-9-]{0,39}$/,II=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,AI="npm i -g @runcanary/cli@latest --prefer-online";function py(e){let t=Bl(Y(),"skills");return{dir:t,body:Bl(t,`${e}.md`),meta:Bl(t,`${e}.json`)}}function RI(e){let t=py(e);try{let n=JSON.parse(dy(t.meta,"utf8"));return{body:dy(t.body,"utf8"),meta:n}}catch{return null}}function Ds(e){try{return xI(e).isSymbolicLink()}catch{return!1}}function EI(e,t){let n=py(e);try{if(Ds(Y())||Ds(n.dir)||Ds(n.body)||Ds(n.meta)||(CI(n.dir,{recursive:!0,mode:448}),Ds(n.dir)))return;hy(n.body,t.body,{flag:"w",mode:384}),hy(n.meta,JSON.stringify(t.meta,null,2)+`
849
- `,{flag:"w",mode:384})}catch{}}function fy(e){return e instanceof Error?e.message:String(e)}async function OI(e,t){let n;try{n=await fetch(e,{headers:{...Ft(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${t}`},signal:AbortSignal.timeout(_I)})}catch(r){return{kind:"failed",reason:fy(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: ${fy(r)}`}}}async function Wl(e){let t=await OI(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 EI(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=RI(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 TI(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 jI(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 gy(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 Er(e,t,n={}){if(!e.ok)return t?{stream:"stdout",text:JSON.stringify({ok:!1,error:e.error,...n})+`
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 cs({json:r})})}Jt();w();Q();nt();import{lstatSync as SI,mkdirSync as CI,readFileSync as dy,writeFileSync as hy}from"node:fs";import{join as Hl}from"node:path";var AI=5e3,II=/^[a-z0-9][a-z0-9-]{0,39}$/,RI=/^[a-z0-9][a-z0-9-]{0,63}(?:\.[a-z0-9]{1,16})*\.(?:html|json|md|txt)$/,TI="npm i -g @runcanary/cli@latest --prefer-online";function py(e){let t=Hl(K(),"skills");return{dir:t,body:Hl(t,`${e}.md`),meta:Hl(t,`${e}.json`)}}function EI(e){let t=py(e);try{let n=JSON.parse(dy(t.meta,"utf8"));return{body:dy(t.body,"utf8"),meta:n}}catch{return null}}function Fs(e){try{return SI(e).isSymbolicLink()}catch{return!1}}function OI(e,t){let n=py(e);try{if(Fs(K())||Fs(n.dir)||Fs(n.body)||Fs(n.meta)||(CI(n.dir,{recursive:!0,mode:448}),Fs(n.dir)))return;hy(n.body,t.body,{flag:"w",mode:384}),hy(n.meta,JSON.stringify(t.meta,null,2)+`
1889
+ `,{flag:"w",mode:384})}catch{}}function fy(e){return e instanceof Error?e.message:String(e)}async function $I(e,t){let n;try{n=await fetch(e,{headers:{...Dt(),accept:"text/markdown, text/plain","user-agent":`canary-cli/${t}`},signal:AbortSignal.timeout(AI)})}catch(r){return{kind:"failed",reason:fy(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: ${fy(r)}`}}}async function ql(e){let t=await $I(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 OI(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=EI(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 NI(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 _I(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 gy(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 Or(e,t,n={}){if(!e.ok)return t?{stream:"stdout",text:JSON.stringify({ok:!1,error:e.error,...n})+`
850
1890
  `,exit:1}:{stream:"stderr",text:`\u2717 ${e.error}
851
1891
  `,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)+`
852
1892
  `,exit:0}}return{stream:"stdout",text:`${gy(e)}
853
1893
 
854
1894
  ${e.body}${e.body.endsWith(`
855
1895
  `)?"":`
856
- `}`,exit:0}}function Fs(e){(e.stream==="stdout"?process.stdout:process.stderr).write(e.text),process.exit(e.exit)}function NI(e,t,n={}){if(!e.ok||t){let r=Er(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:`${gy(e)}
857
- `,exit:0}}function Ei(){return ue().replace(/\/+$/,"")}function my(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 Wl({key:"index",url:`${Ei()}/llms.txt`,cliVersion:e.version()??"0.0.0",notFound:`this Canary server (${Ei()}) does not publish skills yet`});Fs(Er(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;$I.test(t)||Fs(Er({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){II.test(n.asset)||Fs(Er({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 Wl({key:`${t}--${n.asset}`,url:`${Ei()}/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=NI(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 Wl({key:t,url:`${Ei()}/skills/${t}.md`,cliVersion:s,notFound:`no such operation "${t}" \u2014 run \`canary skills\` to list the operations`});if(o.ok){let i=jI(o.body);if(i&&s!=="0.0.0-dev"&&TI(s,i)<0){let a=`"${t}" needs Canary CLI ${i} or newer (you have ${s}). Update: ${AI}`,c=Er({ok:!1,error:a},r,{needsCli:i,cliVersion:s});Fs({...c,exit:2})}}Fs(Er(o,r,{name:t}))})}w();fe();Z();$n();var PI=3e3;function MI(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 yy(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=ne();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=K().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 U(`/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=wc(),l=c&&a?await Oo({token:r,apiUrl:ue().replace(/\/+$/,""),userId:i.user.id},c,a.id,AbortSignal.timeout(PI)):void 0,d=mc();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(MI(i.usage)),c&&(console.log(No(c)),console.log(In));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();Z();De();async function ky(){let e=ne();if(!e)throw new L(401,"not logged in");let{workspaces:t}=await U("/api/v1/cli/workspaces",{token:e});return t}function Or(e,t,n,r={}){e?console.log(JSON.stringify({ok:!1,error:t,message:n,...r})):console.error(n),process.exitCode=1}function wy(e,t){if(t instanceof L&&t.status===401){Or(e,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}Or(e,"workspace_error",t instanceof Error?t.message:String(t))}async function LI(e){let t=await ky(),n=K().team?.id;if(e){console.log(JSON.stringify({workspaces:t,active:n??null}));return}if(t.length===0){console.error("You're not a member of any workspace yet. Set one up at www.runcanary.ai first.");return}let 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 by(e,t){if(!Te(n=>({...n,team:{id:e.id,name:e.name}}))){Or(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 DI(e,t){let n=await ky(),r=e.trim();if(/^\d+$/.test(r)){let o=Number(r);if(o<1||o>n.length){Or(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}by(n[o-1],t);return}let s=n.filter(o=>o.id===r||o.name.toLowerCase()===r.toLowerCase());if(s.length===0){Or(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){Or(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}by(s[0],t)}function FI(e){let t=K().team;if(!t){e?console.log(JSON.stringify({workspace:null})):console.error("No active workspace. Run: canary workspace use <name>"),process.exitCode=1;return}console.log(e?JSON.stringify({workspace:t}):t.name)}function vy(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 LI(r)}catch(s){wy(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 DI(n,s)}catch(o){wy(s,o)}}),t.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(n=>FI(n.json===!0))}De();mn();var xe=new su;xe.name("canary").description("Canary \u2014 break the code your AI writes.").version(wt);var xy=process.argv[2]==="hook"||process.argv[2]==="jobs"||process.argv[2]==="wait";xy||pd();xy||fo();af(xe);yy(xe);Om(xe);my(xe);vy(xe);uy(xe);Mh(xe);Zm(xe);Gm(xe);wf(xe);fm(xe);yf(xe);yc(xe);Em(xe);xe.addHelpText("after",`
858
- Ask Canary anything, in your own words: canary "find issues in billing" (or on stdin: canary -)`);var HI=new Set(["help",...xe.commands.flatMap(e=>[e.name(),...e.aliases()])]),UI=new Set(["-h","--help",...xe.options.flatMap(e=>[e.short,e.long]).filter(e=>!!e)]),Sy=rp(process.argv.slice(2),HI,UI);Sf()||(Sy?op(process.cwd(),Sy):xe.parseAsync(process.argv)).catch(e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)});
1896
+ `}`,exit:0}}function Ds(e){(e.stream==="stdout"?process.stdout:process.stderr).write(e.text),process.exit(e.exit)}function jI(e,t,n={}){if(!e.ok||t){let r=Or(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:`${gy(e)}
1897
+ `,exit:0}}function Oi(){return ue().replace(/\/+$/,"")}function my(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 ql({key:"index",url:`${Oi()}/llms.txt`,cliVersion:e.version()??"0.0.0",notFound:`this Canary server (${Oi()}) does not publish skills yet`});Ds(Or(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;II.test(t)||Ds(Or({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){RI.test(n.asset)||Ds(Or({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 ql({key:`${t}--${n.asset}`,url:`${Oi()}/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=jI(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 ql({key:t,url:`${Oi()}/skills/${t}.md`,cliVersion:s,notFound:`no such operation "${t}" \u2014 run \`canary skills\` to list the operations`});if(o.ok){let i=_I(o.body);if(i&&s!=="0.0.0-dev"&&NI(s,i)<0){let a=`"${t}" needs Canary CLI ${i} or newer (you have ${s}). Update: ${TI}`,c=Or({ok:!1,error:a},r,{needsCli:i,cliVersion:s});Ds({...c,exit:2})}}Ds(Or(o,r,{name:t}))})}w();fe();Q();In();var PI=3e3;function MI(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 yy(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=ne();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 B(`/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=wc(),l=c&&a?await $o({token:r,apiUrl:ue().replace(/\/+$/,""),userId:i.user.id},c,a.id,AbortSignal.timeout(PI)):void 0,d=mc();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(MI(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();Q();Fe();async function ky(){let e=ne();if(!e)throw new L(401,"not logged in");let{workspaces:t}=await B("/api/v1/cli/workspaces",{token:e});return t}function $r(e,t,n,r={}){e?console.log(JSON.stringify({ok:!1,error:t,message:n,...r})):console.error(n),process.exitCode=1}function wy(e,t){if(t instanceof L&&t.status===401){$r(e,"not_logged_in","Not logged in. Run: canary login",{fix:"canary login"});return}$r(e,"workspace_error",t instanceof Error?t.message:String(t))}async function LI(e){let t=await ky(),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 by(e,t){if(!Ne(n=>({...n,team:{id:e.id,name:e.name}}))){$r(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 FI(e,t){let n=await ky(),r=e.trim();if(/^\d+$/.test(r)){let o=Number(r);if(o<1||o>n.length){$r(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}by(n[o-1],t);return}let s=n.filter(o=>o.id===r||o.name.toLowerCase()===r.toLowerCase());if(s.length===0){$r(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){$r(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}by(s[0],t)}function DI(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 vy(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 LI(r)}catch(s){wy(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 FI(n,s)}catch(o){wy(s,o)}}),t.command("current").description("Print the active workspace").option("--json","output machine-readable JSON").action(n=>DI(n.json===!0))}Fe();mn();var Se=new su;Se.name("canary").description("Canary \u2014 break the code your AI writes.").version(wt);var Sy=process.argv[2]==="hook"||process.argv[2]==="jobs"||process.argv[2]==="wait";Sy||pd();Sy||fo();af(Se);yy(Se);$m(Se);my(Se);vy(Se);uy(Se);Mh(Se);Qm(Se);Jm(Se);wf(Se);fm(Se);yf(Se);yc(Se);Om(Se);Se.addHelpText("after",`
1898
+ Ask Canary anything, in your own words: canary "find issues in billing" (or on stdin: canary -)`);var WI=new Set(["help",...Se.commands.flatMap(e=>[e.name(),...e.aliases()])]),BI=new Set(["-h","--help",...Se.options.flatMap(e=>[e.short,e.long]).filter(e=>!!e)]),xy=rp(process.argv.slice(2),WI,BI);xf()||(xy?op(process.cwd(),xy):Se.parseAsync(process.argv)).catch(e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)});
859
1899
  /*! Bundled license information:
860
1900
 
861
1901
  smol-toml/dist/error.js: