@firefunc-agent/runner 0.9.0 → 0.9.4

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 (66) hide show
  1. package/README.md +90 -28
  2. package/dist/activity.d.ts +4 -1
  3. package/dist/activity.js +94 -8
  4. package/dist/api.d.ts +24 -0
  5. package/dist/api.js +74 -5
  6. package/dist/brief.d.ts +5 -0
  7. package/dist/brief.js +21 -0
  8. package/dist/build-info.json +2 -2
  9. package/dist/cli.js +10 -2
  10. package/dist/config.d.ts +2 -0
  11. package/dist/cut.d.ts +45 -0
  12. package/dist/cut.js +105 -0
  13. package/dist/daemon.d.ts +16 -0
  14. package/dist/daemon.js +156 -35
  15. package/dist/declined.d.ts +11 -0
  16. package/dist/declined.js +27 -0
  17. package/dist/engines/claude.js +129 -1
  18. package/dist/engines/types.d.ts +10 -0
  19. package/dist/exec.d.ts +3 -0
  20. package/dist/exec.js +48 -5
  21. package/dist/firefunc/agents.js +59 -7
  22. package/dist/firefunc/client.d.ts +1 -0
  23. package/dist/firefunc/client.js +3 -0
  24. package/dist/firefunc/configure.d.ts +6 -0
  25. package/dist/firefunc/configure.js +409 -0
  26. package/dist/firefunc/main.js +45 -7
  27. package/dist/firefunc/output.d.ts +1 -0
  28. package/dist/firefunc/output.js +24 -1
  29. package/dist/firefunc/tasks.js +32 -4
  30. package/dist/firefunc/version.js +2 -17
  31. package/dist/held.d.ts +18 -0
  32. package/dist/held.js +95 -0
  33. package/dist/job.d.ts +3 -0
  34. package/dist/job.js +437 -76
  35. package/dist/keep-local.d.ts +6 -1
  36. package/dist/keep-local.js +171 -4
  37. package/dist/limit.d.ts +30 -0
  38. package/dist/limit.js +258 -0
  39. package/dist/locks.d.ts +14 -0
  40. package/dist/locks.js +164 -0
  41. package/dist/mcp-proxy.d.ts +21 -0
  42. package/dist/mcp-proxy.js +180 -0
  43. package/dist/mcp.d.ts +2 -0
  44. package/dist/mcp.js +31 -2
  45. package/dist/orphans.d.ts +40 -0
  46. package/dist/orphans.js +235 -0
  47. package/dist/pool.d.ts +7 -0
  48. package/dist/pool.js +57 -9
  49. package/dist/pr-title.d.ts +11 -0
  50. package/dist/pr-title.js +63 -0
  51. package/dist/recover.d.ts +10 -0
  52. package/dist/recover.js +104 -0
  53. package/dist/session-stream.d.ts +8 -1
  54. package/dist/session-stream.js +9 -1
  55. package/dist/skills.d.ts +11 -0
  56. package/dist/skills.js +164 -0
  57. package/dist/stopped.d.ts +3 -0
  58. package/dist/stopped.js +10 -0
  59. package/dist/usage.d.ts +49 -0
  60. package/dist/usage.js +389 -0
  61. package/dist/version.d.ts +1 -0
  62. package/dist/version.js +17 -0
  63. package/dist/worktrees.d.ts +15 -0
  64. package/dist/worktrees.js +96 -0
  65. package/package.json +1 -1
  66. package/skill/firefunc/SKILL.md +63 -8
@@ -3,5 +3,10 @@ export declare function codeNote(ref: string | null): string;
3
3
  export declare function stripCode(text: string): string;
4
4
  export declare const UNNAMED_COMMAND = "a command";
5
5
  export declare function commandName(command: string): string;
6
- export declare function errorLine(stderr: string): string | null;
6
+ export declare function setupCommandName(command: string): string;
7
+ export declare function errorLine(stderr: string, sendable?: (line: string) => boolean): string | null;
8
+ export declare function foldHome(text: string, home: string): string;
9
+ export declare function lastWords(output: string): string | null;
10
+ export declare function setupReason(stderr: string, stdout: string): string | null;
7
11
  export declare function pushRefusal(stderr: string): string | null;
12
+ export declare function promisesLaterCheck(text: string): boolean;
@@ -390,7 +390,7 @@ function nextName(words, k, shape) {
390
390
  }
391
391
  return null;
392
392
  }
393
- function nameOf(words) {
393
+ function programAt(words) {
394
394
  let k = 0;
395
395
  let wrapped = false;
396
396
  while (k < words.length) {
@@ -406,6 +406,10 @@ function nameOf(words) {
406
406
  else
407
407
  break;
408
408
  }
409
+ return k;
410
+ }
411
+ function nameOf(words) {
412
+ const k = programAt(words);
409
413
  const first = words[k];
410
414
  if (!first?.bare || !/^[\w.@+/-]+$/.test(first.text))
411
415
  return null;
@@ -431,10 +435,41 @@ function nameOf(words) {
431
435
  }
432
436
  export const UNNAMED_COMMAND = 'a command';
433
437
  export function commandName(command) {
438
+ return namesOf(command, nameOf);
439
+ }
440
+ const INTERPRETER = /^(?:sh|bash|zsh|dash|ksh|fish|pwsh|powershell|node|tsx|ts-node|ruby|perl|php|python[\d.]*|py)$/;
441
+ const SHELL = /^(?:sh|bash|zsh|dash|ksh|fish|pwsh|powershell)$/;
442
+ const SCRIPT_NAME = /^[\w@+-][\w.@+-]*\.[A-Za-z0-9]{1,6}$/;
443
+ function scriptOf(words, at, shell) {
444
+ for (let i = at + 1; i < words.length; i++) {
445
+ const w = words[i];
446
+ if (w.bare && w.text.startsWith('-')) {
447
+ const body = shell
448
+ ? /^-[a-z]*c[a-z]*$|^-(?:Command|command)$/.test(w.text)
449
+ : /^-(?:[cepr]|-eval|-print)$/.test(w.text);
450
+ if (body)
451
+ return null;
452
+ continue;
453
+ }
454
+ const file = w.text.split('/').pop() ?? '';
455
+ return SCRIPT_NAME.test(file) && !carriesCredential(file) ? file : null;
456
+ }
457
+ return null;
458
+ }
459
+ export function setupCommandName(command) {
460
+ return namesOf(command, (words) => {
461
+ const name = nameOf(words);
462
+ if (!name || !INTERPRETER.test(name))
463
+ return name;
464
+ const script = scriptOf(words, programAt(words), SHELL.test(name));
465
+ return script ? `${name} ${script}` : name;
466
+ });
467
+ }
468
+ function namesOf(command, nameFor) {
434
469
  const parts = [];
435
470
  let op = '';
436
471
  for (const seg of segmentsOf(command)) {
437
- const name = nameOf(seg.words);
472
+ const name = nameFor(seg.words);
438
473
  if (name) {
439
474
  if (parts.length)
440
475
  parts.push(op === '&&' || op === '||' || op === '|' ? op : ';');
@@ -452,24 +487,137 @@ const FRAME = /^\s*(?:>?\s*\d*\s*[|│]|[\^~]+\s*$)|^\s+at\s/;
452
487
  const ERRORISH = /\b(?:error|fatal|failed|failure|denied|refused|not found|no such|unauthori[sz]ed|forbidden|timed out|cannot|can't|could not|unable|invalid|missing|ENOENT|EACCES|ECONNREFUSED|ETIMEDOUT)\b|\w(?:Error|Exception)\b/i;
453
488
  const CARET = /^\s*[\^~]+\s*$/;
454
489
  const PY_FRAME = /^\s*File ".*", line \d+/;
455
- export function errorLine(stderr) {
490
+ const SHELL_TRACE = /^\s*\+/;
491
+ function traceLines(lines) {
492
+ const traced = lines.map(() => false);
493
+ let open = null;
494
+ for (let i = 0; i < lines.length; i++) {
495
+ const line = lines[i];
496
+ if (!open && !SHELL_TRACE.test(line))
497
+ continue;
498
+ traced[i] = true;
499
+ for (let c = 0; c < line.length; c++) {
500
+ const ch = line[c];
501
+ if (open === 'sq') {
502
+ if (ch === "'")
503
+ open = null;
504
+ }
505
+ else if (open === 'ansi') {
506
+ if (ch === '\\')
507
+ c++;
508
+ else if (ch === "'")
509
+ open = null;
510
+ }
511
+ else if (ch === '\\')
512
+ c++;
513
+ else if (ch === '$' && line[c + 1] === "'") {
514
+ open = 'ansi';
515
+ c++;
516
+ }
517
+ else if (ch === "'")
518
+ open = 'sq';
519
+ }
520
+ }
521
+ return traced;
522
+ }
523
+ export function errorLine(stderr, sendable = () => true) {
456
524
  const lines = stderr.split(/\r?\n/);
525
+ const traced = traceLines(lines);
457
526
  for (let i = 0; i < lines.length; i++) {
458
527
  const raw = lines[i];
459
528
  const line = raw.trim();
460
- if (!line || FRAME.test(raw) || !ERRORISH.test(line))
529
+ if (!line || FRAME.test(raw) || traced[i] || !ERRORISH.test(line))
461
530
  continue;
462
531
  const next = lines.slice(i + 1, i + 4).find((l) => l.trim()) ?? '';
463
532
  if (CARET.test(next) || PY_FRAME.test(lines[i - 1] ?? ''))
464
533
  continue;
465
534
  if (/[;{]\s*$/.test(line) || (/^\s/.test(raw) && CODE_SHAPE.test(raw)))
466
535
  continue;
536
+ if (carriesCredential(line) || !sendable(line))
537
+ continue;
467
538
  const kept = stripCode(line).trim();
468
539
  if (kept && !kept.startsWith(`[${CODE_NOTE}`))
469
540
  return kept;
470
541
  }
471
542
  return null;
472
543
  }
544
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
545
+ const CREDENTIAL_FLAG = /(?:^|\s)(?:-u\s*\S*:\S|--user(?:=|\s+)\S*:\S|-p\s*\S|-b\s+\S|--[\w-]*(?:pass(?:word|wd|phrase)?|token|secret|api-?key|access-?key|auth\w*|cred\w*|cookie)(?:=|\s+)\S)|(?:^|\s)(?:-H|--header)(?:=|\s*)['"]?\s*[\w-]*(?:token|key|auth\w*|cookie|secret)[\w-]*\s*:/i;
546
+ const SECRET_URL = /\b(?:hooks\.slack\.com\/(?:services|workflows|triggers)\/|discord(?:app)?\.com\/api\/webhooks\/|[\w.-]*\.webhook\.office\.com\/|outlook\.office(?:365)?\.com\/webhook|hooks\.zapier\.com\/hooks\/|api\.telegram\.org\/bot)|[?&#;](?:[\w-]*(?:token|key|secret|sig|signature|password|passwd|pwd|auth|code|credential|session)[\w-]*|X-Amz-[\w-]+|X-Goog-[\w-]+|sv|se|sp|sr|st)=[^&\s]/i;
547
+ const ENV_ASSIGNMENT = /(?:^|[\s;'"(])[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*=[^\s=]/;
548
+ function carriesCredential(line) {
549
+ return (secretKindsIn(line).length > 0 ||
550
+ /[a-z][a-z0-9+.-]*:\/\/[^\s/@:]*:[^\s/@]+@/i.test(line) ||
551
+ /(?:^|[\s'"(])[^\s:@/'"(]+:[^\s@/]+@[\w-]+\.[\w.-]/.test(line) ||
552
+ /\b[\w.-]*(?:password|passwd|passphrase|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credentials?)[\w.-]*["']?\s*[:=]\s*\S/i.test(line) ||
553
+ /(?:\b|_)pass["']?\s*[:=]\s*\S/i.test(line) ||
554
+ /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}|\bauthorization\b\s*[:=]|\bcookie\b\s*[:=]/i.test(line) ||
555
+ CREDENTIAL_FLAG.test(line) ||
556
+ SECRET_URL.test(line) ||
557
+ ENV_ASSIGNMENT.test(line));
558
+ }
559
+ const SECRET_WORD = /\b(?:password|passwd|passphrase|secrets?|tokens?|api[\s_-]?keys?|credentials?|private[\s_-]?keys?|bearer|cookies?)\b/i;
560
+ function opaqueRun(line) {
561
+ for (const run of line.match(/[A-Za-z0-9_+/=-]{16,}/g) ?? []) {
562
+ const digit = /\d/.test(run);
563
+ const lower = /[a-z]/.test(run);
564
+ const upper = /[A-Z]/.test(run);
565
+ if (run.includes('/')) {
566
+ if (run.length >= 30 && digit && lower && upper)
567
+ return true;
568
+ }
569
+ else if ((digit && (lower || upper)) || (run.length >= 32 && lower && upper))
570
+ return true;
571
+ }
572
+ return false;
573
+ }
574
+ function plainWords(line) {
575
+ if (SHELL_TRACE.test(line) || carriesCredential(line))
576
+ return false;
577
+ if (/:\/\/|\bwww\./i.test(line) || /[=@`]/.test(line))
578
+ return false;
579
+ if (/(?:^|[\s([{"'])--?[A-Za-z]/.test(line))
580
+ return false;
581
+ return !SECRET_WORD.test(line) && !opaqueRun(line);
582
+ }
583
+ export function foldHome(text, home) {
584
+ const root = home.replace(/[\\/]+$/, '');
585
+ if (root.length < 2)
586
+ return text;
587
+ const escaped = root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
588
+ return text.replace(new RegExp(`${escaped}(?![\\w-])`, 'g'), '~');
589
+ }
590
+ export function lastWords(output) {
591
+ const lines = output
592
+ .replace(ANSI, '')
593
+ .split(/\r?\n/)
594
+ .map((l) => l.split('\r').pop() ?? '');
595
+ const traced = traceLines(lines);
596
+ let looked = 0;
597
+ let below = '';
598
+ for (let i = lines.length - 1; i >= 0 && looked < 20; i--) {
599
+ const raw = lines[i];
600
+ const line = raw.trim();
601
+ if (!line)
602
+ continue;
603
+ looked++;
604
+ const under = below;
605
+ below = raw;
606
+ if (traced[i] || FRAME.test(raw) || CARET.test(under) || PY_FRAME.test(lines[i - 1] ?? ''))
607
+ continue;
608
+ if (isCodeLine(raw) || /[;{]\s*$/.test(line) || (/^\s/.test(raw) && CODE_SHAPE.test(raw)))
609
+ continue;
610
+ if (!plainWords(line))
611
+ continue;
612
+ const kept = stripCode(line).trim();
613
+ if (kept && !kept.includes(`[${CODE_NOTE}`))
614
+ return kept;
615
+ }
616
+ return null;
617
+ }
618
+ export function setupReason(stderr, stdout) {
619
+ return errorLine(stderr, plainWords) ?? lastWords(stderr) ?? lastWords(stdout);
620
+ }
473
621
  export function pushRefusal(stderr) {
474
622
  const kept = stderr
475
623
  .split(/\r?\n/)
@@ -481,4 +629,23 @@ export function pushRefusal(stderr) {
481
629
  .filter((l) => secretKindsIn(l).length === 0);
482
630
  return kept.length ? kept.join(' ') : null;
483
631
  }
632
+ const WAITING_OPENER = /^(?:(?:i['’]m|i am|now|currently|still)\s+)*(?:still\s+)?waiting\s+(?:on|for|until)\b/i;
633
+ const LATER_CHECK = /\bi(?:['’]ll| will| am going to|['’]m going to)\s+(?:(?:then|now|come back and|go back and)\s+)?(?:check|look(?: at)?|report(?: back)?|post|update|share|confirm|verify|follow up|circle back|let you know|write(?: the)?|review|re-?run)\b/i;
634
+ const ON_SOMETHING_RUNNING = /\b(?:when|once|after|as soon as|until)\s+(?:it|they|this|that|those|the\s[\w .'/-]{1,60}?|my\s[\w .'/-]{1,60}?)\s+(?:finish(?:es|ed)?|complete[sd]?|(?:is|are)\s+done|come[s]?\s+back|return[s]?|report[s]?|land[s]?|pass(?:es)?|fail[s]?)\b|\b(?:is|are)\s+still\s+running\b|\bin the background\b/i;
635
+ const STILL_RUNNING = /^(?:the|my|our)\s[\w .'/-]{1,60}?\s(?:is|are)\s+still\s+running\b/i;
636
+ const NEGATED = /\b(?:not needed|no need|is not|are not|isn['’]t|aren['’]t|never)\b/i;
637
+ export function promisesLaterCheck(text) {
638
+ const sentences = text
639
+ .replace(/```[\s\S]*?```/g, ' ')
640
+ .split(/(?<=[.!?…])\s+|\n+/)
641
+ .map((s) => s.replace(/^[\s>*_#-]+/, '').trim())
642
+ .filter(Boolean);
643
+ for (const s of sentences.slice(-2)) {
644
+ if ((WAITING_OPENER.test(s) || STILL_RUNNING.test(s)) && !NEGATED.test(s))
645
+ return true;
646
+ if (LATER_CHECK.test(s) && ON_SOMETHING_RUNNING.test(s))
647
+ return true;
648
+ }
649
+ return false;
650
+ }
484
651
  //# sourceMappingURL=keep-local.js.map
@@ -0,0 +1,30 @@
1
+ export type PlanLimit = {
2
+ kind: 'plan';
3
+ resetsAt: string | null;
4
+ window?: string;
5
+ said?: string;
6
+ };
7
+ export declare function readClaudeLimit(stdout: string, now?: Date): PlanLimit | null;
8
+ export declare function resetFromSentence(text: string, now?: Date): string | null;
9
+ export declare function limitSentence(engineName: string, limit: PlanLimit, kept: boolean): string;
10
+ export type ActiveLimit = {
11
+ engine: string;
12
+ resetsAt: string | null;
13
+ window?: string;
14
+ until: string;
15
+ since: string;
16
+ };
17
+ export declare const UNKNOWN_RESET_WAIT_MS: number;
18
+ export declare const RESET_GRACE_MS: number;
19
+ export declare class LimitGate {
20
+ private readonly file;
21
+ private readonly now;
22
+ private limits;
23
+ constructor(file: string | null, now?: () => number);
24
+ static fileIn(runnerDir: string): string;
25
+ set(engine: string, limit: PlanLimit): ActiveLimit;
26
+ isLimited(engine: string): ActiveLimit | null;
27
+ active(): ActiveLimit[];
28
+ private prune;
29
+ private save;
30
+ }
package/dist/limit.js ADDED
@@ -0,0 +1,258 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
4
+ const PLAN_LIMIT_WORDS = /\bhit your (?:[\w-]+ ){0,2}limit\b|\busage limit\b|\b(?:session|weekly|5-hour|five-hour) limit\b/i;
5
+ function epochToIso(v) {
6
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0)
7
+ return null;
8
+ const ms = v < 1e12 ? v * 1000 : v;
9
+ const d = new Date(ms);
10
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
11
+ }
12
+ export function readClaudeLimit(stdout, now = new Date()) {
13
+ try {
14
+ let rejected = null;
15
+ let result = null;
16
+ let mainLoopRateError = false;
17
+ for (const line of stdout.split('\n')) {
18
+ const t = line.trim();
19
+ if (!t.startsWith('{'))
20
+ continue;
21
+ if (t.includes('"type":"assistant"')) {
22
+ if (t.includes('"parent_tool_use_id":null')) {
23
+ mainLoopRateError = t.includes('"error":"rate_limit"');
24
+ }
25
+ continue;
26
+ }
27
+ if (!t.includes('"type":"result"') && !t.includes('"type":"rate_limit_event"'))
28
+ continue;
29
+ let ev;
30
+ try {
31
+ ev = JSON.parse(t);
32
+ }
33
+ catch {
34
+ continue;
35
+ }
36
+ if (!isObj(ev))
37
+ continue;
38
+ if (ev.type === 'rate_limit_event' && isObj(ev.rate_limit_info)) {
39
+ const info = ev.rate_limit_info;
40
+ if (info.status !== 'rejected')
41
+ continue;
42
+ const window = typeof info.rateLimitType === 'string'
43
+ ? info.rateLimitType
44
+ : typeof info.rate_limit_type === 'string'
45
+ ? info.rate_limit_type
46
+ : undefined;
47
+ const unified = isObj(info.unifiedWindows) && window && isObj(info.unifiedWindows[window])
48
+ ? info.unifiedWindows[window]
49
+ : null;
50
+ rejected = {
51
+ resetsAt: epochToIso(info.resetsAt) ?? epochToIso(unified?.resetsAt),
52
+ ...(window ? { window } : {}),
53
+ };
54
+ }
55
+ else if (ev.type === 'result') {
56
+ result = ev;
57
+ }
58
+ }
59
+ if (!result || result.is_error !== true)
60
+ return null;
61
+ const text = typeof result.result === 'string' ? result.result.trim() : '';
62
+ if (result.api_error_status !== 429 && !mainLoopRateError)
63
+ return null;
64
+ if (!rejected && !PLAN_LIMIT_WORDS.test(text))
65
+ return null;
66
+ const resetsAt = rejected?.resetsAt ?? resetFromSentence(text, now);
67
+ return {
68
+ kind: 'plan',
69
+ resetsAt,
70
+ ...(rejected?.window ? { window: rejected.window } : {}),
71
+ ...(text ? { said: text.slice(0, 200) } : {}),
72
+ };
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
79
+ function knownZone(zone) {
80
+ if (!zone)
81
+ return null;
82
+ try {
83
+ new Intl.DateTimeFormat('en-US', { timeZone: zone });
84
+ return zone;
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
90
+ function wallParts(ms, zone) {
91
+ const parts = new Intl.DateTimeFormat('en-US', {
92
+ timeZone: zone,
93
+ hourCycle: 'h23',
94
+ year: 'numeric',
95
+ month: '2-digit',
96
+ day: '2-digit',
97
+ hour: '2-digit',
98
+ minute: '2-digit',
99
+ second: '2-digit',
100
+ }).formatToParts(new Date(ms));
101
+ const get = (type) => Number(parts.find((p) => p.type === type)?.value ?? '0');
102
+ return {
103
+ y: get('year'),
104
+ mo: get('month') - 1,
105
+ d: get('day'),
106
+ h: get('hour') % 24,
107
+ mi: get('minute'),
108
+ s: get('second'),
109
+ };
110
+ }
111
+ function zoneOffset(ms, zone) {
112
+ const p = wallParts(ms, zone);
113
+ return Date.UTC(p.y, p.mo, p.d, p.h, p.mi, p.s) - Math.floor(ms / 1000) * 1000;
114
+ }
115
+ function zonedInstant(y, mo, d, h, mi, zone) {
116
+ const guess = Date.UTC(y, mo, d, h, mi);
117
+ let at = guess - zoneOffset(guess, zone);
118
+ const again = guess - zoneOffset(at, zone);
119
+ if (again !== at)
120
+ at = again;
121
+ return at;
122
+ }
123
+ export function resetFromSentence(text, now = new Date()) {
124
+ const m = /\bresets\s+(?:at\s+)?(?:(?<mon>[A-Za-z]{3,9})\.?\s+(?<day>\d{1,2})(?:st|nd|rd|th)?,?\s+(?:at\s+)?)?(?<h>\d{1,2})(?::(?<mi>\d{2}))?\s*(?<ap>am|pm)?(?:\s*\((?<tz>[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+){0,2})\))?/i.exec(text);
125
+ if (!m?.groups)
126
+ return null;
127
+ const g = m.groups;
128
+ let h = Number(g.h);
129
+ const mi = g.mi ? Number(g.mi) : 0;
130
+ if (!Number.isFinite(h) || h > 23 || mi > 59)
131
+ return null;
132
+ const ap = g.ap?.toLowerCase();
133
+ if (ap) {
134
+ if (h < 1 || h > 12)
135
+ return null;
136
+ h = (h % 12) + (ap === 'pm' ? 12 : 0);
137
+ }
138
+ else if (!g.mi) {
139
+ return null;
140
+ }
141
+ const zone = knownZone(g.tz) ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
142
+ const nowMs = now.getTime();
143
+ const today = wallParts(nowMs, zone);
144
+ if (g.mon && g.day) {
145
+ const mo = MONTHS.indexOf(g.mon.slice(0, 3).toLowerCase());
146
+ const d = Number(g.day);
147
+ if (mo < 0 || d < 1 || d > 31)
148
+ return null;
149
+ let at = zonedInstant(today.y, mo, d, h, mi, zone);
150
+ if (at < nowMs - 183 * 86_400_000)
151
+ at = zonedInstant(today.y + 1, mo, d, h, mi, zone);
152
+ return new Date(at).toISOString();
153
+ }
154
+ let at = zonedInstant(today.y, today.mo, today.d, h, mi, zone);
155
+ if (at < nowMs - 60_000) {
156
+ const next = new Date(Date.UTC(today.y, today.mo, today.d + 1));
157
+ at = zonedInstant(next.getUTCFullYear(), next.getUTCMonth(), next.getUTCDate(), h, mi, zone);
158
+ }
159
+ return new Date(at).toISOString();
160
+ }
161
+ export function limitSentence(engineName, limit, kept) {
162
+ const when = limit.resetsAt ? `resets ${limit.resetsAt}` : 'it did not say when the limit resets';
163
+ return (`${engineName} was stopped by the plan's usage limit — ${when}. ` +
164
+ `The runner pushed nothing from this attempt and claims no new work for ${engineName} ` +
165
+ `until the reset. ` +
166
+ (kept
167
+ ? 'When the task runs again after the reset, this machine continues the same session from where it stopped instead of starting over.'
168
+ : 'Run the task again after the reset.'));
169
+ }
170
+ export const UNKNOWN_RESET_WAIT_MS = 15 * 60_000;
171
+ export const RESET_GRACE_MS = 2 * 60_000;
172
+ export class LimitGate {
173
+ file;
174
+ now;
175
+ limits = new Map();
176
+ constructor(file, now = () => Date.now()) {
177
+ this.file = file;
178
+ this.now = now;
179
+ if (!file || !existsSync(file))
180
+ return;
181
+ try {
182
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
183
+ if (!Array.isArray(raw))
184
+ return;
185
+ for (const r of raw) {
186
+ if (!isObj(r) || typeof r.engine !== 'string' || typeof r.until !== 'string')
187
+ continue;
188
+ if (Number.isNaN(Date.parse(r.until)))
189
+ continue;
190
+ this.limits.set(r.engine, {
191
+ engine: r.engine,
192
+ resetsAt: typeof r.resetsAt === 'string' ? r.resetsAt : null,
193
+ ...(typeof r.window === 'string' ? { window: r.window } : {}),
194
+ until: r.until,
195
+ since: typeof r.since === 'string' ? r.since : new Date(this.now()).toISOString(),
196
+ });
197
+ }
198
+ this.prune();
199
+ }
200
+ catch {
201
+ }
202
+ }
203
+ static fileIn(runnerDir) {
204
+ return join(runnerDir, 'limits.json');
205
+ }
206
+ set(engine, limit) {
207
+ const nowMs = this.now();
208
+ const reset = limit.resetsAt ? Date.parse(limit.resetsAt) : Number.NaN;
209
+ const untilMs = Number.isFinite(reset)
210
+ ? Math.max(reset + RESET_GRACE_MS, nowMs + 60_000)
211
+ : nowMs + UNKNOWN_RESET_WAIT_MS;
212
+ const active = {
213
+ engine,
214
+ resetsAt: limit.resetsAt,
215
+ ...(limit.window ? { window: limit.window } : {}),
216
+ until: new Date(untilMs).toISOString(),
217
+ since: new Date(nowMs).toISOString(),
218
+ };
219
+ this.limits.set(engine, active);
220
+ this.save();
221
+ return active;
222
+ }
223
+ isLimited(engine) {
224
+ this.prune();
225
+ return this.limits.get(engine) ?? null;
226
+ }
227
+ active() {
228
+ this.prune();
229
+ return [...this.limits.values()];
230
+ }
231
+ prune() {
232
+ const nowMs = this.now();
233
+ let changed = false;
234
+ for (const [engine, l] of this.limits) {
235
+ if (Date.parse(l.until) <= nowMs) {
236
+ this.limits.delete(engine);
237
+ changed = true;
238
+ }
239
+ }
240
+ if (changed)
241
+ this.save();
242
+ }
243
+ save() {
244
+ if (!this.file)
245
+ return;
246
+ try {
247
+ mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });
248
+ const tmp = `${this.file}.tmp`;
249
+ writeFileSync(tmp, `${JSON.stringify([...this.limits.values()], null, 2)}\n`, {
250
+ mode: 0o600,
251
+ });
252
+ renameSync(tmp, this.file);
253
+ }
254
+ catch {
255
+ }
256
+ }
257
+ }
258
+ //# sourceMappingURL=limit.js.map
package/dist/locks.d.ts CHANGED
@@ -2,3 +2,17 @@ export type KeyedMutex = {
2
2
  run<T>(key: string, fn: () => Promise<T>): Promise<T>;
3
3
  };
4
4
  export declare function createKeyedMutex(): KeyedMutex;
5
+ export declare function repoLockKey(repo: string): string;
6
+ export declare function heavyLockDir(runnerDir: string, repo: string): string;
7
+ export type HeavyLockOptions = {
8
+ label?: string;
9
+ pollMs?: number;
10
+ maxWaitMs?: number;
11
+ onWait?: (holder: number | null) => void;
12
+ now?: () => number;
13
+ sleep?: (ms: number) => Promise<void>;
14
+ };
15
+ export declare function acquireHeavyLock(lockDir: string, opts?: HeavyLockOptions): Promise<() => void>;
16
+ export declare function withHeavyLock<T>(lockDir: string, fn: () => Promise<T>, opts?: HeavyLockOptions): Promise<T>;
17
+ export declare function heavyScript(): string;
18
+ export declare function ensureHeavyScript(runnerDir: string): string | null;