@wjarka/cezarion 0.17.0-dev.5506 → 0.17.0-dev.5515

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 (62) hide show
  1. package/README.md +12 -0
  2. package/dist/ci-wait/controller.d.ts +37 -37
  3. package/dist/ci-wait/errors.js +2 -2
  4. package/dist/ci-wait/errors.js.map +1 -1
  5. package/dist/ci-wait/tools.js +8 -6
  6. package/dist/ci-wait/tools.js.map +1 -1
  7. package/dist/cli-dispatch.js +1 -0
  8. package/dist/cli-dispatch.js.map +1 -1
  9. package/dist/delegation/transport.d.ts +62 -62
  10. package/dist/jobs/cli.d.ts +2 -0
  11. package/dist/jobs/cli.js +53 -0
  12. package/dist/jobs/cli.js.map +1 -0
  13. package/dist/jobs/command.d.ts +9 -0
  14. package/dist/jobs/command.js +19 -0
  15. package/dist/jobs/command.js.map +1 -0
  16. package/dist/jobs/job.d.ts +77 -0
  17. package/dist/jobs/job.js +252 -0
  18. package/dist/jobs/job.js.map +1 -0
  19. package/dist/server/activity-routes.d.ts +23 -23
  20. package/dist/server/live-routes.d.ts +6 -6
  21. package/dist/server/run-checkout.d.ts +2 -3
  22. package/dist/server/run-checkout.js +4 -4
  23. package/dist/server/run-checkout.js.map +1 -1
  24. package/dist/server/self-update-routes.d.ts +19 -19
  25. package/dist/server/server.d.ts +1383 -1435
  26. package/dist/server/server.js +11 -24
  27. package/dist/server/server.js.map +1 -1
  28. package/dist/subcommands.d.ts +1 -1
  29. package/dist/subcommands.js +2 -1
  30. package/dist/subcommands.js.map +1 -1
  31. package/dist/voice/routes.d.ts +19 -19
  32. package/dist/workflows/run/session-events.d.ts +1 -1
  33. package/dist/workflows/run/session-events.js +3 -2
  34. package/dist/workflows/run/session-events.js.map +1 -1
  35. package/dist/workflows/run/wait-kinds.d.ts +3 -0
  36. package/dist/workflows/run/wait-kinds.js +11 -1
  37. package/dist/workflows/run/wait-kinds.js.map +1 -1
  38. package/package.json +3 -3
  39. package/web/dist/assets/{activity-motion-BHr-ZAZp.js → activity-motion-D-wNjCZO.js} +1 -1
  40. package/web/dist/assets/{activity-route-Bk7-QeK_.js → activity-route-CEhKA6LC.js} +1 -1
  41. package/web/dist/assets/{commit-diff-panel-C9vHxqqQ.js → commit-diff-panel-C5SEnKvj.js} +1 -1
  42. package/web/dist/assets/{diff-gmuErI3F.js → diff-DOKQG121.js} +2 -2
  43. package/web/dist/assets/{diff-view-DigfbKBX.js → diff-view-Dlbaomc6.js} +1 -1
  44. package/web/dist/assets/{git-toolbar-DOUDDTBC.js → git-toolbar-B_lgnDi3.js} +1 -1
  45. package/web/dist/assets/{github-DBcdEsSz.js → github-89EDv5jm.js} +1 -1
  46. package/web/dist/assets/{global-activity-route-CxCecB2W.js → global-activity-route-2SM3xKBA.js} +1 -1
  47. package/web/dist/assets/{index-Cybrk3p9.js → index-DKIv9VPA.js} +3 -3
  48. package/web/dist/assets/{preview-pane-connected-mMMD4IiM.js → preview-pane-connected-B730Jv1e.js} +1 -1
  49. package/web/dist/assets/{repo-git-Dv-6cKAC.js → repo-git-D6gQXbHu.js} +1 -1
  50. package/web/dist/assets/{report-reader-Dtus2Ua4.js → report-reader-DP43jeNM.js} +1 -1
  51. package/web/dist/assets/{reports-DAgEuUbp.js → reports-DV8NzFp3.js} +1 -1
  52. package/web/dist/assets/{run-header-BPaPARge.js → run-header-DjXPrh23.js} +1 -1
  53. package/web/dist/assets/{skills-XYpWQDCm.js → skills-DuZYEbo5.js} +1 -1
  54. package/web/dist/assets/{task-changes-BAQ4Gn66.js → task-changes-CUWFco57.js} +1 -1
  55. package/web/dist/assets/{task-commits-DS7kN8JG.js → task-commits-Cgoxt66y.js} +1 -1
  56. package/web/dist/assets/{task-files-D7YFhWFg.js → task-files-BmTRfJ5K.js} +1 -1
  57. package/web/dist/assets/{task-github-item-bRgH9WkE.js → task-github-item-Cmro8m-6.js} +1 -1
  58. package/web/dist/assets/{task-thread-CuRhXDEj.js → task-thread-BTjoNRed.js} +2 -2
  59. package/web/dist/assets/{thread-state-DDD8tLGN.js → thread-state-Cd3ERj1h.js} +1 -1
  60. package/web/dist/assets/{use-hand-to-agent-state-b8KEA5pM.js → use-hand-to-agent-state-C2rQan6D.js} +1 -1
  61. package/web/dist/assets/{workflows-BdKDN9aF.js → workflows-DemG2-He.js} +1 -1
  62. package/web/dist/index.html +1 -1
@@ -2,6 +2,18 @@ import type { DelegationRoutes } from './routes.ts';
2
2
  export declare function createDelegationApp(routes: DelegationRoutes): import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, import("hono/types").BlankSchema | import("hono/types").MergeSchemaPath<{
3
3
  "/list": {
4
4
  $get: {
5
+ output: {
6
+ error: string;
7
+ code?: "invalid_input" | undefined;
8
+ };
9
+ outputFormat: "json";
10
+ status: 400;
11
+ input: {
12
+ query: {
13
+ offset?: string | undefined;
14
+ };
15
+ };
16
+ } | {
5
17
  output: {
6
18
  workers: {
7
19
  workerId: string;
@@ -39,18 +51,6 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
39
51
  offset?: string | undefined;
40
52
  };
41
53
  };
42
- } | {
43
- output: {
44
- error: string;
45
- code?: "invalid_input" | undefined;
46
- };
47
- outputFormat: "json";
48
- status: 400;
49
- input: {
50
- query: {
51
- offset?: string | undefined;
52
- };
53
- };
54
54
  };
55
55
  };
56
56
  } & {
@@ -588,6 +588,18 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
588
588
  } & {
589
589
  "/:workerId": {
590
590
  $get: {
591
+ output: {
592
+ error: string;
593
+ code?: "invalid_input" | undefined;
594
+ };
595
+ outputFormat: "json";
596
+ status: 400;
597
+ input: {
598
+ param: {
599
+ workerId: string;
600
+ };
601
+ };
602
+ } | {
591
603
  output: {
592
604
  workerId: string;
593
605
  parentRunId: string;
@@ -691,7 +703,11 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
691
703
  workerId: string;
692
704
  };
693
705
  };
694
- } | {
706
+ };
707
+ };
708
+ } & {
709
+ "/:workerId/collect": {
710
+ $post: {
695
711
  output: {
696
712
  error: string;
697
713
  code?: "invalid_input" | undefined;
@@ -702,12 +718,10 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
702
718
  param: {
703
719
  workerId: string;
704
720
  };
721
+ } & {
722
+ json: Record<string, never>;
705
723
  };
706
- };
707
- };
708
- } & {
709
- "/:workerId/collect": {
710
- $post: {
724
+ } | {
711
725
  output: {
712
726
  workerId: string;
713
727
  parentRunId: string;
@@ -809,7 +823,11 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
809
823
  } & {
810
824
  json: Record<string, never>;
811
825
  };
812
- } | {
826
+ };
827
+ };
828
+ } & {
829
+ "/:workerId/steer": {
830
+ $post: {
813
831
  output: {
814
832
  error: string;
815
833
  code?: "invalid_input" | undefined;
@@ -821,13 +839,11 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
821
839
  workerId: string;
822
840
  };
823
841
  } & {
824
- json: Record<string, never>;
842
+ json: {
843
+ text: string;
844
+ };
825
845
  };
826
- };
827
- };
828
- } & {
829
- "/:workerId/steer": {
830
- $post: {
846
+ } | {
831
847
  output: {
832
848
  workerId: string;
833
849
  state: "delivered" | "queued";
@@ -843,7 +859,11 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
843
859
  text: string;
844
860
  };
845
861
  };
846
- } | {
862
+ };
863
+ };
864
+ } & {
865
+ "/:workerId/stop": {
866
+ $post: {
847
867
  output: {
848
868
  error: string;
849
869
  code?: "invalid_input" | undefined;
@@ -855,15 +875,9 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
855
875
  workerId: string;
856
876
  };
857
877
  } & {
858
- json: {
859
- text: string;
860
- };
878
+ json: Record<string, never>;
861
879
  };
862
- };
863
- };
864
- } & {
865
- "/:workerId/stop": {
866
- $post: {
880
+ } | {
867
881
  output: {
868
882
  workerId: string;
869
883
  state: "stopping" | "terminated";
@@ -877,7 +891,11 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
877
891
  } & {
878
892
  json: Record<string, never>;
879
893
  };
880
- } | {
894
+ };
895
+ };
896
+ } & {
897
+ "/:workerId/destroy": {
898
+ $post: {
881
899
  output: {
882
900
  error: string;
883
901
  code?: "invalid_input" | undefined;
@@ -891,11 +909,7 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
891
909
  } & {
892
910
  json: Record<string, never>;
893
911
  };
894
- };
895
- };
896
- } & {
897
- "/:workerId/destroy": {
898
- $post: {
912
+ } | {
899
913
  output: {
900
914
  workerId: string;
901
915
  state: "complete" | "incomplete";
@@ -918,20 +932,6 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
918
932
  } & {
919
933
  json: Record<string, never>;
920
934
  };
921
- } | {
922
- output: {
923
- error: string;
924
- code?: "invalid_input" | undefined;
925
- };
926
- outputFormat: "json";
927
- status: 400;
928
- input: {
929
- param: {
930
- workerId: string;
931
- };
932
- } & {
933
- json: Record<string, never>;
934
- };
935
935
  } | {
936
936
  output: {
937
937
  workerId: string;
@@ -961,13 +961,11 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
961
961
  "/:workerId/diff": {
962
962
  $get: {
963
963
  output: {
964
- workerId: string;
965
- baselineSha: string;
966
- diff: string;
967
- truncated: boolean;
964
+ error: string;
965
+ code?: "invalid_input" | undefined;
968
966
  };
969
967
  outputFormat: "json";
970
- status: 200;
968
+ status: 400;
971
969
  input: {
972
970
  param: {
973
971
  workerId: string;
@@ -975,11 +973,13 @@ export declare function createDelegationApp(routes: DelegationRoutes): import("h
975
973
  };
976
974
  } | {
977
975
  output: {
978
- error: string;
979
- code?: "invalid_input" | undefined;
976
+ workerId: string;
977
+ baselineSha: string;
978
+ diff: string;
979
+ truncated: boolean;
980
980
  };
981
981
  outputFormat: "json";
982
- status: 400;
982
+ status: 200;
983
983
  input: {
984
984
  param: {
985
985
  workerId: string;
@@ -0,0 +1,2 @@
1
+ /** `cez job`: one JSON object on stdout for a result and on stderr for an error; help is text. */
2
+ export declare function runJobCommand(argv: string[], env: NodeJS.ProcessEnv): Promise<number>;
@@ -0,0 +1,53 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { commandText } from '../home/command.js';
3
+ import { JobError, SUPERVISE, jobDirectory, jobStatus, startJob, superviseJob, tellStarter } from './job.js';
4
+ const HELP = commandText(`Usage: cez job start <name> [--dir <dir>] -- <command> [args...]
5
+ cez job status <name> [--dir <dir>]
6
+
7
+ start Run a long command so that it outlives this shell call, the turn and the
8
+ agent session. Writes its output to a log file and its exit code to an
9
+ exit file in <dir>; each start has files of its own. Prints JSON with
10
+ the long-lived "pid", "log" and "exitFile": pass "pid" and "exitFile"
11
+ to a process wait. Exits 1 and names the running PID while a job of
12
+ that name still runs. A name whose job ended starts again.
13
+ status Print JSON: "state" is "running" or "exited", with "pid", "log",
14
+ "exitFile", and "exitCode" when the exit file holds one.
15
+
16
+ --dir <dir> Where the job's files live. Default: $TMPDIR, the task's temp
17
+ directory, which Cezar removes when the task ends. For a job that
18
+ must outlive the task, name a git-ignored directory in the worktree.
19
+ -h, --help Show this help.
20
+
21
+ The command runs without a shell. For a pipeline, pass: -- sh -c '<pipeline>'.`);
22
+ /** `cez job`: one JSON object on stdout for a result and on stderr for an error; help is text. */
23
+ export async function runJobCommand(argv, env) {
24
+ if (argv[0] === SUPERVISE)
25
+ return superviseJob(argv[1], argv[2], argv.slice(4), tellStarter);
26
+ const split = argv.indexOf('--');
27
+ const own = split === -1 ? argv : argv.slice(0, split);
28
+ const command = split === -1 ? [] : argv.slice(split + 1);
29
+ if (own.includes('--help') || own.includes('-h')) {
30
+ console.log(HELP);
31
+ return 0;
32
+ }
33
+ try {
34
+ const { values, positionals } = parseArgs({ args: own, options: { dir: { type: 'string' } }, allowPositionals: true });
35
+ const [action, name, ...rest] = positionals;
36
+ if (!name || rest.length > 0 || (action !== 'start' && action !== 'status'))
37
+ throw new JobError(HELP);
38
+ const dir = jobDirectory(values.dir, env);
39
+ if (action === 'status') {
40
+ if (command.length > 0)
41
+ throw new JobError(HELP);
42
+ console.log(JSON.stringify(jobStatus(dir, name)));
43
+ return 0;
44
+ }
45
+ console.log(JSON.stringify(await startJob({ name, dir, command, env })));
46
+ return 0;
47
+ }
48
+ catch (error) {
49
+ console.error(JSON.stringify({ error: error instanceof Error ? error.message : 'The job command failed' }));
50
+ return 1;
51
+ }
52
+ }
53
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/jobs/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE7G,MAAM,IAAI,GAAG,WAAW,CAAC;;;;;;;;;;;;;;;;;+EAiBsD,CAAC,CAAC;AAEjF,kGAAkG;AAClG,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,IAAc,EAAE,GAAsB;IACxE,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS;QAAE,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC,CAAE,EAAE,IAAI,CAAC,CAAC,CAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;IAC/F,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC,MAAM,GAAG,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;IAC1D,IAAI,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAAC,OAAO,CAAC,CAAC;IAAC,CAAC;IAClF,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,SAAS,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC;QACvH,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,GAAG,WAAW,CAAC;QAC5C,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,QAAQ,CAAC;YAAE,MAAM,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;QACtG,MAAM,GAAG,GAAG,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QAC1C,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;YACxB,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;YACjD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;YAClD,OAAO,CAAC,CAAC;QACX,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,QAAQ,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;QACzE,OAAO,CAAC,CAAC;IACX,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,wBAAwB,EAAE,CAAC,CAAC,CAAC;QAC5G,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC"}
@@ -0,0 +1,9 @@
1
+ /** This program's own entry as argv, as `artifactInstructions` builds it: from source in a checkout. */
2
+ export declare function ownCommand(): string[];
3
+ /**
4
+ * The launch prompt's part that names the `job start` command in full. Cezar composes it in its own
5
+ * process, where `process.execPath` is the Node that runs Cezar. The tool list also loads inside
6
+ * other programs (omp is a standalone binary), so the `cezar_wait` description names the command
7
+ * only as `cez job start` and points here.
8
+ */
9
+ export declare function jobInstructions(): string;
@@ -0,0 +1,19 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { shellQuote } from '../core/shell-env.js';
3
+ /** This program's own entry as argv, as `artifactInstructions` builds it: from source in a checkout. */
4
+ export function ownCommand() {
5
+ const source = import.meta.url.endsWith('.ts');
6
+ const entry = fileURLToPath(new URL(source ? '../index.ts' : '../index.js', import.meta.url));
7
+ return [process.execPath, ...(source ? ['--import', import.meta.resolve('tsx')] : []), entry];
8
+ }
9
+ /**
10
+ * The launch prompt's part that names the `job start` command in full. Cezar composes it in its own
11
+ * process, where `process.execPath` is the Node that runs Cezar. The tool list also loads inside
12
+ * other programs (omp is a standalone binary), so the `cezar_wait` description names the command
13
+ * only as `cez job start` and points here.
14
+ */
15
+ export function jobInstructions() {
16
+ const command = `${ownCommand().map(shellQuote).join(' ')} job start`;
17
+ return `## Long commands\nTo run a command that takes longer than one shell call (a full test run, a benchmark, a measurement), start it with ${command} <name> -- <command> [args...]. It prints JSON with a long-lived \`pid\`, a \`log\` path and an \`exitFile\` path, and the command keeps running after this shell call, this turn and this session end. Then call cezar_wait with kind "process", that \`pid\` and that \`exitFile\` as \`exit_file\`, and end your turn. Replace \`start\` with \`status\` to find a job by its name later.`;
18
+ }
19
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.js","sourceRoot":"","sources":["../../src/jobs/command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,wGAAwG;AACxG,MAAM,UAAU,UAAU;IACxB,MAAM,MAAM,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,aAAa,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9F,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;AAChG,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe;IAC7B,MAAM,OAAO,GAAG,GAAG,UAAU,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC;IACtE,OAAO,yIAAyI,OAAO,8XAA8X,CAAC;AACxhB,CAAC"}
@@ -0,0 +1,77 @@
1
+ export interface JobRecord {
2
+ name: string;
3
+ pid: number;
4
+ start?: string;
5
+ command: string[];
6
+ startedAt: string;
7
+ log: string;
8
+ exitFile: string;
9
+ }
10
+ export interface JobPaths {
11
+ record: string;
12
+ }
13
+ export type JobStatus = {
14
+ name: string;
15
+ state: 'running';
16
+ pid: number;
17
+ log: string;
18
+ exitFile: string;
19
+ } | {
20
+ name: string;
21
+ state: 'exited';
22
+ pid: number;
23
+ exitCode?: number;
24
+ log: string;
25
+ exitFile: string;
26
+ };
27
+ export declare class JobError extends Error {
28
+ }
29
+ export declare function jobDirectory(dir: string | undefined, env: NodeJS.ProcessEnv): string;
30
+ export declare function jobPaths(dir: string, name: string): JobPaths;
31
+ export declare function jobStatus(dir: string, name: string): JobStatus;
32
+ /** What the supervisor tells its starter: it holds the name, or another supervisor does. */
33
+ export type ClaimAnswer = {
34
+ claimed: true;
35
+ replaced: boolean;
36
+ log: string;
37
+ exitFile: string;
38
+ } | {
39
+ claimed: false;
40
+ pid: number;
41
+ } | {
42
+ claimed: false;
43
+ error: string;
44
+ };
45
+ /**
46
+ * Claims `name` for this process, or answers who holds it. Read, decide and write are one write
47
+ * transaction, so two claimants never both find the name free. A holder that has written its exit
48
+ * file is done even while its process is still ending. Earlier starts' files stay as they are.
49
+ */
50
+ export declare function claimJob(paths: JobPaths, record: JobRecord): ClaimAnswer;
51
+ export interface StartOptions {
52
+ name: string;
53
+ dir: string;
54
+ command: string[];
55
+ cwd?: string;
56
+ env?: NodeJS.ProcessEnv;
57
+ }
58
+ export interface StartedJob {
59
+ name: string;
60
+ pid: number;
61
+ log: string;
62
+ exitFile: string;
63
+ replaced: boolean;
64
+ }
65
+ /** Starts the supervisor and answers once it holds the name. Refuses while the name runs. */
66
+ export declare function startJob(options: StartOptions): Promise<StartedJob>;
67
+ /** The hidden subcommand the supervisor runs as. */
68
+ export declare const SUPERVISE = "__supervise";
69
+ /** Sends the claim answer to the starter over the channel it opened, then lets go of the channel. */
70
+ export declare function tellStarter(answer: ClaimAnswer): Promise<void>;
71
+ /**
72
+ * The supervisor: claims the name, tells its starter, runs the command and writes its exit code.
73
+ * It answers 1 without running anything when another supervisor holds the name. The exit file is
74
+ * renamed into place, so a reader never sees it half written. A SIGTERM or SIGINT goes on to the
75
+ * command, and the exit file still records how it ended.
76
+ */
77
+ export declare function superviseJob(dir: string, name: string, command: string[], tell?: (answer: ClaimAnswer) => Promise<void>): Promise<number>;
@@ -0,0 +1,252 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { constants, tmpdir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { recordedProcessLive } from '../delegation/process-liveness.js';
7
+ import { processStartToken, startOwnedGroup } from '../detached-process.js';
8
+ import { ownCommand } from './command.js';
9
+ /**
10
+ * A long command an agent starts from its own shell and leaves running (hearsay-tools/cezarion#3097).
11
+ * A supervisor process leads a session of its own, so the command outlives the shell call, the turn
12
+ * and the agent session on every runner: Codex ends a command's process group when the command
13
+ * returns, and Cezar ends a session's group when the session ends. The supervisor writes the
14
+ * command's output to a log file and its exit code to an exit file, and its own PID is the one a
15
+ * process wait watches. Each start has files of its own, `<name>.<run>.log` and `<name>.<run>.exit`:
16
+ * a process wait still open on an earlier start of the name never reads a later start's exit code.
17
+ *
18
+ * The supervisor, not its starter, claims the name: it is the process that lives as long as the
19
+ * job, so no starter's death leaves a claim behind or a job unclaimed. The claim is one SQLite
20
+ * write transaction on `<name>.job.db`. The database serializes claimants, and the operating
21
+ * system drops a dead claimant's file lock, so nothing is ever taken over by age or by guess.
22
+ */
23
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
24
+ /** How long a start waits for its supervisor to claim the name before it gives up. */
25
+ const READY_TIMEOUT_MS = 30_000;
26
+ /** How long one claimant waits for another's transaction, which holds a few statements. */
27
+ const CLAIM_BUSY_MS = 10_000;
28
+ export class JobError extends Error {
29
+ }
30
+ export function jobDirectory(dir, env) {
31
+ return resolve(dir ?? env.TMPDIR ?? tmpdir());
32
+ }
33
+ export function jobPaths(dir, name) {
34
+ if (!NAME.test(name))
35
+ throw new JobError(`Invalid job name ${JSON.stringify(name)}: use 1-64 letters, digits, ".", "_" or "-", starting with a letter or digit.`);
36
+ return { record: join(dir, `${name}.job.db`) };
37
+ }
38
+ const damaged = (paths, why) => new JobError(`The job record ${paths.record} cannot be used (${why}). Check that no process of this job runs, then delete it or choose another name.`);
39
+ function parseRecord(paths, text) {
40
+ let value = null;
41
+ try {
42
+ value = JSON.parse(String(text));
43
+ }
44
+ catch { /* refused below */ }
45
+ const pid = value?.pid;
46
+ if (!value || typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid < 2 || typeof value.name !== 'string' || !Array.isArray(value.command) || (value.start !== undefined && typeof value.start !== 'string') || typeof value.log !== 'string' || typeof value.exitFile !== 'string') {
47
+ throw damaged(paths, 'it holds no job record');
48
+ }
49
+ return value;
50
+ }
51
+ /** Runs `use` on the record database. A file that is not one is a refusal, never an absent record:
52
+ * it may belong to a supervisor that still runs. */
53
+ function withRecords(paths, options, use) {
54
+ let db;
55
+ try {
56
+ db = new DatabaseSync(paths.record, options);
57
+ db.exec(`PRAGMA busy_timeout = ${CLAIM_BUSY_MS}`);
58
+ return use(db);
59
+ }
60
+ catch (error) {
61
+ throw error instanceof JobError ? error : damaged(paths, error instanceof Error ? error.message : String(error));
62
+ }
63
+ finally {
64
+ try {
65
+ db?.close();
66
+ }
67
+ catch { /* never opened */ }
68
+ }
69
+ }
70
+ const selectRecord = (paths, db) => {
71
+ const row = db.prepare('SELECT record FROM job WHERE id = 1').get();
72
+ return row === undefined ? undefined : parseRecord(paths, row.record);
73
+ };
74
+ function readRecord(paths) {
75
+ if (!existsSync(paths.record))
76
+ return undefined;
77
+ return withRecords(paths, { readOnly: true }, (db) => {
78
+ // A claimant that ended before its first commit leaves a database with nothing in it.
79
+ if (db.prepare('SELECT count(*) AS objects FROM sqlite_master').get()?.objects === 0)
80
+ return undefined;
81
+ const record = selectRecord(paths, db);
82
+ if (record === undefined)
83
+ throw damaged(paths, 'it holds no job record');
84
+ return record;
85
+ });
86
+ }
87
+ /** The first line of the exit file as an integer, when the supervisor has written it. */
88
+ function readExit(record) {
89
+ try {
90
+ const line = readFileSync(record.exitFile, 'utf8').split('\n', 1)[0].trim();
91
+ return /^-?\d+$/.test(line) ? Number(line) : undefined;
92
+ }
93
+ catch {
94
+ return undefined;
95
+ }
96
+ }
97
+ /** A record whose supervisor still runs. Without a start identity (Windows) a live PID counts. */
98
+ function running(record) {
99
+ return recordedProcessLive({ pid: record.pid, ...(record.start === undefined ? {} : { startToken: record.start }) });
100
+ }
101
+ export function jobStatus(dir, name) {
102
+ const paths = jobPaths(dir, name);
103
+ const record = readRecord(paths);
104
+ if (!record)
105
+ throw new JobError(`No job named ${JSON.stringify(name)} in ${dir}.`);
106
+ const base = { name, pid: record.pid, log: record.log, exitFile: record.exitFile };
107
+ const exitCode = readExit(record);
108
+ if (exitCode !== undefined)
109
+ return { ...base, state: 'exited', exitCode };
110
+ return running(record) ? { ...base, state: 'running' } : { ...base, state: 'exited' };
111
+ }
112
+ /**
113
+ * Claims `name` for this process, or answers who holds it. Read, decide and write are one write
114
+ * transaction, so two claimants never both find the name free. A holder that has written its exit
115
+ * file is done even while its process is still ending. Earlier starts' files stay as they are.
116
+ */
117
+ export function claimJob(paths, record) {
118
+ return withRecords(paths, { readOnly: false }, (db) => {
119
+ db.exec('BEGIN IMMEDIATE');
120
+ try {
121
+ // Only a database with nothing in it is a free name. One that holds anything else, or a job
122
+ // table without its row, is not this command's record of an ended job: it is refused.
123
+ const fresh = db.prepare('SELECT count(*) AS objects FROM sqlite_master').get()?.objects === 0;
124
+ if (fresh)
125
+ db.exec('CREATE TABLE job (id INTEGER PRIMARY KEY CHECK (id = 1), record TEXT NOT NULL)');
126
+ const previous = selectRecord(paths, db);
127
+ if (!fresh && previous === undefined)
128
+ throw damaged(paths, 'it holds no job record');
129
+ if (previous && running(previous) && readExit(previous) === undefined) {
130
+ db.exec('ROLLBACK');
131
+ return { claimed: false, pid: previous.pid };
132
+ }
133
+ db.prepare('INSERT INTO job (id, record) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET record = excluded.record').run(JSON.stringify(record));
134
+ db.exec('COMMIT');
135
+ return { claimed: true, replaced: previous !== undefined, log: record.log, exitFile: record.exitFile };
136
+ }
137
+ catch (error) {
138
+ try {
139
+ db.exec('ROLLBACK');
140
+ }
141
+ catch { /* no transaction is open */ }
142
+ throw error;
143
+ }
144
+ });
145
+ }
146
+ /** Starts the supervisor and answers once it holds the name. Refuses while the name runs. */
147
+ export async function startJob(options) {
148
+ const { name, dir, command } = options;
149
+ if (command.length === 0)
150
+ throw new JobError('Give the command to run after "--".');
151
+ mkdirSync(dir, { recursive: true });
152
+ jobPaths(dir, name);
153
+ const [bin, ...prefix] = ownCommand();
154
+ const { child } = await startOwnedGroup(bin, [...prefix, 'job', SUPERVISE, dir, name, '--', ...command], {
155
+ cwd: options.cwd ?? process.cwd(), env: options.env ?? process.env, stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
156
+ });
157
+ const answer = await supervisorAnswer(child);
158
+ if (!answer.claimed) {
159
+ throw new JobError('pid' in answer ? `Job ${JSON.stringify(name)} is already running as PID ${answer.pid}. Wait for that PID, or choose another name.` : answer.error);
160
+ }
161
+ child.disconnect();
162
+ child.unref();
163
+ return { name, pid: child.pid, log: answer.log, exitFile: answer.exitFile, replaced: answer.replaced };
164
+ }
165
+ /** The supervisor's claim answer; a refusal when it ends or stays silent first. */
166
+ function supervisorAnswer(child) {
167
+ return new Promise((done, fail) => {
168
+ const timer = setTimeout(() => { child.kill('SIGKILL'); fail(new JobError('The job supervisor did not start.')); }, READY_TIMEOUT_MS);
169
+ const settle = (act) => { clearTimeout(timer); child.removeAllListeners('message'); child.removeAllListeners('exit'); act(); };
170
+ child.once('message', answer => settle(() => done(answer)));
171
+ child.once('exit', code => settle(() => fail(new JobError(`The job supervisor ended before it started the command (exit ${code ?? 'by signal'}).`))));
172
+ });
173
+ }
174
+ /** The hidden subcommand the supervisor runs as. */
175
+ export const SUPERVISE = '__supervise';
176
+ function writeAtomic(path, text) {
177
+ const temp = `${path}.${process.pid}.tmp`;
178
+ writeFileSync(temp, text);
179
+ renameSync(temp, path);
180
+ }
181
+ const signalNumber = (signal) => constants.signals[signal] ?? 0;
182
+ /** Sends the claim answer to the starter over the channel it opened, then lets go of the channel. */
183
+ export function tellStarter(answer) {
184
+ return new Promise((sent) => {
185
+ // A starter that has ended closed the channel: there is no one to tell.
186
+ if (!process.send || !process.connected) {
187
+ sent();
188
+ return;
189
+ }
190
+ try {
191
+ process.send(answer, () => { if (process.connected)
192
+ process.disconnect(); sent(); });
193
+ }
194
+ catch {
195
+ sent();
196
+ }
197
+ });
198
+ }
199
+ /**
200
+ * The supervisor: claims the name, tells its starter, runs the command and writes its exit code.
201
+ * It answers 1 without running anything when another supervisor holds the name. The exit file is
202
+ * renamed into place, so a reader never sees it half written. A SIGTERM or SIGINT goes on to the
203
+ * command, and the exit file still records how it ended.
204
+ */
205
+ export async function superviseJob(dir, name, command, tell = async () => { }) {
206
+ const paths = jobPaths(dir, name);
207
+ const start = processStartToken(process.pid);
208
+ const startedAt = new Date();
209
+ // The run id is unique to this supervisor among the starts of one name in this directory.
210
+ const run = `${startedAt.getTime().toString(36)}-${process.pid}`;
211
+ const record = { name, pid: process.pid, ...(start === undefined ? {} : { start }), command, startedAt: startedAt.toISOString(),
212
+ log: join(dir, `${name}.${run}.log`), exitFile: join(dir, `${name}.${run}.exit`) };
213
+ let answer;
214
+ try {
215
+ answer = claimJob(paths, record);
216
+ }
217
+ catch (error) {
218
+ answer = { claimed: false, error: error instanceof Error ? error.message : String(error) };
219
+ }
220
+ if (!answer.claimed) {
221
+ await tell(answer);
222
+ return 1;
223
+ }
224
+ const log = openSync(record.log, 'w');
225
+ // A hangup must not end the supervisor: its starter's terminal or session may close.
226
+ const signals = [['SIGHUP', () => { }]];
227
+ // A starter that died gets no answer; the job runs all the same, and `status` names it.
228
+ void tell(answer).catch(() => { });
229
+ return new Promise((done) => {
230
+ const finish = (code, note) => {
231
+ for (const [signal, handler] of signals)
232
+ process.off(signal, handler);
233
+ if (note)
234
+ writeFileSync(log, `${note}\n`);
235
+ closeSync(log);
236
+ // The directory can be gone: Cezar removes a task's temp directory when the task ends.
237
+ try {
238
+ writeAtomic(record.exitFile, `${code}\n`);
239
+ }
240
+ catch { /* no one can read it there */ }
241
+ done(code);
242
+ };
243
+ const child = spawn(command[0], command.slice(1), { stdio: ['ignore', log, log] });
244
+ for (const signal of ['SIGTERM', 'SIGINT'])
245
+ signals.push([signal, () => { child.kill(signal); }]);
246
+ for (const [signal, handler] of signals)
247
+ process.on(signal, handler);
248
+ child.once('error', error => finish(127, `cez job: cannot run ${command[0]}: ${error.message}`));
249
+ child.once('exit', (code, signal) => finish(code ?? 128 + (signal ? signalNumber(signal) : 0)));
250
+ });
251
+ }
252
+ //# sourceMappingURL=job.js.map