@cydm/pie 2.8.0 → 2.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/dist/builtin/extensions/ask-user/index.js +4 -3
- package/dist/builtin/extensions/cron/index.js +265 -31
- package/dist/builtin/extensions/im-forward/index.js +13 -2
- package/dist/builtin/extensions/memory/index.js +275 -83
- package/dist/builtin/extensions/memory/package.json +2 -1
- package/dist/builtin/extensions/plan-mode/index.js +4 -3
- package/dist/builtin/extensions/subagent/index.js +6 -5
- package/dist/builtin/extensions/todo/index.js +4 -3
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
- package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
- package/dist/chunks/{chunk-JNOFHHLZ.js → chunk-3BC5KGDQ.js} +383 -185
- package/dist/chunks/chunk-3NHP7HK5.js +298 -0
- package/dist/chunks/chunk-6DNYGVZP.js +278 -0
- package/dist/chunks/{chunk-NEES4EBX.js → chunk-GDIYSMTS.js} +6 -4
- package/dist/chunks/{chunk-HGC25NYB.js → chunk-GH4VW2OT.js} +1 -1
- package/dist/chunks/{chunk-5353DEEC.js → chunk-ILUHTKF3.js} +20 -1
- package/dist/chunks/{chunk-LJXHECZ7.js → chunk-PK72LVWQ.js} +13867 -19759
- package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
- package/dist/chunks/chunk-YRR6C43W.js +1740 -0
- package/dist/chunks/config-74AUVDLT.js +46 -0
- package/dist/chunks/model-registry-LI5THXV4.js +17 -0
- package/dist/chunks/src-66XSMIAM.js +134 -0
- package/dist/chunks/src-BPSQMSSC.js +431 -0
- package/dist/chunks/src-OPPYTPWG.js +285 -0
- package/dist/chunks/{src-5XOKRS6F.js → src-YG5M2H44.js} +2 -2
- package/dist/chunks/{test-stream-5SDHKKDB.js → test-stream-JBWXKOQA.js} +1 -1
- package/dist/cli.js +970 -2283
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -409,6 +409,24 @@ pie "summarize this file" --json-output
|
|
|
409
409
|
pie "continue previous task" --session-id my-session
|
|
410
410
|
```
|
|
411
411
|
|
|
412
|
+
### Resuming Sessions From Another Directory
|
|
413
|
+
|
|
414
|
+
Sessions record the directory they were created in. When you resume a
|
|
415
|
+
session that belongs to another project (by `--session-id` or the
|
|
416
|
+
interactive `/resume` picker), Pie restarts itself in that project's
|
|
417
|
+
directory BEFORE loading anything cwd-sensitive (AGENTS.md discovery,
|
|
418
|
+
project skills, project memory) — a resumed session behaves exactly like
|
|
419
|
+
a fresh start in its project. A one-line banner shows the switch, and an
|
|
420
|
+
OSC 7 escape sequence tells supporting terminals where new panes belong.
|
|
421
|
+
|
|
422
|
+
- The shell you launched from keeps its own cwd (Unix shells cannot be
|
|
423
|
+
driven by child processes); the printed banner is the source of truth.
|
|
424
|
+
- `--no-cd` skips the restart (scripted/CI use).
|
|
425
|
+
- `session.resume.chdir: false` in `~/.pie/settings.json` disables it
|
|
426
|
+
permanently.
|
|
427
|
+
- If the recorded directory no longer exists, Pie warns and resumes in
|
|
428
|
+
the current directory instead of failing.
|
|
429
|
+
|
|
412
430
|
### Machine-Readable Output (Agents And Hosts)
|
|
413
431
|
|
|
414
432
|
Every management command (`sessions`, `doctor`, `models`, `extensions`, `permissions`, `capabilities`) emits one compact JSON envelope when given `--json`:
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
createAskUserCapability
|
|
4
|
-
} from "../../../chunks/chunk-
|
|
5
|
-
import "../../../chunks/chunk-
|
|
6
|
-
import "../../../chunks/chunk-
|
|
4
|
+
} from "../../../chunks/chunk-PK72LVWQ.js";
|
|
5
|
+
import "../../../chunks/chunk-RSL7E4R7.js";
|
|
6
|
+
import "../../../chunks/chunk-GH4VW2OT.js";
|
|
7
|
+
import "../../../chunks/chunk-3BC5KGDQ.js";
|
|
7
8
|
import "../../../chunks/chunk-XXGYUYXI.js";
|
|
8
9
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
9
10
|
|
|
@@ -6,7 +6,7 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
|
6
6
|
|
|
7
7
|
// builtin/extensions/cron/index.ts
|
|
8
8
|
import * as path4 from "node:path";
|
|
9
|
-
import * as
|
|
9
|
+
import * as fs4 from "node:fs";
|
|
10
10
|
import { homedir } from "node:os";
|
|
11
11
|
|
|
12
12
|
// builtin/extensions/cron/store.ts
|
|
@@ -70,6 +70,20 @@ function nextTime(s, after) {
|
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
// builtin/extensions/cron/store.ts
|
|
73
|
+
var PROCESS_SESSION_ID = "process";
|
|
74
|
+
function parseProcessCommand(job) {
|
|
75
|
+
if (job.sessionId !== PROCESS_SESSION_ID) return null;
|
|
76
|
+
try {
|
|
77
|
+
const parsed = JSON.parse(job.prompt);
|
|
78
|
+
if (!parsed || !Array.isArray(parsed.command) || parsed.command.length === 0 || !parsed.command.every((part) => typeof part === "string" && part.length > 0) || parsed.command.length > 32 || parsed.command.some((part) => part.length > 4096) || parsed.managedBy !== void 0 && (typeof parsed.managedBy !== "string" || parsed.managedBy.length > 64)) return null;
|
|
79
|
+
return parsed;
|
|
80
|
+
} catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function isProcessJob(job) {
|
|
85
|
+
return job.sessionId === PROCESS_SESSION_ID && parseProcessCommand(job) !== null;
|
|
86
|
+
}
|
|
73
87
|
var Store = class {
|
|
74
88
|
constructor(dir) {
|
|
75
89
|
this.dir = dir;
|
|
@@ -123,6 +137,9 @@ var Store = class {
|
|
|
123
137
|
const ids = /* @__PURE__ */ new Set();
|
|
124
138
|
for (const j of s.jobs) {
|
|
125
139
|
if (!j || typeof j.id !== "string" || ids.has(j.id) || typeof j.sessionId !== "string" || !j.sessionId || j.sessionId.length > 256 || typeof j.cwd !== "string" || !path.isAbsolute(j.cwd) || typeof j.prompt !== "string" || !j.prompt.trim() || j.prompt.length > 16e3 || typeof j.enabled !== "boolean" || !["ready", "running", "blocked"].includes(j.state) || j.remaining !== void 0 && (!Number.isSafeInteger(j.remaining) || j.remaining < 0 || j.remaining > 1e3) || j.next !== null && !Number.isSafeInteger(j.next)) throw new Error("invalid cron job; manual recovery required");
|
|
140
|
+
if (j.sessionId === PROCESS_SESSION_ID) {
|
|
141
|
+
if (!parseProcessCommand(j)) throw new Error("invalid process cron job; manual recovery required");
|
|
142
|
+
}
|
|
126
143
|
ids.add(j.id);
|
|
127
144
|
validateSchedule(j.schedule);
|
|
128
145
|
}
|
|
@@ -170,6 +187,7 @@ var Store = class {
|
|
|
170
187
|
}
|
|
171
188
|
add(sessionId, cwd, prompt, schedule, now = Date.now()) {
|
|
172
189
|
if (!sessionId || sessionId.length > 256) throw new Error("an existing session is required");
|
|
190
|
+
if (sessionId === PROCESS_SESSION_ID) throw new Error("session id is reserved for process jobs");
|
|
173
191
|
if (typeof prompt !== "string" || !prompt.trim() || prompt.length > 16e3) throw new Error("prompt must contain 1..16000 characters");
|
|
174
192
|
const validated = validateSchedule(schedule), next = nextTime(validated, now);
|
|
175
193
|
if (next === null) throw new Error("at must be in the future");
|
|
@@ -191,6 +209,43 @@ var Store = class {
|
|
|
191
209
|
return job;
|
|
192
210
|
});
|
|
193
211
|
}
|
|
212
|
+
/** Register a process job: detached command execution, no session binding.
|
|
213
|
+
* Replaces any existing job from the same manager so `schedule on` is
|
|
214
|
+
* idempotent (one managed job per manager). A RUNNING job is never
|
|
215
|
+
* replaced: removing its reservation would let another execution start
|
|
216
|
+
* while the original worker is still alive (single-outstanding invariant). */
|
|
217
|
+
addProcess(command, managedBy, cwd, schedule, now = Date.now()) {
|
|
218
|
+
const validated = validateSchedule(schedule), next = nextTime(validated, now);
|
|
219
|
+
if (next === null) throw new Error("at must be in the future");
|
|
220
|
+
const count = validated.count;
|
|
221
|
+
const probe = {
|
|
222
|
+
id: randomUUID(),
|
|
223
|
+
sessionId: PROCESS_SESSION_ID,
|
|
224
|
+
cwd: fs.realpathSync(cwd),
|
|
225
|
+
prompt: JSON.stringify({ command, managedBy }),
|
|
226
|
+
schedule: validated,
|
|
227
|
+
enabled: true,
|
|
228
|
+
next,
|
|
229
|
+
state: "ready",
|
|
230
|
+
...count !== void 0 ? { remaining: count } : {}
|
|
231
|
+
};
|
|
232
|
+
if (!parseProcessCommand(probe)) throw new Error("invalid process command (1..32 args, each 1..4096 chars, no NUL bytes)");
|
|
233
|
+
if (command.some((part) => part.includes("\0"))) throw new Error("process command arguments must not contain NUL bytes");
|
|
234
|
+
if (probe.prompt.length > 16e3) throw new Error("process command exceeds the 16000-character job budget");
|
|
235
|
+
const job = { ...probe };
|
|
236
|
+
return this.transaction((s) => {
|
|
237
|
+
const existing = s.jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
|
|
238
|
+
if (existing?.state === "running") throw new Error("managed job is currently running; try again after it finishes");
|
|
239
|
+
s.jobs = s.jobs.filter((j) => j !== existing);
|
|
240
|
+
if (s.jobs.length >= 100) throw new Error("maximum 100 jobs");
|
|
241
|
+
s.jobs.push(job);
|
|
242
|
+
return job;
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/** Find the managed process job for a manager identity, if present. */
|
|
246
|
+
findProcess(managedBy) {
|
|
247
|
+
return this.read().jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
|
|
248
|
+
}
|
|
194
249
|
change(id, action, now = Date.now()) {
|
|
195
250
|
this.transaction((s) => {
|
|
196
251
|
const j = s.jobs.find((j2) => j2.id === id);
|
|
@@ -231,15 +286,30 @@ function complete(job, error, now = Date.now()) {
|
|
|
231
286
|
job.next = "at" in job.schedule ? null : nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
|
|
232
287
|
if (job.next === null) job.enabled = false;
|
|
233
288
|
}
|
|
289
|
+
function completeInterrupted(job, error, now = Date.now()) {
|
|
290
|
+
if (!isProcessJob(job)) {
|
|
291
|
+
complete(job, error, now);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if ("at" in job.schedule) {
|
|
295
|
+
complete(job, `interrupted at shutdown; one-shot outcome uncertain \u2014 ${error}`.slice(0, 500), now);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
job.state = "ready";
|
|
299
|
+
job.error = `interrupted at shutdown; retried automatically: ${error.slice(0, 400)}`;
|
|
300
|
+
job.next = nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
|
|
301
|
+
if (job.next === null) job.enabled = false;
|
|
302
|
+
}
|
|
234
303
|
|
|
235
304
|
// builtin/extensions/cron/runtime.ts
|
|
236
|
-
import * as
|
|
305
|
+
import * as fs3 from "node:fs";
|
|
237
306
|
import * as path3 from "node:path";
|
|
238
307
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
239
308
|
|
|
240
309
|
// builtin/extensions/cron/worker.ts
|
|
241
310
|
import { spawn } from "node:child_process";
|
|
242
311
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
312
|
+
import * as fs2 from "node:fs";
|
|
243
313
|
import * as path2 from "node:path";
|
|
244
314
|
import { StringDecoder } from "node:string_decoder";
|
|
245
315
|
function runWorker(job, signal, cli = process.argv[1], configDir) {
|
|
@@ -341,6 +411,128 @@ function runWorker(job, signal, cli = process.argv[1], configDir) {
|
|
|
341
411
|
if (signal.aborted) stop();
|
|
342
412
|
});
|
|
343
413
|
}
|
|
414
|
+
function processJobEnv(configDir) {
|
|
415
|
+
const allow = ["PATH", "PATHEXT", "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "LANG", "LC_ALL", "TERM", "TMPDIR", "TEMP", "TMP", "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"];
|
|
416
|
+
const env = {};
|
|
417
|
+
for (const key of allow) {
|
|
418
|
+
const value = process.env[key];
|
|
419
|
+
if (value !== void 0) env[key] = value;
|
|
420
|
+
}
|
|
421
|
+
env.PIE_CRON_ROLE = "worker";
|
|
422
|
+
if (configDir) env.PIE_CODING_AGENT_DIR = configDir;
|
|
423
|
+
return env;
|
|
424
|
+
}
|
|
425
|
+
var ProcessWorkerCancelled = class extends Error {
|
|
426
|
+
aborted = true;
|
|
427
|
+
constructor(message) {
|
|
428
|
+
super(message);
|
|
429
|
+
this.name = "ProcessWorkerCancelled";
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir, signal, configDir) {
|
|
433
|
+
return new Promise((resolve3, reject) => {
|
|
434
|
+
const dir = logDir ?? path2.join(process.cwd(), "cron");
|
|
435
|
+
const logFile = path2.join(dir, "process.log");
|
|
436
|
+
try {
|
|
437
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
438
|
+
} catch {
|
|
439
|
+
}
|
|
440
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
441
|
+
const header = `[${stamp}] job=${job.id} cwd=${cwd} cmd=${JSON.stringify(command.command)}
|
|
442
|
+
`;
|
|
443
|
+
try {
|
|
444
|
+
fs2.appendFileSync(logFile, header);
|
|
445
|
+
} catch {
|
|
446
|
+
}
|
|
447
|
+
let out;
|
|
448
|
+
try {
|
|
449
|
+
out = fs2.openSync(logFile, "a");
|
|
450
|
+
} catch {
|
|
451
|
+
}
|
|
452
|
+
let child;
|
|
453
|
+
let settled = false;
|
|
454
|
+
let failure;
|
|
455
|
+
let hostCancelled = false;
|
|
456
|
+
let killTimer;
|
|
457
|
+
let deadlineTimer;
|
|
458
|
+
const ABORT_FAILURE = "worker interrupted; outcome uncertain";
|
|
459
|
+
const terminate = () => {
|
|
460
|
+
if (settled) return;
|
|
461
|
+
try {
|
|
462
|
+
child?.kill();
|
|
463
|
+
} catch {
|
|
464
|
+
}
|
|
465
|
+
killTimer ??= setTimeout(() => {
|
|
466
|
+
try {
|
|
467
|
+
child?.kill("SIGKILL");
|
|
468
|
+
} catch {
|
|
469
|
+
}
|
|
470
|
+
}, 5e3);
|
|
471
|
+
killTimer.unref();
|
|
472
|
+
};
|
|
473
|
+
const stop = () => {
|
|
474
|
+
if (settled) return;
|
|
475
|
+
hostCancelled = true;
|
|
476
|
+
failure ??= ABORT_FAILURE;
|
|
477
|
+
terminate();
|
|
478
|
+
};
|
|
479
|
+
try {
|
|
480
|
+
child = spawn(command.command[0], command.command.slice(1), {
|
|
481
|
+
cwd,
|
|
482
|
+
env: processJobEnv(configDir),
|
|
483
|
+
stdio: ["ignore", out ?? "ignore", out ?? "ignore"],
|
|
484
|
+
windowsHide: true
|
|
485
|
+
});
|
|
486
|
+
} catch (error) {
|
|
487
|
+
if (out !== void 0) {
|
|
488
|
+
try {
|
|
489
|
+
fs2.closeSync(out);
|
|
490
|
+
} catch {
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
const cleanup = () => {
|
|
497
|
+
if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
|
|
498
|
+
if (killTimer !== void 0) clearTimeout(killTimer);
|
|
499
|
+
signal?.removeEventListener("abort", stop);
|
|
500
|
+
if (out !== void 0) {
|
|
501
|
+
try {
|
|
502
|
+
fs2.closeSync(out);
|
|
503
|
+
} catch {
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
deadlineTimer = setTimeout(() => {
|
|
508
|
+
if (settled) return;
|
|
509
|
+
failure = `process job exceeded ${deadlineMs}ms`;
|
|
510
|
+
terminate();
|
|
511
|
+
}, deadlineMs);
|
|
512
|
+
deadlineTimer.unref();
|
|
513
|
+
if (signal?.aborted) stop();
|
|
514
|
+
else signal?.addEventListener("abort", stop, { once: true });
|
|
515
|
+
child.on("error", (error) => {
|
|
516
|
+
failure = error.message;
|
|
517
|
+
});
|
|
518
|
+
child.on("close", (code) => {
|
|
519
|
+
if (settled) return;
|
|
520
|
+
settled = true;
|
|
521
|
+
cleanup();
|
|
522
|
+
try {
|
|
523
|
+
fs2.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
|
|
524
|
+
`);
|
|
525
|
+
} catch {
|
|
526
|
+
}
|
|
527
|
+
if (hostCancelled) {
|
|
528
|
+
reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (failure || code !== 0) reject(new Error(failure ?? `process exited ${code}`));
|
|
532
|
+
else resolve3();
|
|
533
|
+
});
|
|
534
|
+
});
|
|
535
|
+
}
|
|
344
536
|
|
|
345
537
|
// builtin/extensions/cron/runtime.ts
|
|
346
538
|
var delay = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
@@ -356,17 +548,19 @@ function defaultProcessAlive(pid) {
|
|
|
356
548
|
}
|
|
357
549
|
}
|
|
358
550
|
var Runtime = class {
|
|
359
|
-
constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive) {
|
|
551
|
+
constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive, executeProcess = runProcessWorker) {
|
|
360
552
|
this.ctx = ctx;
|
|
361
553
|
this.store = store;
|
|
362
554
|
this.execute = execute;
|
|
363
555
|
this.processAlive = processAlive;
|
|
364
|
-
this.
|
|
556
|
+
this.executeProcess = executeProcess;
|
|
557
|
+
this.cwd = fs3.realpathSync(ctx.cwd);
|
|
365
558
|
}
|
|
366
559
|
ctx;
|
|
367
560
|
store;
|
|
368
561
|
execute;
|
|
369
562
|
processAlive;
|
|
563
|
+
executeProcess;
|
|
370
564
|
id = randomUUID3();
|
|
371
565
|
sessionId = null;
|
|
372
566
|
leader = false;
|
|
@@ -377,6 +571,7 @@ var Runtime = class {
|
|
|
377
571
|
polling = false;
|
|
378
572
|
timer;
|
|
379
573
|
abort = new AbortController();
|
|
574
|
+
processAbort = new AbortController();
|
|
380
575
|
worker;
|
|
381
576
|
cwd;
|
|
382
577
|
notices = /* @__PURE__ */ new Set();
|
|
@@ -410,7 +605,7 @@ var Runtime = class {
|
|
|
410
605
|
this.timer.unref();
|
|
411
606
|
}
|
|
412
607
|
markUnsafe() {
|
|
413
|
-
|
|
608
|
+
fs3.mkdirSync(path3.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
|
|
414
609
|
}
|
|
415
610
|
coordinatorDir() {
|
|
416
611
|
return path3.join(this.store.dir, "scheduler.lock");
|
|
@@ -420,9 +615,9 @@ var Runtime = class {
|
|
|
420
615
|
}
|
|
421
616
|
readCoordinatorOwner() {
|
|
422
617
|
try {
|
|
423
|
-
const file = this.coordinatorOwnerFile(), stat =
|
|
618
|
+
const file = this.coordinatorOwnerFile(), stat = fs3.lstatSync(file);
|
|
424
619
|
if (!stat.isFile() || stat.size > 4096) return void 0;
|
|
425
|
-
const raw =
|
|
620
|
+
const raw = fs3.readFileSync(file, "utf8"), value = JSON.parse(raw);
|
|
426
621
|
if (value?.version !== 1 || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.instanceId !== "string" || !value.instanceId || value.instanceId.length > 128 || !Number.isSafeInteger(value.createdAt)) return void 0;
|
|
427
622
|
return { value, raw };
|
|
428
623
|
} catch {
|
|
@@ -444,26 +639,26 @@ var Runtime = class {
|
|
|
444
639
|
}
|
|
445
640
|
withCoordinatorMutex(fn) {
|
|
446
641
|
const lock = path3.join(this.store.dir, "write.lock");
|
|
447
|
-
|
|
642
|
+
fs3.mkdirSync(lock, { mode: 448 });
|
|
448
643
|
try {
|
|
449
644
|
return fn();
|
|
450
645
|
} finally {
|
|
451
|
-
|
|
646
|
+
fs3.rmdirSync(lock);
|
|
452
647
|
}
|
|
453
648
|
}
|
|
454
649
|
acquireCoordinator() {
|
|
455
650
|
const dir = this.coordinatorDir();
|
|
456
|
-
|
|
651
|
+
fs3.mkdirSync(dir, { mode: 448 });
|
|
457
652
|
const owner = { version: 1, pid: process.pid, instanceId: this.id, createdAt: Date.now() };
|
|
458
653
|
try {
|
|
459
|
-
|
|
654
|
+
fs3.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
|
|
460
655
|
} catch (error) {
|
|
461
656
|
try {
|
|
462
|
-
|
|
657
|
+
fs3.unlinkSync(this.coordinatorOwnerFile());
|
|
463
658
|
} catch {
|
|
464
659
|
}
|
|
465
660
|
try {
|
|
466
|
-
|
|
661
|
+
fs3.rmdirSync(dir);
|
|
467
662
|
} catch {
|
|
468
663
|
}
|
|
469
664
|
throw error;
|
|
@@ -491,16 +686,16 @@ var Runtime = class {
|
|
|
491
686
|
const latest = this.readCoordinatorOwner();
|
|
492
687
|
if (!latest || latest.raw !== held.raw) return false;
|
|
493
688
|
try {
|
|
494
|
-
|
|
495
|
-
|
|
689
|
+
fs3.unlinkSync(this.coordinatorOwnerFile());
|
|
690
|
+
fs3.rmdirSync(this.coordinatorDir());
|
|
496
691
|
return true;
|
|
497
692
|
} catch {
|
|
498
693
|
return false;
|
|
499
694
|
}
|
|
500
695
|
}
|
|
501
696
|
releaseCoordinator() {
|
|
502
|
-
|
|
503
|
-
|
|
697
|
+
fs3.rmSync(this.coordinatorOwnerFile(), { force: true });
|
|
698
|
+
fs3.rmdirSync(this.coordinatorDir());
|
|
504
699
|
this.leader = false;
|
|
505
700
|
}
|
|
506
701
|
persistOwner(sessionId) {
|
|
@@ -534,6 +729,7 @@ var Runtime = class {
|
|
|
534
729
|
if (!this.stopped && generation === this.binding) this.register(sessionId);
|
|
535
730
|
}
|
|
536
731
|
notify(job) {
|
|
732
|
+
if (isProcessJob(job)) return;
|
|
537
733
|
if (job.sessionId !== this.sessionId || !job.error) return;
|
|
538
734
|
const key = job.id + job.error;
|
|
539
735
|
if (!this.notices.has(key)) {
|
|
@@ -542,11 +738,18 @@ var Runtime = class {
|
|
|
542
738
|
}
|
|
543
739
|
}
|
|
544
740
|
flushCompletions() {
|
|
545
|
-
for (const [id,
|
|
741
|
+
for (const [id, entry] of this.completions) {
|
|
742
|
+
const { error, cancelled } = entry;
|
|
546
743
|
try {
|
|
547
744
|
this.store.transaction((state) => {
|
|
548
745
|
const job = state.jobs.find((item) => item.id === id);
|
|
549
|
-
if (job?.state === "running")
|
|
746
|
+
if (job?.state === "running") {
|
|
747
|
+
if (cancelled && error !== void 0 && isProcessJob(job) && job.target === "worker") {
|
|
748
|
+
completeInterrupted(job, error);
|
|
749
|
+
} else {
|
|
750
|
+
complete(job, error);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
550
753
|
});
|
|
551
754
|
this.completions.delete(id);
|
|
552
755
|
} catch (failure) {
|
|
@@ -555,14 +758,15 @@ var Runtime = class {
|
|
|
555
758
|
}
|
|
556
759
|
}
|
|
557
760
|
}
|
|
558
|
-
finish(id, error) {
|
|
559
|
-
this.completions.set(id, error);
|
|
761
|
+
finish(id, error, cancelled) {
|
|
762
|
+
this.completions.set(id, { error, cancelled });
|
|
560
763
|
this.flushCompletions();
|
|
561
764
|
}
|
|
562
765
|
async poll(now = Date.now()) {
|
|
563
766
|
if (this.stopped || this.polling || !this.initialized) return;
|
|
564
|
-
if (
|
|
767
|
+
if (fs3.existsSync(path3.join(this.store.dir, "unsafe.lock"))) {
|
|
565
768
|
this.abort.abort();
|
|
769
|
+
this.processAbort.abort();
|
|
566
770
|
this.ctx.ui.setStatus?.("cron", void 0);
|
|
567
771
|
return;
|
|
568
772
|
}
|
|
@@ -585,6 +789,7 @@ var Runtime = class {
|
|
|
585
789
|
}
|
|
586
790
|
});
|
|
587
791
|
let delivery, launch;
|
|
792
|
+
let processLaunch;
|
|
588
793
|
this.store.transaction((state2) => {
|
|
589
794
|
if (this.recovering) {
|
|
590
795
|
for (const job of state2.jobs) {
|
|
@@ -595,6 +800,7 @@ var Runtime = class {
|
|
|
595
800
|
}
|
|
596
801
|
state2.owners[this.id] = { sessionId: this.sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
|
|
597
802
|
for (const job of state2.jobs) {
|
|
803
|
+
if (isProcessJob(job)) continue;
|
|
598
804
|
const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
|
|
599
805
|
if (this.leader && job.state === "running" && job.target === "worker" && owners.length) this.abort.abort();
|
|
600
806
|
if (job.enabled && owners.length > 1 && job.state !== "running") complete(job, "duplicate participating session owners; close duplicate and resume job");
|
|
@@ -625,6 +831,13 @@ var Runtime = class {
|
|
|
625
831
|
if (this.leader && !state2.jobs.some((job) => job.state === "running")) {
|
|
626
832
|
const due = state2.jobs.filter((job) => job.enabled && job.state === "ready" && job.next !== null && job.next <= now).sort((a, b) => a.next - b.next);
|
|
627
833
|
for (const job of due) {
|
|
834
|
+
if (isProcessJob(job)) {
|
|
835
|
+
job.state = "running";
|
|
836
|
+
job.occurrence = job.next;
|
|
837
|
+
job.target = "worker";
|
|
838
|
+
processLaunch = job;
|
|
839
|
+
break;
|
|
840
|
+
}
|
|
628
841
|
if (state2.jobs.some((other) => other.enabled && other.sessionId === job.sessionId && other.state === "blocked")) continue;
|
|
629
842
|
const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
|
|
630
843
|
if (owners.length > 1) {
|
|
@@ -647,7 +860,7 @@ var Runtime = class {
|
|
|
647
860
|
this.recovering = false;
|
|
648
861
|
if (delivery) {
|
|
649
862
|
const job = delivery;
|
|
650
|
-
const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !
|
|
863
|
+
const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !fs3.existsSync(path3.join(this.store.dir, "unsafe.lock")) && Object.values(this.store.read().owners).filter((owner) => owner.sessionId === job.sessionId).length === 1);
|
|
651
864
|
let error;
|
|
652
865
|
const content = `[Cron job=${job.id} scheduledAt=${job.occurrence}]
|
|
653
866
|
${job.prompt}`;
|
|
@@ -667,7 +880,7 @@ ${job.prompt}`;
|
|
|
667
880
|
if (launch) {
|
|
668
881
|
const job = launch;
|
|
669
882
|
const latest = this.store.read();
|
|
670
|
-
if (this.stopped ||
|
|
883
|
+
if (this.stopped || fs3.existsSync(path3.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
|
|
671
884
|
this.finish(job.id, "ownership changed before worker launch; inspect before resuming");
|
|
672
885
|
return;
|
|
673
886
|
}
|
|
@@ -679,8 +892,19 @@ ${job.prompt}`;
|
|
|
679
892
|
}
|
|
680
893
|
});
|
|
681
894
|
}
|
|
895
|
+
if (processLaunch) {
|
|
896
|
+
const job = processLaunch;
|
|
897
|
+
const command = parseProcessCommand(job);
|
|
898
|
+
this.processAbort = new AbortController();
|
|
899
|
+
this.worker = this.executeProcess(job, command, job.cwd, 30 * 60 * 1e3, this.store.dir, this.processAbort.signal, path3.dirname(this.store.dir)).then(() => this.finish(job.id), (error) => this.finish(job.id, String(error), error?.aborted === true)).catch(() => {
|
|
900
|
+
try {
|
|
901
|
+
this.markUnsafe();
|
|
902
|
+
} catch {
|
|
903
|
+
}
|
|
904
|
+
});
|
|
905
|
+
}
|
|
682
906
|
const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
|
|
683
|
-
this.ctx.ui.setStatus?.("cron", this.leader && enabled.some((job) => job.sessionId === this.sessionId) ? `cron: ${enabled.length} enabled, ${enabled.filter((job) => job.state === "blocked").length} blocked` : void 0);
|
|
907
|
+
this.ctx.ui.setStatus?.("cron", this.leader && enabled.some((job) => job.sessionId === this.sessionId || isProcessJob(job)) ? `cron: ${enabled.length} enabled, ${enabled.filter((job) => job.state === "blocked").length} blocked` : void 0);
|
|
684
908
|
for (const job of state.jobs) this.notify(job);
|
|
685
909
|
} catch {
|
|
686
910
|
this.ctx.ui.setStatus?.("cron", void 0);
|
|
@@ -692,14 +916,21 @@ ${job.prompt}`;
|
|
|
692
916
|
this.stopped = true;
|
|
693
917
|
clearInterval(this.timer);
|
|
694
918
|
this.abort.abort();
|
|
919
|
+
this.processAbort.abort();
|
|
695
920
|
await this.worker;
|
|
696
921
|
while (this.polling) await delay(10);
|
|
697
922
|
for (let attempt = 0; ; attempt++) {
|
|
698
923
|
try {
|
|
699
924
|
this.store.transaction((state) => {
|
|
700
|
-
for (const [id,
|
|
925
|
+
for (const [id, entry] of this.completions) {
|
|
701
926
|
const job = state.jobs.find((item) => item.id === id);
|
|
702
|
-
if (job?.state === "running")
|
|
927
|
+
if (job?.state === "running") {
|
|
928
|
+
if (entry.cancelled && entry.error !== void 0 && isProcessJob(job) && job.target === "worker") {
|
|
929
|
+
completeInterrupted(job, entry.error);
|
|
930
|
+
} else {
|
|
931
|
+
complete(job, entry.error);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
703
934
|
}
|
|
704
935
|
delete state.owners[this.id];
|
|
705
936
|
for (const job of state.jobs) {
|
|
@@ -763,7 +994,7 @@ function cron(ctx) {
|
|
|
763
994
|
if (!state.jobs.some((j) => j.sessionId === runtime.sessionId && (j.enabled || j.state === "running"))) return;
|
|
764
995
|
const duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
|
|
765
996
|
const worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
|
|
766
|
-
if (!startupError && runtime.ready && !duplicates && !worker && !
|
|
997
|
+
if (!startupError && runtime.ready && !duplicates && !worker && !fs4.existsSync(path4.join(store.dir, "unsafe.lock"))) return;
|
|
767
998
|
} catch {
|
|
768
999
|
}
|
|
769
1000
|
ctx.ui.notify("cron: session ownership is uncertain or duplicated; input blocked. Close the duplicate/worker and inspect /tools/cron.", "warning");
|
|
@@ -784,7 +1015,7 @@ function cron(ctx) {
|
|
|
784
1015
|
});
|
|
785
1016
|
const run = (action, id, prompt, schedule) => {
|
|
786
1017
|
if (startupError && action !== "list") throw new Error(`cron unavailable: ${startupError}; see docs/cron.md recovery`);
|
|
787
|
-
if (action === "list") return JSON.stringify({ ...store.read(), recoveryRequired:
|
|
1018
|
+
if (action === "list") return JSON.stringify({ ...store.read(), recoveryRequired: fs4.existsSync(path4.join(store.dir, "unsafe.lock")), coordinatorPresent: fs4.existsSync(path4.join(store.dir, "scheduler.lock")) }, null, 2);
|
|
788
1019
|
if (action === "add") {
|
|
789
1020
|
if (!runtime.ready || !runtime.sessionId) throw new Error("wait for an existing session to load and register");
|
|
790
1021
|
return JSON.stringify({
|
|
@@ -811,7 +1042,7 @@ function cron(ctx) {
|
|
|
811
1042
|
ctx.registerTool({
|
|
812
1043
|
name: "cron_manage",
|
|
813
1044
|
label: "Cron",
|
|
814
|
-
description: 'Manage persistent scheduled prompts bound to THIS existing session and cwd.
|
|
1045
|
+
description: 'Manage persistent scheduled prompts bound to THIS existing session and cwd (creation is prompt-only; sessionless process jobs are managed by their owning commands, e.g. pie memory schedule, but list/pause/resume/remove apply to every job). Actions list/add/pause/resume/remove. every is seconds (minimum 60) and REPEATS FOREVER until removed; at is one-shot; cron is five numeric UTC fields. Add optional count (integer 1..1000) to every/cron to auto-disable after that many executions \u2014 prefer {"every":60,"count":5} over manual removal for N-time notifications. Missed intervals coalesce; blocked/uncertain tasks require human review before resume. remove/pause fail with "job is running" while a delivery is in flight; retry after the delivered turn settles.',
|
|
815
1046
|
parameters: Type.Object({ action: Type.Union(["list", "add", "pause", "resume", "remove"].map((s) => Type.Literal(s))), id: Type.Optional(Type.String()), prompt: Type.Optional(Type.String({ maxLength: 16e3 })), schedule: Type.Optional(Type.Union([Type.Object({ at: Type.String() }), Type.Object({ every: Type.Integer({ minimum: 60, maximum: 31536e3 }), count: Type.Optional(Type.Integer({ minimum: 1, maximum: 1e3 })) }), Type.Object({ cron: Type.String({ maxLength: 256 }), count: Type.Optional(Type.Integer({ minimum: 1, maximum: 1e3 })) })])) }),
|
|
816
1047
|
risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
|
|
817
1048
|
execute: async (args) => {
|
|
@@ -835,6 +1066,9 @@ function cron(ctx) {
|
|
|
835
1066
|
});
|
|
836
1067
|
}
|
|
837
1068
|
export {
|
|
1069
|
+
PROCESS_SESSION_ID,
|
|
1070
|
+
Store,
|
|
838
1071
|
configPath,
|
|
839
|
-
cron as default
|
|
1072
|
+
cron as default,
|
|
1073
|
+
parseProcessCommand
|
|
840
1074
|
};
|
|
@@ -848,6 +848,16 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
848
848
|
terminalCleanup();
|
|
849
849
|
}
|
|
850
850
|
}
|
|
851
|
+
function escapeRegExp(text) {
|
|
852
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
853
|
+
}
|
|
854
|
+
function parseSessionAddress(text) {
|
|
855
|
+
const name = ctx.getSessionName?.()?.trim();
|
|
856
|
+
if (!name) return { kind: "absent" };
|
|
857
|
+
const own = new RegExp(`^${escapeRegExp(name)}:[ \\t]+(.+)$`, "s").exec(text.trim());
|
|
858
|
+
if (own) return { kind: "addressed", body: own[1] };
|
|
859
|
+
return { kind: "absent" };
|
|
860
|
+
}
|
|
851
861
|
async function handleInboundEventInner(event, retry) {
|
|
852
862
|
const matchesTarget = cfg.targetKind === "user" ? event.sender_id === cfg.targetId && (event.chatType === void 0 || event.chatType === "p2p") : event.chat_id === cfg.targetId;
|
|
853
863
|
if (!matchesTarget) return;
|
|
@@ -875,7 +885,8 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
875
885
|
releaseInvalidatedEvent();
|
|
876
886
|
return;
|
|
877
887
|
}
|
|
878
|
-
const
|
|
888
|
+
const address = parseSessionAddress(event.text);
|
|
889
|
+
const resolution = address.kind === "addressed" ? { found: { messageId: "", threadId: meta.threadId ?? null, sessionId, sentAt: Date.now() } } : await resolveRouteForInbound(messageId, meta);
|
|
879
890
|
if (!("found" in resolution)) {
|
|
880
891
|
if (isTransient(resolution)) retry();
|
|
881
892
|
else ctx.log(`im-forward: no route for ${messageId}; ignoring`);
|
|
@@ -887,7 +898,7 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
887
898
|
return;
|
|
888
899
|
}
|
|
889
900
|
const imageKeys = event.images;
|
|
890
|
-
const caption = event.text;
|
|
901
|
+
const caption = address.kind === "addressed" ? address.body : event.text;
|
|
891
902
|
if (!caption && !imageKeys.length) return;
|
|
892
903
|
const submitText = `${IM_INPUT_PREFIX}
|
|
893
904
|
${caption || IM_INPUT_FALLBACK_CAPTION}`;
|