@oxgeneral/orch 0.2.3 → 0.3.0

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 (145) hide show
  1. package/dist/App-TW35IULR.js +18 -0
  2. package/dist/agent-FRQKL7YI.js +9 -0
  3. package/dist/{orchestrator-VGYKSOZJ.js → chunk-2UC4SVJB.js} +236 -71
  4. package/dist/chunk-2UC4SVJB.js.map +1 -0
  5. package/dist/chunk-5AJ4LYO5.js +8 -0
  6. package/dist/{chunk-45K2XID7.js → chunk-6DWHQPTE.js} +2 -1
  7. package/dist/chunk-6DWHQPTE.js.map +1 -0
  8. package/dist/{chunk-POUC4CPC.js → chunk-6MJ7V6VY.js} +2 -2
  9. package/dist/{chunk-HNKJ4IF7.js → chunk-B4JQM4NU.js} +34 -10
  10. package/dist/chunk-B4JQM4NU.js.map +1 -0
  11. package/dist/{chunk-6HENRUYZ.js → chunk-CDFA4IIQ.js} +2 -2
  12. package/dist/chunk-CHRW4CLD.js +2 -0
  13. package/dist/{chunk-ZU6AY2VU.js → chunk-GZ2Q56YZ.js} +2 -2
  14. package/dist/chunk-HMMPM7MF.js +3 -0
  15. package/dist/{chunk-AELEEEV3.js → chunk-HSBYJ5C5.js} +27 -7
  16. package/dist/chunk-HXOMNULD.js +2 -0
  17. package/dist/{chunk-O5AO5QIR.js → chunk-IQXRQBUK.js} +9 -2
  18. package/dist/chunk-IQXRQBUK.js.map +1 -0
  19. package/dist/chunk-L26TK7Y5.js +2 -0
  20. package/dist/chunk-L3FYR45M.js +2 -0
  21. package/dist/chunk-LXNRCJ22.js +2 -0
  22. package/dist/{chunk-TX7WOFCW.js → chunk-MGFMVPRD.js} +4 -7
  23. package/dist/chunk-MGFMVPRD.js.map +1 -0
  24. package/dist/chunk-MNXU3KCD.js +2 -0
  25. package/dist/{chunk-CHIP7O6V.js → chunk-O2MSGW3V.js} +3 -1
  26. package/dist/chunk-O2MSGW3V.js.map +1 -0
  27. package/dist/chunk-PJ5DKXGR.js +2 -0
  28. package/dist/{chunk-VTA74YWX.js → chunk-QEEM67OA.js} +11 -17
  29. package/dist/chunk-QEEM67OA.js.map +1 -0
  30. package/dist/chunk-UMZEA3JT.js +5 -0
  31. package/dist/{shell-OGTSH4RJ.js → chunk-UW6GUUE6.js} +3 -3
  32. package/dist/chunk-XDVMX2FO.js +8 -0
  33. package/dist/chunk-XDVMX2FO.js.map +1 -0
  34. package/dist/chunk-ZA5Z33GO.js +11 -0
  35. package/dist/claude-E36EGXUV.js +2 -0
  36. package/dist/{chunk-IRN2U2NE.js → claude-RIB3RQS5.js} +5 -2
  37. package/dist/claude-RIB3RQS5.js.map +1 -0
  38. package/dist/cli.js +1 -199
  39. package/dist/clipboard-service-PDTSZIR5.js +25 -0
  40. package/dist/codex-OTZKVESD.js +2 -0
  41. package/dist/{codex-U7LTJTX6.js → codex-VBUSA2GJ.js} +5 -3
  42. package/dist/codex-VBUSA2GJ.js.map +1 -0
  43. package/dist/config-CCSS2P7R.js +2 -0
  44. package/dist/container-OIXLFSX2.js +6 -0
  45. package/dist/context-GSMQHQES.js +7 -0
  46. package/dist/cursor-3DJA6LWS.js +2 -0
  47. package/dist/{cursor-3DI5GKRF.js → cursor-4QIOTDBW.js} +5 -3
  48. package/dist/cursor-4QIOTDBW.js.map +1 -0
  49. package/dist/doctor-KBK5JZBZ.js +2 -0
  50. package/dist/doctor-service-F2SXDWHS.js +91 -0
  51. package/dist/doctor-service-F2SXDWHS.js.map +1 -0
  52. package/dist/doctor-service-PB7YBH3F.js +2 -0
  53. package/dist/goal-RFKFPR7M.js +8 -0
  54. package/dist/index.d.ts +124 -46
  55. package/dist/index.js +1817 -5
  56. package/dist/index.js.map +1 -1
  57. package/dist/init-WRDFAFS2.js +53 -0
  58. package/dist/logs-5QHJWMEG.js +12 -0
  59. package/dist/msg-4SCLBO4K.js +9 -0
  60. package/dist/orchestrator-FGGXK3N3.js +5 -0
  61. package/dist/{orchestrator-TAFBYQQ5.js.map → orchestrator-FGGXK3N3.js.map} +1 -1
  62. package/dist/orchestrator-R7IWZUT6.js +13 -0
  63. package/dist/process-manager-33H27MQF.js +2 -0
  64. package/dist/process-manager-A36Y7LHP.js +3 -0
  65. package/dist/{process-manager-TLZOTO4Y.js.map → process-manager-A36Y7LHP.js.map} +1 -1
  66. package/dist/registry-BO2PPRNG.js +2 -0
  67. package/dist/registry-JXXRLJ5J.js +3 -0
  68. package/dist/{registry-UQAHK77P.js.map → registry-JXXRLJ5J.js.map} +1 -1
  69. package/dist/run-HSHRELOP.js +3 -0
  70. package/dist/shell-EOJBDWTH.js +2 -0
  71. package/dist/{chunk-CIIE6LNG.js → shell-IH2MMTVP.js} +3 -2
  72. package/dist/shell-IH2MMTVP.js.map +1 -0
  73. package/dist/status-DLBNWSWM.js +2 -0
  74. package/dist/task-J6ZN7ALI.js +20 -0
  75. package/dist/team-MSIBKOQC.js +4 -0
  76. package/dist/template-engine-MFL5B677.js +3 -0
  77. package/dist/{template-engine-322SCRR6.js.map → template-engine-MFL5B677.js.map} +1 -1
  78. package/dist/template-engine-ONIDVD4F.js +2 -0
  79. package/dist/tui-G4XUFAIP.js +2 -0
  80. package/dist/update-PC2ENCKU.js +2 -0
  81. package/dist/update-check-HGMBDYHL.js +2 -0
  82. package/dist/workspace-manager-KOOYTO7E.js +3 -0
  83. package/dist/{workspace-manager-47KI7B27.js → workspace-manager-T6AXG7XL.js} +40 -3
  84. package/dist/workspace-manager-T6AXG7XL.js.map +1 -0
  85. package/package.json +2 -1
  86. package/readme.md +5 -4
  87. package/scripts/benchmark.ts +304 -0
  88. package/dist/App-KDZSTAMR.js +0 -4864
  89. package/dist/agent-V5M2C3OC.js +0 -157
  90. package/dist/chunk-2B32FPEB.js +0 -11
  91. package/dist/chunk-2B32FPEB.js.map +0 -1
  92. package/dist/chunk-33QNTNR6.js +0 -46
  93. package/dist/chunk-6GFVB6EK.js +0 -101
  94. package/dist/chunk-6HENRUYZ.js.map +0 -1
  95. package/dist/chunk-AELEEEV3.js.map +0 -1
  96. package/dist/chunk-E3TCKHU6.js +0 -13
  97. package/dist/chunk-E3TCKHU6.js.map +0 -1
  98. package/dist/chunk-ED47GL3F.js +0 -29
  99. package/dist/chunk-HXYAZGLP.js +0 -15
  100. package/dist/chunk-I5WEMARW.js +0 -166
  101. package/dist/chunk-IZYSGYXG.js +0 -2
  102. package/dist/chunk-IZYSGYXG.js.map +0 -1
  103. package/dist/chunk-P6ATSXGL.js +0 -107
  104. package/dist/chunk-PBFE5V3G.js +0 -2
  105. package/dist/chunk-PBFE5V3G.js.map +0 -1
  106. package/dist/chunk-PNE6LQRF.js +0 -5
  107. package/dist/chunk-POUC4CPC.js.map +0 -1
  108. package/dist/chunk-XI4TU6VU.js +0 -50
  109. package/dist/chunk-ZU6AY2VU.js.map +0 -1
  110. package/dist/claude-GH6P2DC5.js +0 -4
  111. package/dist/claude-S47YTIHU.js +0 -2
  112. package/dist/claude-S47YTIHU.js.map +0 -1
  113. package/dist/codex-2CH57B7G.js +0 -2
  114. package/dist/codex-2CH57B7G.js.map +0 -1
  115. package/dist/config-LJFM55LN.js +0 -75
  116. package/dist/container-JV7TAUP5.js +0 -1532
  117. package/dist/context-EPSDCJTU.js +0 -83
  118. package/dist/cursor-QFUNKPCQ.js +0 -2
  119. package/dist/cursor-QFUNKPCQ.js.map +0 -1
  120. package/dist/doctor-IO4PV4D6.js +0 -67
  121. package/dist/doctor-service-A34DHPKI.js +0 -2
  122. package/dist/doctor-service-NTWBWOM2.js +0 -2
  123. package/dist/doctor-service-NTWBWOM2.js.map +0 -1
  124. package/dist/goal-I56QP7HS.js +0 -110
  125. package/dist/init-BE5VKWOM.js +0 -149
  126. package/dist/logs-IAUAS5TX.js +0 -207
  127. package/dist/msg-SQWQLJP6.js +0 -95
  128. package/dist/orchestrator-TAFBYQQ5.js +0 -2
  129. package/dist/process-manager-HUVNAPQV.js +0 -2
  130. package/dist/process-manager-TLZOTO4Y.js +0 -2
  131. package/dist/registry-PQWRVNF2.js +0 -2
  132. package/dist/registry-UQAHK77P.js +0 -2
  133. package/dist/run-PSZURVVL.js +0 -95
  134. package/dist/shell-5ZNXFGXV.js +0 -3
  135. package/dist/shell-OGTSH4RJ.js.map +0 -1
  136. package/dist/status-DTF7D3DV.js +0 -56
  137. package/dist/task-5OJTXW27.js +0 -209
  138. package/dist/team-AISPLEJB.js +0 -97
  139. package/dist/template-engine-322SCRR6.js +0 -2
  140. package/dist/template-engine-3CDRZNMJ.js +0 -3
  141. package/dist/tui-XDJE3IUA.js +0 -225
  142. package/dist/update-72GZMF65.js +0 -64
  143. package/dist/update-check-4RV7Z6WT.js +0 -2
  144. package/dist/workspace-manager-7M46ESUL.js +0 -2
  145. package/dist/workspace-manager-7M46ESUL.js.map +0 -1
@@ -1,157 +0,0 @@
1
- #!/usr/bin/env node
2
- import { agentToEditorContent, openInEditor, agentFromEditorContent } from './chunk-P6ATSXGL.js';
3
- import { printSuccess, agentName, dim, statusIcon, printTable, formatTokens, printKeyValue } from './chunk-I5WEMARW.js';
4
-
5
- // src/cli/commands/agent.ts
6
- function registerAgentCommand(program, container) {
7
- const agent = program.command("agent").description("Manage agents");
8
- agent.command("add <name>").description("Add a new agent").requiredOption("--adapter <adapter>", "Adapter type: claude, shell, codex, cursor").option("--role <role>", "Agent role description").option("--command <cmd>", "Shell command (for shell adapter)").option("--model <model>", "Model name (for AI adapters)").option("--max-turns <n>", "Max turns per run").option("--timeout <ms>", "Timeout in ms").option("--approval-policy <policy>", "suggest|auto|manual").option("--workspace-mode <mode>", "shared|worktree|isolated").option("--skills <skills>", "Comma-separated list of agent skills").option("-e, --edit", "Open $EDITOR to write the role description").action(async (name, opts) => {
9
- await container.paths.requireInit();
10
- let role = opts.role;
11
- if (opts.edit) {
12
- const initial = agentToEditorContent({ name, model: opts.model, role });
13
- const edited = await openInEditor(initial);
14
- const parsed = agentFromEditorContent(edited);
15
- if (parsed.name) name = parsed.name;
16
- if (parsed.model) opts.model = parsed.model;
17
- if (parsed.role) role = parsed.role;
18
- }
19
- const a = await container.agentService.create({
20
- name,
21
- adapter: opts.adapter,
22
- role,
23
- command: opts.command,
24
- model: opts.model,
25
- max_turns: opts.maxTurns ? parseInt(opts.maxTurns, 10) : void 0,
26
- timeout_ms: opts.timeout ? parseInt(opts.timeout, 10) : void 0,
27
- approval_policy: opts.approvalPolicy,
28
- workspace_mode: opts.workspaceMode,
29
- skills: opts.skills ? opts.skills.split(",").map((s) => s.trim()) : void 0
30
- });
31
- if (container.context.json) {
32
- console.log(JSON.stringify(a, null, 2));
33
- } else if (container.context.quiet) {
34
- console.log(a.id);
35
- } else {
36
- printSuccess(`Added agent ${agentName(a.name)} (${a.adapter}) \u2192 ${a.id}`);
37
- }
38
- });
39
- agent.command("list").description("List all agents").action(async () => {
40
- await container.paths.requireInit();
41
- const agents = await container.agentService.list();
42
- if (container.context.json) {
43
- console.log(JSON.stringify(agents, null, 2));
44
- return;
45
- }
46
- if (container.context.quiet) {
47
- agents.forEach((a) => console.log(a.id));
48
- return;
49
- }
50
- if (agents.length === 0) {
51
- console.log(`
52
- No agents. Add one: ${dim("orch agent add <name> --adapter claude")}
53
- `);
54
- return;
55
- }
56
- const headers = ["STATUS", "AGENT", "ADAPTER", "TASK", "TIME"];
57
- const rows = agents.map((a) => [
58
- `${statusIcon(a.status)} ${a.status}`,
59
- agentName(a.name),
60
- a.adapter,
61
- a.current_task ?? dim("\u2014"),
62
- dim("\u2014")
63
- ]);
64
- console.log();
65
- printTable(headers, rows);
66
- const running = agents.filter((a) => a.status === "running").length;
67
- console.log(
68
- `
69
- ${agents.length} agents \xB7 ${running} running \xB7 ${formatTokens(agents.reduce((sum, a) => sum + (a.stats.tokens_used ?? 0), 0))} tokens total
70
- `
71
- );
72
- });
73
- agent.command("status <id>").description("Show agent details").action(async (id) => {
74
- await container.paths.requireInit();
75
- const a = await container.agentService.get(id);
76
- if (container.context.json) {
77
- console.log(JSON.stringify(a, null, 2));
78
- return;
79
- }
80
- console.log(`
81
- ${a.name}`);
82
- console.log(` ${"\u2550".repeat(42)}`);
83
- console.log();
84
- const pairs = [
85
- ["Adapter", `${a.adapter}${a.config.model ? ` (${a.config.model})` : ""}`],
86
- ["Status", `${statusIcon(a.status)} ${a.status}`],
87
- ["Policy", a.config.approval_policy ?? "auto"]
88
- ];
89
- if (a.current_task) pairs.push(["Task", a.current_task]);
90
- if (a.role) pairs.push(["Role", a.role]);
91
- if (a.config.skills?.length) pairs.push(["Skills", a.config.skills.join(", ")]);
92
- printKeyValue(pairs);
93
- console.log(`
94
- Stats
95
- ${"\u2500".repeat(42)}`);
96
- printKeyValue([
97
- ["Tasks completed", String(a.stats.tasks_completed)],
98
- ["Tasks failed", String(a.stats.tasks_failed)],
99
- ["Total runs", String(a.stats.total_runs)],
100
- ["Tokens used", formatTokens(a.stats.tokens_used ?? 0)]
101
- ]);
102
- console.log();
103
- });
104
- agent.command("edit <id>").description("Edit an agent in $EDITOR").action(async (id) => {
105
- await container.paths.requireInit();
106
- const a = await container.agentService.get(id);
107
- const initial = agentToEditorContent({
108
- name: a.name,
109
- model: a.config.model,
110
- role: a.role
111
- });
112
- const edited = await openInEditor(initial);
113
- const parsed = agentFromEditorContent(edited);
114
- const updated = await container.agentService.update(id, {
115
- name: parsed.name,
116
- role: parsed.role,
117
- model: parsed.model
118
- });
119
- if (container.context.json) {
120
- console.log(JSON.stringify(updated, null, 2));
121
- } else if (container.context.quiet) {
122
- console.log(updated.id);
123
- } else {
124
- printSuccess(`Updated agent ${agentName(updated.name)} (${updated.id})`);
125
- }
126
- });
127
- agent.command("remove <id>").description("Remove an agent").action(async (id) => {
128
- await container.paths.requireInit();
129
- await container.agentService.remove(id);
130
- printSuccess(`Removed agent ${id}`);
131
- });
132
- agent.command("disable <id>").description("Disable an agent").action(async (id) => {
133
- await container.paths.requireInit();
134
- await container.agentService.disable(id);
135
- printSuccess(`Disabled agent ${id}`);
136
- });
137
- agent.command("enable <id>").description("Enable an agent").action(async (id) => {
138
- await container.paths.requireInit();
139
- await container.agentService.enable(id);
140
- printSuccess(`Enabled agent ${id}`);
141
- });
142
- agent.command("autonomous <id>").description("Toggle autonomous mode for an agent").option("--on", "Enable autonomous mode").option("--off", "Disable autonomous mode").action(async (id, opts) => {
143
- await container.paths.requireInit();
144
- const current = await container.agentService.get(id);
145
- const enable = opts.on ? true : opts.off ? false : !current.autonomous;
146
- const a = await container.agentService.setAutonomous(id, enable);
147
- if (container.context.json) {
148
- console.log(JSON.stringify(a, null, 2));
149
- } else if (container.context.quiet) {
150
- console.log(a.id);
151
- } else {
152
- printSuccess(`Autonomous mode ${enable ? "enabled" : "disabled"} for agent ${agentName(a.name)} (${a.id})`);
153
- }
154
- });
155
- }
156
-
157
- export { registerAgentCommand };
@@ -1,11 +0,0 @@
1
- import {b as b$1}from'./chunk-ZU6AY2VU.js';import {randomBytes}from'crypto';import s from'fs/promises';import i from'path';import P from'js-yaml';import'fs';async function D(r,t){let n=i.dirname(r);await k(n);let e=i.join(n,`.${i.basename(r)}.${randomBytes(4).toString("hex")}.tmp`);try{await s.writeFile(e,t,"utf-8"),await s.rename(e,r);}catch(l){throw await s.unlink(e).catch(()=>{}),l}}async function L(r){try{let t=await s.readFile(r,"utf-8");return P.load(t)}catch(t){if(f(t))return null;throw t}}async function B(r,t){let n=P.dump(t,{indent:2,lineWidth:120,noRefs:true,sortKeys:false});await D(r,n);}async function M(r){try{let t=await s.readFile(r,"utf-8");return JSON.parse(t)}catch(t){if(f(t))return null;throw t}}async function W(r,t){let n=JSON.stringify(t,null,2)+`
2
- `;await D(r,n);}var x=4096;async function A(r,t){let n=i.dirname(r);await k(n);let e=JSON.stringify(t)+`
3
- `;if(Buffer.byteLength(e,"utf-8")>x&&t!==null&&typeof t=="object"){let a=t;if(typeof a.data=="string"&&a.data.length>0){let u=JSON.stringify({...a,data:""})+`
4
- `,h=Buffer.byteLength(u,"utf-8"),m=x-h-3;if(m>0){let g=a.data.slice(0,m);e=JSON.stringify({...a,data:g+"\u2026"})+`
5
- `;}}}let o=await s.open(r,"a");try{await o.write(e,null,"utf-8");}finally{await o.close();}}var b=50*1024*1024;async function Y(r){try{let t=await s.stat(r);return t.size>b?(process.stderr.write(`[readJsonl] file too large (${(t.size/1024/1024).toFixed(1)} MB), reading tail only: ${r}
6
- `),z(r,200)):E(r)}catch(t){if(f(t))return [];throw t}}async function z(r,t){try{let n=await s.stat(r);if(n.size<32768)return (await E(r)).slice(-t);let e=await s.open(r,"r");try{let l=Math.min(n.size,n.size>1048576?131072:65536),o=Math.max(0,n.size-l),a=o,u="";for(let g=0;g<4&&o>=0;g++){a=o;let y=Math.min(l,n.size-o),w=Buffer.alloc(y);await e.read(w,0,y,o),u=w.toString("utf-8")+u;let j=u.split(`
7
- `).filter($=>$.trim().length>0);if(j.length>=t+1)return p(j.slice(-t));if(o===0)break;o=Math.max(0,o-l);}let h=u.split(`
8
- `).filter(g=>g.trim().length>0),m=a>0?h.slice(1):h;return p(m.slice(-t))}finally{await e.close();}}catch(n){if(f(n))return [];throw n}}async function E(r){let n=(await s.readFile(r,"utf-8")).split(`
9
- `).filter(e=>e.trim().length>0);return p(n)}function p(r){let t=[];for(let n of r){let e=n.trim();if(e)try{t.push(JSON.parse(e));}catch{process.stderr.write(`[readJsonl] skipping corrupt line: ${e.slice(0,200)}
10
- `);}}return t}async function k(r){await s.mkdir(r,{recursive:true});}async function v(r){try{return await s.access(r),!0}catch{return false}}async function Z(r,t){try{let n=await s.readdir(r);return t?n.filter(e=>e.endsWith(t)):n}catch(n){if(f(n))return [];throw n}}function f(r){return r instanceof Error&&"code"in r&&r.code==="ENOENT"}var N=".orchestry",R=/^[A-Za-z0-9._-]+$/,J=class{constructor(t){this.projectRoot=t;}get root(){return i.join(this.projectRoot,N)}get configPath(){return i.join(this.root,"config.yml")}get statePath(){return i.join(this.root,"state.json")}get lockPath(){return i.join(this.root,"orchestry.lock")}get tasksDir(){return i.join(this.root,"tasks")}get agentsDir(){return i.join(this.root,"agents")}get runsDir(){return i.join(this.root,"runs")}get templatesDir(){return i.join(this.root,"templates")}get logsDir(){return i.join(this.root,"logs")}get contextDir(){return i.join(this.root,"context")}contextPath(t){return i.join(this.contextDir,`${c(t)}.json`)}get messagesDir(){return i.join(this.root,"messages")}messagePath(t){return i.join(this.messagesDir,`${c(t)}.json`)}get goalsDir(){return i.join(this.root,"goals")}goalPath(t){return i.join(this.goalsDir,`${c(t)}.yml`)}get teamsDir(){return i.join(this.root,"teams")}teamPath(t){return i.join(this.teamsDir,`${c(t)}.yml`)}get gitignorePath(){return i.join(this.root,".gitignore")}get workspaceExcludePath(){return i.join(this.root,"workspace-exclude")}taskPath(t){return i.join(this.tasksDir,`${c(t)}.yml`)}agentPath(t){return i.join(this.agentsDir,`${c(t)}.yml`)}runPath(t){return i.join(this.runsDir,`${c(t)}.json`)}runEventsPath(t){return i.join(this.runsDir,`${c(t)}.jsonl`)}defaultTemplatePath(){return i.join(this.templatesDir,"default.md")}async isInitialized(){return v(this.root)}async requireInit(){if(!await this.isInitialized())throw new b$1}};function c(r){if(!R.test(r))throw new Error(`Invalid identifier: "${r}"`);return r}function G(r,t){let n=i.resolve(r),e=i.resolve(t);if(!n.startsWith(e+i.sep)&&n!==e)throw new Error(`Workspace path "${r}" is outside project root`)}export{L as a,B as b,M as c,W as d,A as e,Y as f,z as g,k as h,v as i,Z as j,J as k,c as l,G as m};//# sourceMappingURL=chunk-2B32FPEB.js.map
11
- //# sourceMappingURL=chunk-2B32FPEB.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/infrastructure/storage/fs-utils.ts","../src/infrastructure/storage/paths.ts"],"names":["atomicWrite","filePath","content","dir","path","ensureDir","tmpPath","randomBytes","fs","err","readYaml","yaml","isENOENT","writeYaml","data","readJson","writeJson","PIPE_BUF","appendJsonl","record","line","obj","shell","overhead","budget","truncated","fd","MAX_JSONL_READ_SIZE","readJsonl","stat","readJsonlTail","readAndParseJsonl","count","chunkSize","position","earliestReadPosition","tail","attempt","readSize","buf","lines","l","parseJsonlLines","safeLines","results","raw","dirPath","pathExists","listFiles","ext","entries","ORCHESTRY_DIR","ID_PATTERN","Paths","projectRoot","key","sanitizeId","id","NotInitializedError","validateWorkspacePath","workspacePath","resolved","root"],"mappings":"6JAgBA,eAAsBA,CAAAA,CAAYC,CAAAA,CAAkBC,EAAgC,CAClF,IAAMC,EAAMC,CAAAA,CAAK,OAAA,CAAQH,CAAQ,CAAA,CACjC,MAAMI,CAAAA,CAAUF,CAAG,EAEnB,IAAMG,CAAAA,CAAUF,EAAK,IAAA,CAAKD,CAAAA,CAAK,IAAIC,CAAAA,CAAK,QAAA,CAASH,CAAQ,CAAC,CAAA,CAAA,EAAIM,YAAY,CAAC,CAAA,CAAE,SAAS,KAAK,CAAC,CAAA,IAAA,CAAM,CAAA,CAElG,GAAI,CACF,MAAMC,EAAG,SAAA,CAAUF,CAAAA,CAASJ,EAAS,OAAO,CAAA,CAC5C,MAAMM,CAAAA,CAAG,MAAA,CAAOF,EAASL,CAAQ,EACnC,OAASQ,CAAAA,CAAK,CAEZ,YAAMD,CAAAA,CAAG,MAAA,CAAOF,CAAO,CAAA,CAAE,MAAM,IAAM,CAAC,CAAC,CAAA,CACjCG,CACR,CACF,CAKA,eAAsBC,EAAYT,CAAAA,CAAqC,CACrE,GAAI,CACF,IAAMC,EAAU,MAAMM,CAAAA,CAAG,SAASP,CAAAA,CAAU,OAAO,CAAA,CACnD,OAAOU,EAAK,IAAA,CAAKT,CAAO,CAC1B,CAAA,MAASO,CAAAA,CAAK,CACZ,GAAIG,CAAAA,CAASH,CAAG,CAAA,CAAG,OAAO,KAC1B,MAAMA,CACR,CACF,CAKA,eAAsBI,EAAaZ,CAAAA,CAAkBa,CAAAA,CAAwB,CAC3E,IAAMZ,EAAUS,CAAAA,CAAK,IAAA,CAAKG,EAAM,CAC9B,MAAA,CAAQ,EACR,SAAA,CAAW,GAAA,CACX,OAAQ,IAAA,CACR,QAAA,CAAU,KACZ,CAAC,CAAA,CACD,MAAMd,CAAAA,CAAYC,CAAA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oB,CAC1B,OAAOrD,CAAAA,CAAK,IAAA,CAAK,IAAA,CAAK,OAAA,CAAS,CAAA,EAAGoD,CAAAA,CAAWC,CAAE,CAAC,CAAA,KAAA,CAAO,CACzD,CAEA,aAAA,CAAcA,CAAAA,CAAoB,CAChC,OAAOrD,CAAAA,CAAK,IAAA,CAAK,IAAA,CAAK,OAAA,CAAS,CAAA,EAAGoD,CAAAA,CAAWC,CAAE,CAAC,CAAA,MAAA,CAAQ,CAC1D,CAEA,mBAAA,EAA8B,CAC5B,OAAOrD,CAAAA,CAAK,IAAA,CAAK,IAAA,CAAK,YAAA,CAAc,YAAY,CAClD,CAEA,MAAM,aAAA,EAAkC,CACtC,OAAO2C,CAAAA,CAAW,IAAA,CAAK,IAAI,CAC7B,CAEA,MAAM,WAAA,EAA6B,CACjC,GAAI,CAAE,MAAM,IAAA,CAAK,eAAc,CAC7B,MAAM,IAAIW,GAEd,CACF,EAQO,SAASF,CAAAA,CAAWC,CAAAA,CAAoB,CAC7C,GAAI,CAACL,CAAAA,CAAW,IAAA,CAAKK,CAAE,CAAA,CACrB,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBA,CAAE,CAAA,CAAA,CAAG,CAAA,CAE/C,OAAOA,CACT,CAMO,SAASE,CAAAA,CAAsBC,CAAAA,CAAuBN,EAA2B,CACtF,IAAMO,CAAAA,CAAWzD,CAAAA,CAAK,OAAA,CAAQwD,CAAa,CAAA,CACrCE,CAAAA,CAAO1D,CAAAA,CAAK,OAAA,CAAQkD,CAAW,CAAA,CAErC,GAAI,CAACO,CAAAA,CAAS,UAAA,CAAWC,CAAAA,CAAO1D,CAAAA,CAAK,GAAG,CAAA,EAAKyD,CAAAA,GAAaC,CAAAA,CACxD,MAAM,IAAI,KAAA,CAAM,CAAA,gBAAA,EAAmBF,CAAa,CAAA,yBAAA,CAA2B,CAE/E","file":"chunk-2B32FPEB.js","sourcesContent":["/**\n * Low-level filesystem utilities.\n *\n * All file persistence goes through these functions.\n * atomicWrite guarantees no partial reads via temp → rename.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport yaml from 'js-yaml';\n\n/**\n * Write file atomically: write to temp file, then rename.\n * Prevents corrupted reads on concurrent access.\n */\nexport async function atomicWrite(filePath: string, content: string): Promise<void> {\n const dir = path.dirname(filePath);\n await ensureDir(dir);\n\n const tmpPath = path.join(dir, `.${path.basename(filePath)}.${randomBytes(4).toString('hex')}.tmp`);\n\n try {\n await fs.writeFile(tmpPath, content, 'utf-8');\n await fs.rename(tmpPath, filePath);\n } catch (err) {\n // Clean up temp file on failure\n await fs.unlink(tmpPath).catch(() => {});\n throw err;\n }\n}\n\n/**\n * Read and parse a YAML file. Returns null if file does not exist.\n */\nexport async function readYaml<T>(filePath: string): Promise<T | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return yaml.load(content) as T;\n } catch (err) {\n if (isENOENT(err)) return null;\n throw err;\n }\n}\n\n/**\n * Write data as YAML atomically.\n */\nexport async function writeYaml<T>(filePath: string, data: T): Promise<void> {\n const content = yaml.dump(data, {\n indent: 2,\n lineWidth: 120,\n noRefs: true,\n sortKeys: false,\n });\n await atomicWrite(filePath, content);\n}\n\n/**\n * Read and parse a JSON file. Returns null if file does not exist.\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return JSON.parse(content) as T;\n } catch (err) {\n if (isENOENT(err)) return null;\n throw err;\n }\n}\n\n/**\n * Write data as JSON atomically.\n */\nexport async function writeJson<T>(filePath: string, data: T): Promise<void> {\n const content = JSON.stringify(data, null, 2) + '\\n';\n await atomicWrite(filePath, content);\n}\n\n/**\n * POSIX PIPE_BUF — writes up to this size are guaranteed atomic with O_APPEND.\n * 4096 on Linux/macOS. We leave some room for encoding overhead.\n */\nconst PIPE_BUF = 4096;\n\n/**\n * Append a JSON record to a .jsonl file (newline-delimited JSON).\n *\n * Uses a file handle opened with 'a' (O_APPEND) to ensure atomic writes.\n * On POSIX, O_APPEND guarantees that each write() call appends atomically\n * when the data fits within PIPE_BUF (typically 4096 bytes), preventing\n * interleaving from concurrent writers.\n *\n * If the serialized line exceeds PIPE_BUF, the record's `data` field is\n * truncated so the entire line fits within the atomic-write limit.\n * This prevents interleaving corruption from concurrent writers.\n */\nexport async function appendJsonl(filePath: string, record: unknown): Promise<void> {\n const dir = path.dirname(filePath);\n await ensureDir(dir);\n let line = JSON.stringify(record) + '\\n';\n\n // If the line exceeds PIPE_BUF, truncate the `data` field to fit\n const byteLen = Buffer.byteLength(line, 'utf-8');\n if (byteLen > PIPE_BUF && record !== null && typeof record === 'object') {\n const obj = record as Record<string, unknown>;\n if (typeof obj.data === 'string' && obj.data.length > 0) {\n // Measure overhead without data to know how much room data gets\n const shell = JSON.stringify({ ...obj, data: '' }) + '\\n';\n const overhead = Buffer.byteLength(shell, 'utf-8');\n const budget = PIPE_BUF - overhead - 3; // 3 bytes for the '…' suffix (UTF-8 ellipsis)\n if (budget > 0) {\n // Slice to budget chars — for ASCII (most event data) this equals bytes.\n // For multi-byte chars the result may be slightly over PIPE_BUF,\n // which is acceptable on local filesystems (ext4/APFS hold inode lock).\n const truncated = obj.data.slice(0, budget);\n line = JSON.stringify({ ...obj, data: truncated + '…' }) + '\\n';\n }\n }\n }\n\n const fd = await fs.open(filePath, 'a');\n try {\n await fd.write(line, null, 'utf-8');\n } finally {\n await fd.close();\n }\n}\n\n/** Max file size for full readJsonl (50 MB). Larger files use tail read. */\nconst MAX_JSONL_READ_SIZE = 50 * 1024 * 1024;\n\n/**\n * Read all records from a .jsonl file.\n * Falls back to reading only the last 200 records if the file exceeds MAX_JSONL_READ_SIZE.\n */\nexport async function readJsonl<T>(filePath: string): Promise<T[]> {\n try {\n const stat = await fs.stat(filePath);\n if (stat.size > MAX_JSONL_READ_SIZE) {\n process.stderr.write(\n `[readJsonl] file too large (${(stat.size / 1024 / 1024).toFixed(1)} MB), reading tail only: ${filePath}\\n`,\n );\n return readJsonlTail<T>(filePath, 200);\n }\n return readAndParseJsonl<T>(filePath);\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\n/**\n * Read the last N records from a .jsonl file.\n *\n * Reads the file in reverse chunks to avoid loading multi-MB files into memory.\n * Falls back to full read for small files (< 32KB).\n */\nexport async function readJsonlTail<T>(filePath: string, count: number): Promise<T[]> {\n try {\n const stat = await fs.stat(filePath);\n // For small files, read directly and slice (avoid mutual recursion with readJsonl)\n if (stat.size < 32768) {\n return (await readAndParseJsonl<T>(filePath)).slice(-count);\n }\n\n // Read from end in chunks to find enough lines\n // Use larger chunks for bigger files (tool_result events can be 8KB+ per line)\n const fd = await fs.open(filePath, 'r');\n try {\n const chunkSize = Math.min(stat.size, stat.size > 1_048_576 ? 131072 : 65536);\n let position = Math.max(0, stat.size - chunkSize);\n let earliestReadPosition = position;\n let tail = '';\n\n // Read up to 4 chunks from the end\n for (let attempt = 0; attempt < 4 && position >= 0; attempt++) {\n earliestReadPosition = position;\n const readSize = Math.min(chunkSize, stat.size - position);\n const buf = Buffer.alloc(readSize);\n await fd.read(buf, 0, readSize, position);\n tail = buf.toString('utf-8') + tail;\n\n const lines = tail.split('\\n').filter((l) => l.trim().length > 0);\n if (lines.length >= count + 1) {\n // +1 because first line might be partial\n return parseJsonlLines<T>(lines.slice(-count));\n }\n if (position === 0) break;\n position = Math.max(0, position - chunkSize);\n }\n\n // Parse whatever we got\n const lines = tail.split('\\n').filter((l) => l.trim().length > 0);\n // Skip first line if we didn't read from start (could be partial)\n const safeLines = earliestReadPosition > 0 ? lines.slice(1) : lines;\n return parseJsonlLines<T>(safeLines.slice(-count));\n } finally {\n await fd.close();\n }\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\n/** Read a file and parse all JSONL records. */\nasync function readAndParseJsonl<T>(filePath: string): Promise<T[]> {\n const content = await fs.readFile(filePath, 'utf-8');\n const lines = content.split('\\n').filter((l) => l.trim().length > 0);\n return parseJsonlLines<T>(lines);\n}\n\n/**\n * Parse JSONL lines with error tolerance — corrupt lines are logged and skipped.\n */\nfunction parseJsonlLines<T>(lines: string[]): T[] {\n const results: T[] = [];\n for (const raw of lines) {\n const line = raw.trim();\n if (!line) continue;\n try {\n results.push(JSON.parse(line) as T);\n } catch {\n process.stderr.write(`[readJsonl] skipping corrupt line: ${line.slice(0, 200)}\\n`);\n }\n }\n return results;\n}\n\n/**\n * Ensure a directory exists, creating it recursively if needed.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fs.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Check if a path exists.\n */\nexport async function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * List files in a directory matching an optional extension filter.\n */\nexport async function listFiles(dirPath: string, ext?: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dirPath);\n if (ext) {\n return entries.filter((e) => e.endsWith(ext));\n }\n return entries;\n } catch (err) {\n if (isENOENT(err)) return [];\n throw err;\n }\n}\n\nfunction isENOENT(err: unknown): boolean {\n return err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code === 'ENOENT';\n}\n","/**\n * Path resolution for .orchestry/ directory.\n *\n * All path construction goes through this module.\n * Validates initialization state and sanitizes identifiers.\n */\n\nimport path from 'node:path';\nimport { accessSync } from 'node:fs';\nimport { NotInitializedError } from '../../domain/errors.js';\nimport { pathExists } from './fs-utils.js';\n\nconst ORCHESTRY_DIR = '.orchestry';\nconst ID_PATTERN = /^[A-Za-z0-9._-]+$/;\n\nexport class Paths {\n constructor(private readonly projectRoot: string) {}\n\n /** Root .orchestry/ directory */\n get root(): string {\n return path.join(this.projectRoot, ORCHESTRY_DIR);\n }\n\n get configPath(): string {\n return path.join(this.root, 'config.yml');\n }\n\n get statePath(): string {\n return path.join(this.root, 'state.json');\n }\n\n get lockPath(): string {\n return path.join(this.root, 'orchestry.lock');\n }\n\n get tasksDir(): string {\n return path.join(this.root, 'tasks');\n }\n\n get agentsDir(): string {\n return path.join(this.root, 'agents');\n }\n\n get runsDir(): string {\n return path.join(this.root, 'runs');\n }\n\n get templatesDir(): string {\n return path.join(this.root, 'templates');\n }\n\n get logsDir(): string {\n return path.join(this.root, 'logs');\n }\n\n get contextDir(): string {\n return path.join(this.root, 'context');\n }\n\n contextPath(key: string): string {\n return path.join(this.contextDir, `${sanitizeId(key)}.json`);\n }\n\n get messagesDir(): string {\n return path.join(this.root, 'messages');\n }\n\n messagePath(id: string): string {\n return path.join(this.messagesDir, `${sanitizeId(id)}.json`);\n }\n\n get goalsDir(): string {\n return path.join(this.root, 'goals');\n }\n\n goalPath(id: string): string {\n return path.join(this.goalsDir, `${sanitizeId(id)}.yml`);\n }\n\n get teamsDir(): string {\n return path.join(this.root, 'teams');\n }\n\n teamPath(id: string): string {\n return path.join(this.teamsDir, `${sanitizeId(id)}.yml`);\n }\n\n get gitignorePath(): string {\n return path.join(this.root, '.gitignore');\n }\n\n get workspaceExcludePath(): string {\n return path.join(this.root, 'workspace-exclude');\n }\n\n taskPath(id: string): string {\n return path.join(this.tasksDir, `${sanitizeId(id)}.yml`);\n }\n\n agentPath(id: string): string {\n return path.join(this.agentsDir, `${sanitizeId(id)}.yml`);\n }\n\n runPath(id: string): string {\n return path.join(this.runsDir, `${sanitizeId(id)}.json`);\n }\n\n runEventsPath(id: string): string {\n return path.join(this.runsDir, `${sanitizeId(id)}.jsonl`);\n }\n\n defaultTemplatePath(): string {\n return path.join(this.templatesDir, 'default.md');\n }\n\n async isInitialized(): Promise<boolean> {\n return pathExists(this.root);\n }\n\n async requireInit(): Promise<void> {\n if (!(await this.isInitialized())) {\n throw new NotInitializedError();\n }\n }\n}\n\n/**\n * Validate an identifier for use in file paths.\n * Only allows [A-Za-z0-9._-] characters.\n * Rejects identifiers containing forbidden characters (path separators, etc.)\n * to prevent path traversal attacks.\n */\nexport function sanitizeId(id: string): string {\n if (!ID_PATTERN.test(id)) {\n throw new Error(`Invalid identifier: \"${id}\"`);\n }\n return id;\n}\n\n/**\n * Validate that a workspace path is within the project root.\n * Prevents path traversal attacks.\n */\nexport function validateWorkspacePath(workspacePath: string, projectRoot: string): void {\n const resolved = path.resolve(workspacePath);\n const root = path.resolve(projectRoot);\n\n if (!resolved.startsWith(root + path.sep) && resolved !== root) {\n throw new Error(`Workspace path \"${workspacePath}\" is outside project root`);\n }\n}\n\n/**\n * Resolve project root by walking up from cwd looking for .orchestry/.\n * Returns cwd if not found (for init command).\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string {\n let dir = path.resolve(startDir);\n const root = path.parse(dir).root;\n\n while (dir !== root) {\n try {\n accessSync(path.join(dir, '.orchestry'));\n return dir;\n } catch {\n // Not found, go up\n }\n dir = path.dirname(dir);\n }\n\n // Not found — return original dir (for init command)\n return startDir;\n}\n"]}
@@ -1,46 +0,0 @@
1
- #!/usr/bin/env node
2
- // src/domain/transitions.ts
3
- var VALID_TRANSITIONS = {
4
- todo: ["in_progress", "cancelled"],
5
- in_progress: ["review", "retrying", "failed", "cancelled"],
6
- retrying: ["in_progress", "failed", "cancelled"],
7
- review: ["done", "todo", "cancelled"],
8
- done: [],
9
- failed: ["todo", "retrying"],
10
- cancelled: ["todo"]
11
- };
12
- var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["done", "failed", "cancelled"]);
13
- function canTransition(from, to) {
14
- return VALID_TRANSITIONS[from].includes(to);
15
- }
16
- function isTerminal(status) {
17
- return TERMINAL_STATUSES.has(status);
18
- }
19
- function isDispatchable(status) {
20
- return status === "todo" || status === "retrying";
21
- }
22
- function isBlocked(task, allTasks) {
23
- if (task.depends_on.length === 0) return false;
24
- return task.depends_on.some((depId) => {
25
- const dep = allTasks.find((t) => t.id === depId);
26
- return !dep || dep.status !== "done";
27
- });
28
- }
29
- function resolveFailureStatus(task) {
30
- if (task.attempts < task.max_attempts) {
31
- return "retrying";
32
- }
33
- return "failed";
34
- }
35
- function resolveCompletionStatus(task, success, _autoApprove) {
36
- if (success) {
37
- return "review";
38
- }
39
- return resolveFailureStatus(task);
40
- }
41
- function calculateRetryDelay(attempt, baseDelayMs, maxDelayMs) {
42
- const delay = baseDelayMs * Math.pow(2, attempt);
43
- return Math.min(delay, maxDelayMs);
44
- }
45
-
46
- export { calculateRetryDelay, canTransition, isBlocked, isDispatchable, isTerminal, resolveCompletionStatus, resolveFailureStatus };
@@ -1,101 +0,0 @@
1
- #!/usr/bin/env node
2
- import fs from 'fs/promises';
3
- import path from 'path';
4
- import os from 'os';
5
- import { execFile } from 'child_process';
6
-
7
- var PACKAGE_NAME = "@oxgeneral/orch";
8
- var CACHE_DIR = path.join(os.homedir(), ".orchestry");
9
- var CACHE_FILE = path.join(CACHE_DIR, "update-check.json");
10
- var CHECK_INTERVAL_MS = 4 * 60 * 60 * 1e3;
11
- function compareSemver(a, b) {
12
- const pa = a.split(".").map(Number);
13
- const pb = b.split(".").map(Number);
14
- for (let i = 0; i < 3; i++) {
15
- const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
16
- if (diff !== 0) return diff > 0 ? 1 : -1;
17
- }
18
- return 0;
19
- }
20
- async function readCache() {
21
- try {
22
- const raw = await fs.readFile(CACHE_FILE, "utf-8");
23
- const data = JSON.parse(raw);
24
- if (Date.now() - data.checked_at < CHECK_INTERVAL_MS) return data;
25
- } catch {
26
- }
27
- return null;
28
- }
29
- async function writeCache(latest) {
30
- await fs.mkdir(CACHE_DIR, { recursive: true });
31
- const data = { latest, checked_at: Date.now() };
32
- const tmp = `${CACHE_FILE}.tmp.${process.pid}`;
33
- await fs.writeFile(tmp, JSON.stringify(data), "utf-8");
34
- await fs.rename(tmp, CACHE_FILE);
35
- }
36
- function fetchLatestVersion() {
37
- return new Promise((resolve) => {
38
- execFile("npm", ["view", PACKAGE_NAME, "version", "--json"], { timeout: 5e3 }, (err, stdout) => {
39
- if (err) return resolve(null);
40
- try {
41
- resolve(JSON.parse(stdout.trim()));
42
- } catch {
43
- resolve(null);
44
- }
45
- });
46
- });
47
- }
48
- async function checkForUpdate(currentVersion) {
49
- try {
50
- const cached = await readCache();
51
- if (cached) {
52
- return {
53
- current: currentVersion,
54
- latest: cached.latest,
55
- updateAvailable: compareSemver(cached.latest, currentVersion) > 0
56
- };
57
- }
58
- fetchLatestVersion().then(async (latest) => {
59
- if (latest) await writeCache(latest).catch(() => {
60
- });
61
- }).catch(() => {
62
- });
63
- return null;
64
- } catch {
65
- return null;
66
- }
67
- }
68
- async function checkForUpdateCached(currentVersion) {
69
- try {
70
- const cached = await readCache();
71
- if (!cached) return null;
72
- return {
73
- current: currentVersion,
74
- latest: cached.latest,
75
- updateAvailable: compareSemver(cached.latest, currentVersion) > 0
76
- };
77
- } catch {
78
- return null;
79
- }
80
- }
81
- async function checkForUpdateNow(currentVersion) {
82
- const latest = await fetchLatestVersion();
83
- if (!latest) return null;
84
- await writeCache(latest).catch(() => {
85
- });
86
- return {
87
- current: currentVersion,
88
- latest,
89
- updateAvailable: compareSemver(latest, currentVersion) > 0
90
- };
91
- }
92
- function printUpdateNotification(info) {
93
- if (!info.updateAvailable) return;
94
- const msg = `
95
- Update available: ${info.current} \u2192 ${info.latest}
96
- Run: npm install -g ${PACKAGE_NAME}
97
- `;
98
- process.stderr.write(msg);
99
- }
100
-
101
- export { checkForUpdate, checkForUpdateCached, checkForUpdateNow, printUpdateNotification };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/infrastructure/adapters/registry.ts"],"names":["AdapterRegistry","adapter","kind"],"mappings":"AASO,IAAMA,EAAN,KAAsB,CACV,SAAW,IAAI,GAAA,CAEhC,SAASC,CAAAA,CAA8B,CACrC,KAAK,QAAA,CAAS,GAAA,CAAIA,EAAQ,IAAA,CAAMA,CAAO,EACzC,CAEA,GAAA,CAAIC,EAAyC,CAC3C,OAAO,IAAA,CAAK,QAAA,CAAS,IAAIA,CAAI,CAC/B,CAEA,OAAA,CAAQA,CAAAA,CAA6B,CACnC,IAAMD,CAAAA,CAAU,KAAK,QAAA,CAAS,GAAA,CAAIC,CAAI,CAAA,CACtC,GAAI,CAACD,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,CAAA,kBAAA,EAAqBC,CAAI,CAAA,cAAA,EAAiB,KAAK,SAAA,EAAU,CAAE,KAAK,IAAI,CAAC,EAAE,CAAA,CAEzF,OAAOD,CACT,CAEA,IAAA,EAAwB,CACtB,OAAO,KAAA,CAAM,KAAK,IAAA,CAAK,QAAA,CAAS,QAAQ,CAC1C,CAEA,SAAA,EAAsB,CACpB,OAAO,KAAA,CAAM,KAAK,IAAA,CAAK,QAAA,CAAS,MAAM,CACxC,CAEA,GAAA,CAAIC,CAAAA,CAAuB,CACzB,OAAO,IAAA,CAAK,SAAS,GAAA,CAAIA,CAAI,CAC/B,CACF","file":"chunk-6HENRUYZ.js","sourcesContent":["/**\n * Adapter registry.\n *\n * Maps adapter kind strings to adapter instances.\n * Pre-populated at startup in the container.\n */\n\nimport type { IAgentAdapter } from './interface.js';\n\nexport class AdapterRegistry {\n private readonly adapters = new Map<string, IAgentAdapter>();\n\n register(adapter: IAgentAdapter): void {\n this.adapters.set(adapter.kind, adapter);\n }\n\n get(kind: string): IAgentAdapter | undefined {\n return this.adapters.get(kind);\n }\n\n require(kind: string): IAgentAdapter {\n const adapter = this.adapters.get(kind);\n if (!adapter) {\n throw new Error(`Unknown adapter: \"${kind}\". Available: ${this.listKinds().join(', ')}`);\n }\n return adapter;\n }\n\n list(): IAgentAdapter[] {\n return Array.from(this.adapters.values());\n }\n\n listKinds(): string[] {\n return Array.from(this.adapters.keys());\n }\n\n has(kind: string): boolean {\n return this.adapters.has(kind);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/domain/task.ts","../src/infrastructure/template/template-engine.ts"],"names":["AUTONOMOUS_LABEL","LiquidTemplateEngine","options","Liquid","template","context","renderPromise","timer","timeoutPromise","_","reject","buildPromptContext","task","agent","attempt","workspacePath","config","allAgents","retryContext","sharedContext","feedback","rawMessages","agentById","a","messages","m","DEFA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CAAA,CAASI,GAAa,EAAC,EAAG,GAAA,CAAKM,CAAAA,GAAO,CACpC,EAAA,CAAIA,CAAAA,CAAE,EAAA,CACN,IAAA,CAAMA,EAAE,IAAA,CACR,IAAA,CAAMA,CAAAA,CAAE,IAAA,CACR,OAAA,CAASA,CAAAA,CAAE,OACb,CAAA,CAAE,EACF,OAAA,CAAST,CAAAA,CAAU,CAAA,CAAIA,CAAAA,CAAU,KACjC,cAAA,CAAgBC,CAAAA,CAChB,KAAA,CAAOD,CAAAA,CAAU,EAAII,CAAAA,CAAe,MAAA,CACpC,QAAA,CAAAE,CAAAA,CACA,cAAA,CAAgBD,CAAAA,EAAiB,MAAA,CAAO,IAAA,CAAKA,CAAa,CAAA,CAAE,MAAA,CAAS,CAAA,CAAIA,CAAAA,CAAgB,OACzF,QAAA,CAAAK,CACF,CACF,KAGaE,CAAAA,CAA0B,CAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","file":"chunk-AELEEEV3.js","sourcesContent":["/**\n * Task domain model.\n *\n * A Task is the unit of work in the orchestrator.\n * It moves through a state machine: todo → in_progress → review → done.\n */\n\nexport type TaskStatus =\n | 'todo'\n | 'in_progress'\n | 'retrying'\n | 'review'\n | 'done'\n | 'failed'\n | 'cancelled';\n\n/** Label applied to tasks auto-generated by the orchestrator for autonomous agents. */\nexport const AUTONOMOUS_LABEL = 'autonomous' as const;\n\nexport type WorkspaceMode = 'shared' | 'worktree' | 'isolated';\n\nexport type ReviewCriterion = 'test_pass' | 'typecheck' | 'lint';\n\nexport interface ReviewResult {\n criterion: ReviewCriterion;\n passed: boolean;\n output: string;\n}\n\nexport interface TaskProof {\n branch?: string;\n pr_url?: string;\n files_changed: string[];\n test_results?: string;\n agent_summary?: string;\n}\n\nexport interface Task {\n id: string;\n title: string;\n description: string;\n status: TaskStatus;\n priority: number;\n assignee?: string;\n labels: string[];\n depends_on: string[];\n created_at: string;\n updated_at: string;\n attempts: number;\n max_attempts: number;\n workspace_mode?: WorkspaceMode;\n workspace?: string;\n proof?: TaskProof;\n review_criteria?: ReviewCriterion[];\n review_results?: ReviewResult[];\n scope?: string[];\n feedback?: string;\n}\n\nexport interface CreateTaskInput {\n title: string;\n description?: string;\n priority?: number;\n assignee?: string;\n labels?: string[];\n depends_on?: string[];\n max_attempts?: number;\n workspace_mode?: WorkspaceMode;\n review_criteria?: ReviewCriterion[];\n scope?: string[];\n}\n","/**\n * Template engine for prompt construction.\n *\n * Uses LiquidJS for Liquid-compatible templating with\n * task, agent, project, and run context variables.\n */\n\nimport type { Liquid } from 'liquidjs';\nimport type { Agent } from '../../domain/agent.js';\nimport type { OrchestratorConfig } from '../../domain/config.js';\nimport { AUTONOMOUS_LABEL, type Task } from '../../domain/task.js';\n\nexport interface ITemplateEngine {\n render(template: string, context: PromptContext): Promise<string>;\n}\n\nexport interface AgentInfo {\n id: string;\n name: string;\n role?: string;\n adapter: string;\n}\n\nexport interface RetryContext {\n previous_error: string;\n previous_output: string;\n}\n\nexport interface PromptContext {\n project: {\n name: string;\n description?: string;\n };\n task: {\n id: string;\n title: string;\n description: string;\n priority: number;\n labels: string[];\n scope?: string[];\n is_autonomous: boolean;\n };\n agent: {\n id: string;\n name: string;\n role?: string;\n };\n agents: AgentInfo[];\n attempt: number | null;\n workspace_path: string;\n retry?: RetryContext;\n feedback?: string;\n shared_context?: Record<string, string>;\n messages?: Array<{\n id: string;\n from: string;\n subject: string;\n body: string;\n sent_at: string;\n reply_to?: string;\n }>;\n}\n\nexport class LiquidTemplateEngine implements ITemplateEngine {\n private engine: Liquid | undefined;\n private readonly renderTimeoutMs: number;\n\n constructor(options?: { renderTimeoutMs?: number }) {\n this.renderTimeoutMs = options?.renderTimeoutMs ?? 5_000;\n }\n\n private async getEngine(): Promise<Liquid> {\n if (!this.engine) {\n const { Liquid } = await import('liquidjs');\n this.engine = new Liquid({\n strictFilters: false,\n strictVariables: false,\n });\n }\n return this.engine;\n }\n\n async render(template: string, context: PromptContext): Promise<string> {\n const engine = await this.getEngine();\n const renderPromise = engine.parseAndRender(template, context);\n\n if (this.renderTimeoutMs <= 0) {\n return renderPromise;\n }\n\n let timer: ReturnType<typeof setTimeout>;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Template render timed out after ${this.renderTimeoutMs}ms`)),\n this.renderTimeoutMs,\n );\n });\n\n try {\n return await Promise.race([renderPromise, timeoutPromise]);\n } finally {\n clearTimeout(timer!);\n }\n }\n}\n\n/**\n * Build prompt context from domain objects.\n */\nexport interface BuildPromptOptions {\n allAgents?: Agent[];\n retryContext?: RetryContext;\n sharedContext?: Record<string, string>;\n feedback?: string;\n messages?: import('../../domain/message.js').Message[];\n}\n\nexport function buildPromptContext(\n task: Task,\n agent: Agent,\n attempt: number,\n workspacePath: string,\n config: OrchestratorConfig,\n options?: BuildPromptOptions,\n): PromptContext {\n const { allAgents, retryContext, sharedContext, feedback, messages: rawMessages } = options ?? {};\n\n // Map messages to prompt-friendly shape\n const agentById = new Map((allAgents ?? []).map((a) => [a.id, a]));\n const messages = rawMessages?.length\n ? rawMessages.map((m) => ({\n id: m.id,\n from: agentById.get(m.from_agent_id)?.name ?? m.from_agent_id,\n subject: m.subject,\n body: m.body,\n sent_at: m.created_at,\n reply_to: m.reply_to,\n }))\n : undefined;\n\n return {\n project: {\n name: config.project.name,\n description: config.project.description,\n },\n task: {\n id: task.id,\n title: task.title,\n description: task.description,\n priority: task.priority,\n labels: task.labels,\n scope: task.scope,\n is_autonomous: task.labels?.includes(AUTONOMOUS_LABEL) ?? false,\n },\n agent: {\n id: agent.id,\n name: agent.name,\n role: agent.role,\n },\n agents: (allAgents ?? []).map((a) => ({\n id: a.id,\n name: a.name,\n role: a.role,\n adapter: a.adapter,\n })),\n attempt: attempt > 1 ? attempt : null,\n workspace_path: workspacePath,\n retry: attempt > 1 ? retryContext : undefined,\n feedback,\n shared_context: sharedContext && Object.keys(sharedContext).length > 0 ? sharedContext : undefined,\n messages,\n };\n}\n\n/** Default prompt template */\nexport const DEFAULT_PROMPT_TEMPLATE = `You are {{ agent.name }}{% if agent.role %} ({{ agent.role }}){% endif %}.\n\n## Task: {{ task.title }}\n{{ task.description }}\n\nPriority: {{ task.priority }}\n{% if attempt %}Attempt: {{ attempt }}{% endif %}\n{% if retry %}\n## Previous attempt failed\n**Error:** {{ retry.previous_error }}\n{% if retry.previous_output != \"\" %}\n**Last output:**\n\\`\\`\\`\n{{ retry.previous_output }}\n\\`\\`\\`\n{% endif %}\n**Important:** The previous approach failed. Analyze the error above and try a different strategy. Do NOT repeat the same steps that led to the failure.\n{% endif %}\n\n## Context\nProject: {{ project.name }}\nWorking directory: {{ workspace_path }}\n\n## Team\nYou are part of a multi-agent team. Available agents:\n{% for a in agents %}- **{{ a.name }}** ({{ a.adapter }}){% if a.role %} — {{ a.role }}{% endif %} · ID: \\`{{ a.id }}\\`\n{% endfor %}\nUse \\`orch agent list\\` to check current agent statuses. Find teammates by name/role — do NOT hardcode agent IDs.\n\n{% if feedback %}\n## Review Feedback\nThis task was previously completed but **rejected** during review with the following feedback:\n> {{ feedback }}\n\n**Important:** Address the feedback above. Focus on what the reviewer asked to change. Do NOT redo work that was already accepted.\n{% endif %}\n\n{% if shared_context %}\n## Shared Context\nOther agents have shared the following information:\n{% for entry in shared_context %}- **{{ entry[0] }}**: {{ entry[1] }}\n{% endfor %}\n{% endif %}\n\n{% if messages %}\n## Inbox ({{ messages.size }} message{% if messages.size != 1 %}s{% endif %})\n{% for msg in messages %}\n---\n**From:** {{ msg.from }}{% if msg.subject != \"\" %} · **Subject:** {{ msg.subject }}{% endif %}\n{{ msg.body }}\n{% if msg.reply_to %}*(Reply to: {{ msg.reply_to }})*{% endif %}\n---\n{% endfor %}\n{% endif %}\n\n## Orchestrator CLI\nManage tasks and coordinate with other agents using \\`orch\\`:\n\n**Tasks:**\n- \\`orch task add \"<title>\" -d \"<description>\" -p <1-4> --assignee <agent-id>\\` — create and assign a task\n- \\`orch task add \"<title>\" -d \"<description>\" --scope \"src/path/**\" --depends-on <task-id>\\` — scoped task with dependency\n- \\`orch task list [--status todo|in_progress|done|failed]\\` — list tasks\n\n**Messaging:**\n- \\`orch msg send <agent-id> \"<body>\" -s \"<subject>\"\\` — direct message\n- \\`orch msg broadcast \"<body>\" -s \"<subject>\"\\` — broadcast to all\n- \\`orch msg inbox {{ agent.id }}\\` — your pending messages\n\n**Shared context:**\n- \\`orch context set <key> <value>\\` / \\`orch context get <key>\\` / \\`orch context list\\`\n\n{% if task.is_autonomous %}\n## Autonomous Goal Mode\nThis is an autonomous task driven by a goal. Work in a continuous loop until the goal is achieved:\n\n1. **Read the GOAL section** above — understand the desired outcome.\n2. **Decompose** — break the goal into concrete subtasks via \\`orch task add\\`. Assign yourself for your specialty, delegate other work to appropriate teammates by role.\n3. **Execute** — follow your standard workflow for each subtask.\n4. **Track progress** — after each iteration: \\`orch context set <goal>-progress \"<done, remaining>\"\\`.\n5. **Be proactive** — do NOT wait for tasks from others. Create your own subtasks and keep working.\n6. **Do NOT finish** the [auto] task until the goal is achieved — keep creating subtasks.\n7. **When done** — \\`orch context set <goal>-status \"ACHIEVED: <summary>\"\\`.\n{% endif %}\n\n## Rules\n- Do NOT ask clarifying questions. You are running autonomously without human input.\n- Make reasonable assumptions and proceed with the best approach.\n- If critical information is missing, document your assumptions and continue.\n- When a task is too large or spans multiple domains, break it into subtasks using \\`orch task add\\`.\n- When creating subtasks, use \\`--scope\\` to declare which files each task will touch, and \\`--depends-on\\` to order dependent work.\n`;\n"]}
@@ -1,13 +0,0 @@
1
- import {d,h,e}from'./chunk-ZU6AY2VU.js';import {a,d as d$1,c}from'./chunk-AELEEEV3.js';import {dirname}from'path';import k from'fs/promises';import {execFile}from'child_process';var J={todo:["in_progress","cancelled"],in_progress:["review","retrying","failed","cancelled"],retrying:["in_progress","failed","cancelled"],review:["done","todo","cancelled"],done:[],failed:["todo","retrying"],cancelled:["todo"]},Q=new Set(["done","failed","cancelled"]);function st(c,t){return J[c].includes(t)}function P(c){return Q.has(c)}function D(c){return c==="todo"||c==="retrying"}function G(c,t){return c.depends_on.length===0?false:c.depends_on.some(e=>{let s=t.find(a=>a.id===e);return !s||s.status!=="done"})}function A(c){return c.attempts<c.max_attempts?"retrying":"failed"}function N(c,t,e){return "review"}function F(c,t,e){let s=t*Math.pow(2,c);return Math.min(s,e)}function U(c,t){if(!c?.length||!t?.length)return false;for(let e of c)for(let s of t)if(V(e,s))return true;return false}function V(c,t){if(c===t)return true;let e=c.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let a=dirname(e),l=dirname(s);return a===l&&a!=="."}return false}async function C(c){let t=c+".bak",e=await H(c);if(e!==null){if(X(e))return {acquired:false,pid:e};try{await k.rename(c,t);}catch{}}try{let s=await k.open(c,"wx");return await s.writeFile(String(process.pid),"utf-8"),await s.close(),await k.unlink(t).catch(()=>{}),{acquired:!0,pid:process.pid}}catch(s){if(s.code==="EEXIST")return await k.rename(t,c).catch(()=>{}),{acquired:false,pid:await H(c)??void 0};throw s}}async function B(c){await k.unlink(c).catch(()=>{});}async function H(c){try{let t=await k.readFile(c,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}function X(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}var R=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?.status??"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}},b=class{constructor(t){this.inner=t;}listCache=null;async list(){if(this.listCache)return this.listCache;let t=await this.inner.list();return this.listCache=t,t}async get(t){return this.inner.get(t)}async getByName(t){return this.inner.getByName(t)}async save(t){await this.inner.save(t),this.listCache=null;}async delete(t){await this.inner.delete(t),this.listCache=null;}invalidate(){this.listCache=null;}},x=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?.status??"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}};var Y={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},_=class{cwd;timeoutMs;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4;}async runAll(t){let e=[];for(let s of t){let a=await this.runCriterion(s);e.push(a);}return e}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let a=s.passed?"\u2713":"\u2717",l=s.output.slice(0,500);return `${a} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
2
- ${l}`}).join(`
3
-
4
- `)}runCriterion(t){let{cmd:e,args:s}=Y[t];return new Promise(a=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(l,r,i)=>{let u=(r+`
5
- `+i).trim();a({criterion:t,passed:!l,output:u.slice(0,2e3)});});})}};var Z=8192,tt=4096,W=class{constructor(t){this.deps=t;this.cachedTaskStore=new R(t.taskStore),this.cachedAgentStore=new b(t.agentStore),this.cachedGoalStore=t.goalStore?new x(t.goalStore):null;}intervalId=null;shuttingDown=false;state=null;abortControllers=new Map;cachedTaskStore;cachedAgentStore;cachedGoalStore;saveStateTimer=null;saveStateDirty=false;lockAcquired=false;consecutiveTickFailures=0;maxConsecutiveTickFailures=5;maxRetryQueueSize=100;signalHandlers=[];immediateDispatchTimer=null;taskCreatedUnsub=null;tickInProgress=false;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(l=>{e=l;}),a=this.stateMutex;return this.stateMutex=s,a.then(async()=>{try{return await t()}finally{e();}})}async runTask(t){await this.withTemporaryLock(async()=>{await this.loadState(),await this.dispatchTask(t);});}async runAll(){await this.withTemporaryLock(async()=>{await this.loadState(),await this.dispatchAll();});}async withTemporaryLock(t){let e=await C(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true;try{await t();}finally{this.lockAcquired=false,await B(this.deps.lockPath);}}async startWatch(){let t=await C(this.deps.lockPath);if(!t.acquired)throw new d(t.pid);this.lockAcquired=true,await this.loadState(),this.state.pid=process.pid,this.state.started_at=new Date().toISOString(),await this.saveState(),this.registerSignalHandlers(),this.taskCreatedUnsub=this.deps.eventBus.on("task:created",()=>{this.scheduleImmediateDispatch();}),await this.tick(),this.intervalId=setInterval(()=>this.tick().then(()=>{this.consecutiveTickFailures=0;},e=>{this.consecutiveTickFailures++;let s=e instanceof Error?e.message:String(e);this.deps.eventBus.emit({type:"orchestrator:error",error:s,context:"tick",fatal:this.consecutiveTickFailures>=this.maxConsecutiveTickFailures}),this.consecutiveTickFailures>=this.maxConsecutiveTickFailures&&(this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`${this.consecutiveTickFailures} consecutive tick failures`}),this.stop().catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:"stop after consecutive tick failures",fatal:false});}));}),this.deps.config.scheduling.poll_interval_ms);}registerSignalHandlers(){let t=e=>{this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`Received ${e}`}),this.stop().catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`stop after ${e} signal`,fatal:false});});};for(let e of ["SIGINT","SIGTERM"]){let s=()=>t(e);this.signalHandlers.push([e,s]),process.on(e,s);}}removeSignalHandlers(){for(let[t,e]of this.signalHandlers)process.removeListener(t,e);this.signalHandlers=[];}async stop(){this.shuttingDown||(this.shuttingDown=true,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.taskCreatedUnsub&&(this.taskCreatedUnsub(),this.taskCreatedUnsub=null),this.immediateDispatchTimer&&(clearTimeout(this.immediateDispatchTimer),this.immediateDispatchTimer=null),await this.flushStateLazy(),await this.withStateLock(async()=>{if(this.state){for(let[t,e]of Object.entries(this.state.running)){this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(e.pid),await this.deps.runService.finish(e.run_id,"cancelled");let s=await this.deps.taskStore.get(t);s&&await this.deps.taskService.updateStatus(t,A(s)),await this.deps.agentService.setStatus(e.agent_id,"idle");}this.state.running={},this.state.claimed=[],this.state.pid=void 0,this.state.started_at=void 0,await this.saveState();}}),this.lockAcquired&&(await B(this.deps.lockPath),this.lockAcquired=false),this.removeSignalHandlers());}async cancelTask(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.cancelTask(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state,s=e.running[t];s&&(this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(s.pid,3e3).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask setStatus idle for agent ${s.agent_id}`,fatal:false});}),delete e.running[t],await this.saveState()),e.retry_queue=e.retry_queue.filter(a=>a.task_id!==t);try{await this.deps.taskService.cancel(t);}catch{try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{}}await this.saveState();});}async forceStopAgent(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.forceStopAgent(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state;for(let[s,a]of Object.entries(e.running))if(a.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(a.pid,3e3),await this.deps.runService.finish(a.run_id,"cancelled");try{await this.deps.taskService.updateStatus(s,"failed");}catch{}delete e.running[s];}await this.deps.agentService.setStatus(t,"idle"),await this.saveState();});}async tick(){if(!this.shuttingDown){this.tickInProgress=true;try{await this.withStateLock(async()=>{if(this.shuttingDown)return;this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),this.cachedGoalStore?.invalidate(),await this.loadState(),await this.reconcile(),await this.seedAutonomousTasks(),await this.dispatchAll();let t=await this.cachedTaskStore.list(),e=Object.keys(this.state.running).length,s=t.filter(a=>D(a.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});});}finally{this.tickInProgress=false;}}}scheduleImmediateDispatch(){this.shuttingDown||this.immediateDispatchTimer||(this.immediateDispatchTimer=setTimeout(()=>{this.immediateDispatchTimer=null,!(this.shuttingDown||this.tickInProgress)&&this.immediateDispatch().catch(t=>{this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"immediate dispatch on task:created",fatal:false});});},500));}async immediateDispatch(){this.shuttingDown||await this.withStateLock(async()=>{this.shuttingDown||(this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),await this.loadState(),await this.dispatchAll(),await this.saveState());});}async reconcile(){let t=this.state,e=Date.now();for(let[r,i]of Object.entries(t.running)){let u=await this.deps.taskStore.get(r);if(!u||P(u.status)){this.abortControllers.delete(r),delete t.running[r],await this.deps.agentService.setStatus(i.agent_id,"idle").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),context:`reconcile setStatus idle for stale agent ${i.agent_id} (task ${r})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(i.pid)){try{await this._handleRunFailure(r,i,"Process crashed unexpectedly");}catch{delete t.running[r],await this.deps.agentService.setStatus(i.agent_id,"idle").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),context:`reconcile crash fallback setStatus idle for agent ${i.agent_id} (task ${r})`,fatal:false});});}continue}let o=new Date(i.last_event_at).getTime(),n=this.deps.config.defaults.agent.stall_timeout_ms;if(e-o>n){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:i.run_id}),this.abortControllers.get(r)?.abort(),await this.deps.processManager.killWithGrace(i.pid,5e3);try{await this._handleRunFailure(r,i,"Agent stalled (no events)");}catch{delete t.running[r],await this.deps.agentService.setStatus(i.agent_id,"idle").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),context:`reconcile stall fallback setStatus idle for agent ${i.agent_id} (task ${r})`,fatal:false});});}}}let s=new Set(Object.values(t.running).map(r=>r.agent_id)),a=await this.cachedAgentStore.list();for(let r of a)r.status==="running"&&!s.has(r.id)&&await this.deps.agentService.setStatus(r.id,"idle");let l=await this.cachedTaskStore.list();for(let r of l)if(r.status==="in_progress"&&!t.running[r.id]){try{await this.deps.taskService.updateStatus(r.id,"failed");}catch{r.status="failed",r.updated_at=new Date().toISOString(),await this.deps.taskStore.save(r).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`force-write orphaned task ${r.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:r.id});}for(let r=t.retry_queue.length-1;r>=0;r--){let i=t.retry_queue[r];e>=new Date(i.due_at).getTime()&&(t.retry_queue.splice(r,1),await this.dispatchTask(i.task_id));}await this.saveState();}async seedAutonomousTasks(){let e=(await this.cachedAgentStore.list()).filter(i=>i.autonomous&&i.status==="idle");if(e.length===0)return;let s=await this.cachedTaskStore.list(),a$1=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],l=false,r=new Set;for(let i of e){if(s.some(h=>h.assignee===i.id&&!P(h.status)))continue;let o=a$1.find(h=>h.assignee===i.id&&!r.has(h.id))??a$1.find(h=>!h.assignee&&!r.has(h.id));o&&r.add(o.id);let n=i.role??"general assistant",d=o?`[auto] ${i.name}: ${o.title.slice(0,60)}`:`[auto] ${i.name}: ${n.slice(0,60)}`,g=o?`## GOAL (highest priority)
6
-
7
- ${o.description||o.title}
8
-
9
- ---
10
- Agent role: ${n}`:`Autonomous work cycle. Agent role: ${n}`;try{await this.deps.taskService.create({title:d,description:g,assignee:i.id,labels:[a],priority:3}),l=!0;}catch(h){this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`autonomous task for agent ${i.id}`,fatal:false});}}l&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,a=e-s;if(a<=0)return;let l=await this.cachedTaskStore.list(),r=l.filter(o=>D(o.status)&&!G(o,l)&&!t.running[o.id]&&!t.claimed.includes(o.id)).sort((o,n)=>{let d=n.updated_at??"",g=o.updated_at??"";return d<g?-1:d>g?1:0}).slice(0,a),i=new Set,u=l.filter(o=>o.status==="in_progress"&&o.scope?.length);for(let o=0;o<r.length;o++){let n=r[o];if(!n.scope?.length)continue;let d=r.slice(0,o).filter(v=>!i.has(v.id)),g=[...u,...d],h=false;for(let v of g)if(U(n.scope,v.scope)){this.deps.eventBus.emit({type:"task:scope_overlap",taskId:n.id,overlappingTaskId:v.id,patterns:n.scope}),h=true;break}h&&i.add(n.id);}for(let o of r)if(!i.has(o.id))try{await this.dispatchTask(o.id);}catch(n){this.deps.eventBus.emit({type:"orchestrator:error",error:n instanceof Error?n.message:String(n),context:`dispatch task ${o.id}`,fatal:false});}}async dispatchTask(t){let e$1=this.state;if(e$1.running[t]){let a=e$1.running[t];throw new h(t,a.run_id,a.agent_id)}let s=await this.deps.taskService.get(t);e$1.claimed.push(t),await this.saveState();try{let a=await this.deps.agentService.findBestAgent(s);if(!a){if((await this.cachedAgentStore.list()).length===0)throw new e;this.unclaim(t),await this.saveState();return}let{path:l,branch:r}=await this.deps.workspaceManager.prepare(s,a,this.deps.config),i=this.deps.config.prompt?.template??d$1,u=await this.cachedAgentStore.list(),o=s.attempts+1,n;if(o>1){let w=await this.deps.runService.getLastFailedRunContext(s.id);w&&(n={previous_error:w.error,previous_output:w.output});}let d=this.deps.contextStore?await this.deps.contextStore.getAll():void 0,g=this.deps.messageService?await this.deps.messageService.drainMailbox(a.id,s.id):[],h=c(s,a,o,l,this.deps.config,{allAgents:u,retryContext:n,sharedContext:d,feedback:s.feedback,messages:g.length?g:void 0}),v=await this.deps.templateEngine.render(i,h),p=await this.deps.runService.create({taskId:s.id,agentId:a.id,attempt:o,prompt:v,workspacePath:l});(s.status==="failed"||s.status==="cancelled")&&(await this.deps.taskService.retry(t),s.status="todo",s.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,a.id),await this.deps.taskService.incrementAttempts(t),r&&(s.proof={...s.proof??{files_changed:[]},branch:r},s.workspace=l,await this.deps.taskStore.save(s)),await this.deps.agentService.setStatus(a.id,"running");let m=await this.deps.agentService.get(a.id);m.current_task=t,await this.deps.agentStore.save(m);let f=this.deps.adapterRegistry.require(a.adapter),S=new AbortController;this.abortControllers.set(t,S);let y=f.execute({prompt:v,workspace:l,env:{...a.config.env,ORCH_AGENT_ID:a.id,ORCH_AGENT_NAME:a.name,ORCH_TASK_ID:s.id},config:m.config,signal:S.signal}),M=y.pid,O=new Date().toISOString();await this.deps.runService.start(p.id,M),this.unclaim(t),e$1.running[t]={run_id:p.id,agent_id:a.id,task_id:t,pid:M,started_at:O,last_event_at:O},await this.saveState(),this.collectEvents(y.events,p.id,t,a.id).catch(w=>{this.deps.eventBus.emit({type:"orchestrator:error",error:w instanceof Error?w.message:String(w),context:`adapter execution for ${t}`,fatal:!1});});}catch(a){throw this.unclaim(t),await this.saveState(),a}}async collectEvents(t,e,s,a){let l,r,i,u=new Set;try{for await(let n of t){if(this.shuttingDown)break;if(n.type==="done"){n.tokens&&(l=n.tokens);let p=n.data;p&&typeof p.result=="string"&&(r=p.result);}if(n.type==="output"){let p=n.data;if(p){let m=typeof p.text=="string"?p.text:typeof p.message=="string"?p.message:void 0;m?.trim()&&(i=m);}}if(n.type==="file_change"){let p=n.data;if(p&&Array.isArray(p.paths))for(let m of p.paths)typeof m=="string"&&u.add(m);else {let m=p&&typeof p.path=="string"?p.path:typeof n.data=="string"?n.data:String(n.data);u.add(m);}}let d=et(n.timestamp)?n.timestamp:new Date().toISOString(),g=z(n.data,Z);n.data=void 0;let h={timestamp:d,type:n.type==="output"?"agent_output":n.type==="file_change"?"file_changed":n.type==="command"?"command_run":n.type==="tool_call"?"tool_call":n.type==="error"?"error":"done",data:g};await this.deps.runService.appendEvent(e,h),this.state?.running[s]&&(this.state.running[s].last_event_at=d,this.saveStateLazy());let v=z(g,tt);n.type==="output"||n.type==="tool_call"?this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:a,data:v}):n.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:a,path:typeof n.data=="string"?n.data:String(n.data)}):n.type==="error"&&this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:a,error:v});}let o=r??i;await this.handleRunSuccess(s,e,a,l,o,[...u]);}catch(o){let n=o instanceof Error?o.message:String(o),d=this.state?.running[s];d&&await this.handleRunFailure(s,d,n);}}async handleRunSuccess(t,e,s,a,l,r){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,a,l,r))}async _handleRunSuccess(t,e,s,a$1,l,r){await this.flushStateLazy(),this.abortControllers.delete(t);let i=this.state;if(!i.running[t])return;let u=await this.deps.taskStore.get(t);if(!u)return;u.proof={...u.proof,agent_summary:l?.slice(0,2e3)??u.proof?.agent_summary,files_changed:r?.length?r:u.proof?.files_changed??[]},delete u.feedback,await this.deps.taskStore.save(u);let o=await this.deps.agentStore.get(s),d=u.labels?.includes(a)||o?.config.approval_policy==="auto",g=N();await this.deps.runService.finish(e,"succeeded",a$1);let h=i.running[t],v=h?Date.now()-new Date(h.started_at).getTime():0;h&&(i.stats.total_runtime_ms+=v),delete i.running[t];let p={tasks_completed:(o?.stats.tasks_completed??0)+1,total_runs:(o?.stats.total_runs??0)+1,total_runtime_ms:(o?.stats.total_runtime_ms??0)+v};if(a$1&&(p.tokens_used=(o?.stats.tokens_used??0)+a$1.total),await this.deps.agentService.updateStats(s,p).catch(f=>{this.deps.eventBus.emit({type:"orchestrator:error",error:f instanceof Error?f.message:String(f),context:`agent stats update for ${s}`,fatal:false});}),i.stats.total_tasks_completed++,i.stats.total_runs++,a$1&&(i.stats.total_tokens.input+=a$1.input,i.stats.total_tokens.output+=a$1.output,i.stats.total_tokens.total=i.stats.total_tokens.input+i.stats.total_tokens.output),u.proof?.branch)try{let f=await this.deps.workspaceManager.mergeBack(u.proof.branch);if(f.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:u.proof.branch}),await this.deps.workspaceManager.cleanup(t).catch(S=>{this.deps.eventBus.emit({type:"orchestrator:error",error:S instanceof Error?S.message:String(S),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:u.proof.branch,conflictInfo:f.conflictInfo}),await this.forceTaskToReview(u,s,`MERGE CONFLICT: ${f.conflictInfo}`);return}}catch(f){let S=f instanceof Error?f.message:String(f);await this.forceTaskToReview(u,s,`MERGE ERROR: ${S}`);return}try{await this.deps.taskService.updateStatus(t,g);}catch(f){let S=f instanceof Error?f.message:String(f);this.deps.eventBus.emit({type:"orchestrator:error",error:S,context:`state machine validation failed for task ${t} -> ${g}, force-writing`,fatal:false}),u.status=g,u.updated_at=new Date().toISOString(),await this.deps.taskStore.save(u).catch(y=>{this.deps.eventBus.emit({type:"orchestrator:error",error:y instanceof Error?y.message:String(y),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(f=>{this.deps.eventBus.emit({type:"orchestrator:error",error:f instanceof Error?f.message:String(f),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let m=await this.deps.agentStore.get(s);m&&(m.current_task=void 0,await this.deps.agentStore.save(m)),u.review_criteria?.length?await this.runAutoReview(t,u.review_criteria,u.workspace??this.deps.projectRoot):d&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s){return this.withStateLock(()=>this._handleRunFailure(t,e,s))}async _handleRunFailure(t,e,s){await this.flushStateLazy(),this.abortControllers.delete(t);let a=this.state,l=await this.deps.taskStore.get(t);if(!l)return;await this.deps.runService.finish(e.run_id,"failed",void 0,s),await this.deps.agentService.setStatus(e.agent_id,"idle");let r=await this.deps.agentStore.get(e.agent_id);r&&(r.current_task=void 0,await this.deps.agentStore.save(r));let i=await this.deps.agentStore.get(e.agent_id),u=Date.now()-new Date(e.started_at).getTime();await this.deps.agentService.updateStats(e.agent_id,{tasks_failed:(i?.stats.tasks_failed??0)+1,total_runs:(i?.stats.total_runs??0)+1,total_runtime_ms:(i?.stats.total_runtime_ms??0)+u});let o=A(l);if(await this.deps.taskService.updateStatus(t,o),o==="retrying"){let n=F(l.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);a.retry_queue.some(g=>g.task_id===t)||(a.retry_queue.length>=this.maxRetryQueueSize&&a.retry_queue.shift(),a.retry_queue.push({task_id:t,attempt:l.attempts+1,due_at:new Date(Date.now()+n).toISOString(),error:s})),this.deps.eventBus.emit({type:"run:retry",runId:e.run_id,attempt:l.attempts+1,delay_ms:n});}else a.stats.total_tasks_failed++;a.stats.total_runtime_ms+=u,delete a.running[t],a.stats.total_runs++,await this.saveState(),this.scheduleImmediateDispatch();}async runAutoReview(t,e,s){let l=await new _({cwd:s}).runAll(e),r=_.allPassed(l),i=await this.deps.taskStore.get(t);if(i&&(i.review_results=l,i.proof={...i.proof,test_results:_.formatReport(l),files_changed:i.proof?.files_changed??[]},await this.deps.taskStore.save(i),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:r,results:l}),r))try{await this.deps.taskService.updateStatus(t,"done");}catch(u){let o=u instanceof Error?u.message:String(u);this.deps.eventBus.emit({type:"orchestrator:error",error:o,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),i.status="done",i.updated_at=new Date().toISOString(),await this.deps.taskStore.save(i).catch(n=>{this.deps.eventBus.emit({type:"orchestrator:error",error:n instanceof Error?n.message:String(n),context:`force-write task ${t} to store failed (auto-review)`,fatal:false});});}}async forceTaskToReview(t,e,s){t.proof={...t.proof,agent_summary:`${s}
11
-
12
- ${t.proof?.agent_summary??""}`.slice(0,2e3),files_changed:t.proof?.files_changed??[]},t.status="review",t.updated_at=new Date().toISOString(),await this.deps.taskStore.save(t),await this.deps.agentService.setStatus(e,"idle").catch(l=>{this.deps.eventBus.emit({type:"orchestrator:error",error:l instanceof Error?l.message:String(l),context:`forceTaskToReview setStatus idle for agent ${e}`,fatal:false});});let a=await this.deps.agentStore.get(e);a&&(a.current_task=void 0,await this.deps.agentStore.save(a)),await this.saveState();}unclaim(t){let e=this.state.claimed.indexOf(t);e!==-1&&this.state.claimed.splice(e,1);}requireOwnership(){if(!this.lockAcquired)throw new d(0)}async loadState(){this.state=await this.deps.stateStore.read();}async saveState(){this.state&&await this.deps.stateStore.write(this.state);}saveStateLazy(){this.saveStateDirty=true,!this.saveStateTimer&&(this.saveStateTimer=setTimeout(()=>{this.saveStateTimer=null,this.saveStateDirty&&(this.saveStateDirty=false,this.saveState().catch(t=>{this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"debounced state save",fatal:false});}));},500));}async flushStateLazy(){this.saveStateTimer&&(clearTimeout(this.saveStateTimer),this.saveStateTimer=null),this.saveStateDirty&&(this.saveStateDirty=false,await this.saveState());}};function et(c){if(typeof c!="string")return false;let t=new Date(c);return !isNaN(t.getTime())&&t.toISOString()===c}function z(c,t){let e=typeof c=="string"?c:JSON.stringify(c);return e.length>t?e.slice(0,t)+"\u2026":e}export{st as a,P as b,D as c,G as d,A as e,W as f};//# sourceMappingURL=chunk-E3TCKHU6.js.map
13
- //# sourceMappingURL=chunk-E3TCKHU6.js.map