@oxgeneral/orch 0.2.4 → 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 (143) hide show
  1. package/dist/App-TW35IULR.js +18 -0
  2. package/dist/agent-FRQKL7YI.js +9 -0
  3. package/dist/{orchestrator-OMU46RCE.js → chunk-2UC4SVJB.js} +190 -53
  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-VAAOW526.js → chunk-GZ2Q56YZ.js} +2 -2
  14. package/dist/{doctor-service-QEJCE5FK.js → chunk-HMMPM7MF.js} +2 -2
  15. package/dist/{chunk-AELEEEV3.js → chunk-HSBYJ5C5.js} +27 -7
  16. package/dist/chunk-HXOMNULD.js +2 -0
  17. package/dist/{chunk-3TGCIXJA.js → chunk-IQXRQBUK.js} +2 -1
  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-2KSBOAW3.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/{chunk-K6DMQERQ.js → doctor-service-F2SXDWHS.js} +3 -1
  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 +105 -43
  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-L6QX2LJ7.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-G5EQRS72.js → workspace-manager-T6AXG7XL.js} +4 -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-KHUT3IV7.js +0 -4962
  89. package/dist/agent-V5M2C3OC.js +0 -157
  90. package/dist/chunk-33QNTNR6.js +0 -46
  91. package/dist/chunk-6HENRUYZ.js.map +0 -1
  92. package/dist/chunk-AELEEEV3.js.map +0 -1
  93. package/dist/chunk-ED47GL3F.js +0 -29
  94. package/dist/chunk-FRTKB575.js +0 -87
  95. package/dist/chunk-HXYAZGLP.js +0 -15
  96. package/dist/chunk-I5WEMARW.js +0 -166
  97. package/dist/chunk-IZYSGYXG.js +0 -2
  98. package/dist/chunk-IZYSGYXG.js.map +0 -1
  99. package/dist/chunk-P6ATSXGL.js +0 -107
  100. package/dist/chunk-PBFE5V3G.js +0 -2
  101. package/dist/chunk-PBFE5V3G.js.map +0 -1
  102. package/dist/chunk-PNE6LQRF.js +0 -5
  103. package/dist/chunk-POUC4CPC.js.map +0 -1
  104. package/dist/chunk-QTDKQYZI.js +0 -11
  105. package/dist/chunk-QTDKQYZI.js.map +0 -1
  106. package/dist/chunk-VAAOW526.js.map +0 -1
  107. package/dist/chunk-ZTQ3KWXR.js +0 -13
  108. package/dist/chunk-ZTQ3KWXR.js.map +0 -1
  109. package/dist/claude-GH6P2DC5.js +0 -4
  110. package/dist/claude-S47YTIHU.js +0 -2
  111. package/dist/claude-S47YTIHU.js.map +0 -1
  112. package/dist/codex-2CH57B7G.js +0 -2
  113. package/dist/codex-2CH57B7G.js.map +0 -1
  114. package/dist/config-LJFM55LN.js +0 -75
  115. package/dist/container-KPH4HVAJ.js +0 -1532
  116. package/dist/context-EPSDCJTU.js +0 -83
  117. package/dist/cursor-QFUNKPCQ.js +0 -2
  118. package/dist/cursor-QFUNKPCQ.js.map +0 -1
  119. package/dist/doctor-GHRV5I2S.js +0 -67
  120. package/dist/doctor-service-QEJCE5FK.js.map +0 -1
  121. package/dist/doctor-service-TPOMFAIG.js +0 -2
  122. package/dist/goal-I56QP7HS.js +0 -110
  123. package/dist/init-EQTGQ4G2.js +0 -165
  124. package/dist/logs-AK255DEJ.js +0 -207
  125. package/dist/msg-SQWQLJP6.js +0 -95
  126. package/dist/orchestrator-L6QX2LJ7.js +0 -2
  127. package/dist/process-manager-HUVNAPQV.js +0 -2
  128. package/dist/process-manager-TLZOTO4Y.js +0 -2
  129. package/dist/registry-PQWRVNF2.js +0 -2
  130. package/dist/registry-UQAHK77P.js +0 -2
  131. package/dist/run-PSZURVVL.js +0 -95
  132. package/dist/shell-5ZNXFGXV.js +0 -3
  133. package/dist/shell-OGTSH4RJ.js.map +0 -1
  134. package/dist/status-DTF7D3DV.js +0 -56
  135. package/dist/task-35SDKXFC.js +0 -209
  136. package/dist/team-AISPLEJB.js +0 -97
  137. package/dist/template-engine-322SCRR6.js +0 -2
  138. package/dist/template-engine-3CDRZNMJ.js +0 -3
  139. package/dist/tui-AR6PVMBQ.js +0 -230
  140. package/dist/update-DCCWVISK.js +0 -64
  141. package/dist/update-check-4YKLGBFB.js +0 -2
  142. package/dist/workspace-manager-AS4TFA7R.js +0 -3
  143. package/dist/workspace-manager-AS4TFA7R.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,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 +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","DEFAULT_PROMPT_TEMPLATE"],"mappings":"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","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,29 +0,0 @@
1
- #!/usr/bin/env node
2
- // src/domain/config.ts
3
- var DEFAULT_CONFIG = {
4
- project: {
5
- name: "my-project"
6
- },
7
- defaults: {
8
- agent: {
9
- adapter: "claude",
10
- approval_policy: "auto",
11
- max_turns: 50,
12
- timeout_ms: 36e5,
13
- stall_timeout_ms: 3e5,
14
- workspace_mode: "worktree"
15
- },
16
- task: {
17
- max_attempts: 3,
18
- priority: 3
19
- }
20
- },
21
- scheduling: {
22
- poll_interval_ms: 3e4,
23
- max_concurrent_agents: 6,
24
- retry_base_delay_ms: 1e4,
25
- retry_max_delay_ms: 3e5
26
- }
27
- };
28
-
29
- export { DEFAULT_CONFIG };
@@ -1,87 +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
- var REVALIDATE_AFTER_MS = CHECK_INTERVAL_MS * 0.75;
12
- function compareSemver(a, b) {
13
- const pa = a.split(".").map(Number);
14
- const pb = b.split(".").map(Number);
15
- for (let i = 0; i < 3; i++) {
16
- const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
17
- if (diff !== 0) return diff > 0 ? 1 : -1;
18
- }
19
- return 0;
20
- }
21
- async function readCache() {
22
- try {
23
- const raw = await fs.readFile(CACHE_FILE, "utf-8");
24
- const data = JSON.parse(raw);
25
- if (Date.now() - data.checked_at < CHECK_INTERVAL_MS) return data;
26
- } catch {
27
- }
28
- return null;
29
- }
30
- async function writeCache(latest) {
31
- await fs.mkdir(CACHE_DIR, { recursive: true });
32
- const data = { latest, checked_at: Date.now() };
33
- const tmp = `${CACHE_FILE}.tmp.${process.pid}`;
34
- await fs.writeFile(tmp, JSON.stringify(data), "utf-8");
35
- await fs.rename(tmp, CACHE_FILE);
36
- }
37
- function fetchLatestVersion() {
38
- return new Promise((resolve) => {
39
- const child = execFile("npm", ["view", PACKAGE_NAME, "version", "--json"], { timeout: 5e3 }, (err, stdout) => {
40
- if (err) return resolve(null);
41
- try {
42
- resolve(JSON.parse(stdout.trim()));
43
- } catch {
44
- resolve(null);
45
- }
46
- });
47
- child.unref();
48
- });
49
- }
50
- function buildUpdateInfo(current, latest) {
51
- return { current, latest, updateAvailable: compareSemver(latest, current) > 0 };
52
- }
53
- async function checkForUpdateNow(currentVersion) {
54
- const latest = await fetchLatestVersion();
55
- if (!latest) return null;
56
- await writeCache(latest).catch(() => {
57
- });
58
- return buildUpdateInfo(currentVersion, latest);
59
- }
60
- async function checkForUpdateSWR(currentVersion) {
61
- try {
62
- const cached = await readCache();
63
- if (!cached) {
64
- checkForUpdateNow(currentVersion).catch(() => {
65
- });
66
- return null;
67
- }
68
- const age = Date.now() - cached.checked_at;
69
- if (age >= REVALIDATE_AFTER_MS) {
70
- checkForUpdateNow(currentVersion).catch(() => {
71
- });
72
- }
73
- return buildUpdateInfo(currentVersion, cached.latest);
74
- } catch {
75
- return null;
76
- }
77
- }
78
- function printUpdateNotification(info) {
79
- if (!info.updateAvailable) return;
80
- const msg = `
81
- Update available: ${info.current} \u2192 ${info.latest}
82
- Run: npm install -g ${PACKAGE_NAME}
83
- `;
84
- process.stderr.write(msg);
85
- }
86
-
87
- export { checkForUpdateNow, checkForUpdateSWR, printUpdateNotification };
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env node
2
- // src/domain/goal.ts
3
- var GOAL_STATUSES = ["active", "paused", "achieved", "abandoned"];
4
- var TERMINAL_GOAL_STATUSES = /* @__PURE__ */ new Set(["achieved", "abandoned"]);
5
- function isGoalTerminal(status) {
6
- return TERMINAL_GOAL_STATUSES.has(status);
7
- }
8
- var GOAL_STATUS_ORDER = {
9
- active: 0,
10
- paused: 1,
11
- achieved: 2,
12
- abandoned: 3
13
- };
14
-
15
- export { GOAL_STATUSES, GOAL_STATUS_ORDER, isGoalTerminal };
@@ -1,166 +0,0 @@
1
- #!/usr/bin/env node
2
- import chalk from 'chalk';
3
-
4
- var icons = {
5
- running: "\u25CF",
6
- todo: "\u25CB",
7
- review: "\u25C8",
8
- done: "\u2713",
9
- failed: "\u2715",
10
- retrying: "\u21BB",
11
- cancelled: "\u25CB",
12
- idle: "\u25CB",
13
- error: "\u2715",
14
- disabled: "\u2500",
15
- agentAction: "\u25B8",
16
- orchestratorEvent: "\u2192",
17
- warning: "\u26A0"
18
- };
19
- var asciiIcons = {
20
- running: "*",
21
- todo: "o",
22
- review: "#",
23
- done: "+",
24
- failed: "x",
25
- retrying: "~",
26
- cancelled: "o",
27
- idle: "o",
28
- error: "x",
29
- disabled: "-",
30
- agentAction: ">",
31
- orchestratorEvent: "->",
32
- warning: "!!"
33
- };
34
- var colors = {
35
- amber: chalk.ansi256(214),
36
- green: chalk.ansi256(72),
37
- red: chalk.ansi256(167),
38
- blue: chalk.ansi256(74),
39
- yellow: chalk.ansi256(178),
40
- dim: chalk.ansi256(240),
41
- ghost: chalk.ansi256(236),
42
- white: chalk.ansi256(255),
43
- purple: chalk.ansi256(141)
44
- };
45
- var useAscii = false;
46
- function setAsciiMode(ascii) {
47
- useAscii = ascii;
48
- }
49
- function setNoColor(noColor) {
50
- if (noColor) {
51
- chalk.level = 0;
52
- }
53
- }
54
- function getIcon(name) {
55
- return useAscii ? asciiIcons[name] : icons[name];
56
- }
57
- function statusIcon(status) {
58
- const icon = getIcon(status);
59
- switch (status) {
60
- case "running":
61
- case "in_progress":
62
- return colors.green(getIcon("running"));
63
- case "todo":
64
- return colors.dim(getIcon("todo"));
65
- case "review":
66
- return colors.blue(getIcon("review"));
67
- case "done":
68
- return colors.green(getIcon("done"));
69
- case "failed":
70
- return colors.red(getIcon("failed"));
71
- case "retrying":
72
- return colors.yellow(getIcon("retrying"));
73
- case "cancelled":
74
- return colors.dim(getIcon("cancelled"));
75
- case "idle":
76
- return colors.dim(getIcon("idle"));
77
- case "error":
78
- return colors.red(getIcon("error"));
79
- case "disabled":
80
- return colors.ghost(getIcon("disabled"));
81
- default:
82
- return icon;
83
- }
84
- }
85
- function priorityLabel(priority) {
86
- switch (priority) {
87
- case 1:
88
- return colors.red("P1");
89
- case 2:
90
- return colors.yellow("P2");
91
- case 3:
92
- return "P3";
93
- case 4:
94
- return colors.dim("P4");
95
- default:
96
- return `P${priority}`;
97
- }
98
- }
99
- function formatDuration(ms) {
100
- const seconds = Math.floor(ms / 1e3);
101
- if (seconds < 60) return `${seconds}s`;
102
- const minutes = Math.floor(seconds / 60);
103
- const secs = seconds % 60;
104
- if (minutes < 60) return `${minutes}:${String(secs).padStart(2, "0")}`;
105
- const hours = Math.floor(minutes / 60);
106
- const mins = minutes % 60;
107
- return `${hours}h${String(mins).padStart(2, "0")}m`;
108
- }
109
- function formatDurationSince(isoDate) {
110
- const ms = Date.now() - new Date(isoDate).getTime();
111
- return formatDuration(ms);
112
- }
113
- function formatTokens(n) {
114
- if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
115
- return String(n);
116
- }
117
- function printError(message, hint) {
118
- console.error(` ${colors.red(getIcon("failed"))} ${message}`);
119
- if (hint) {
120
- console.error(` ${hint}`);
121
- }
122
- }
123
- function printSuccess(message) {
124
- console.log(` ${colors.green(getIcon("done"))} ${message}`);
125
- }
126
- function printWarning(message) {
127
- console.log(` ${colors.yellow(getIcon("warning"))} ${message}`);
128
- }
129
- function printTable(headers, rows, padding = 2) {
130
- const colWidths = headers.map(
131
- (h, i) => Math.max(h.length, ...rows.map((r) => stripAnsi(r[i] ?? "").length))
132
- );
133
- const headerLine = headers.map((h, i) => h.padEnd(colWidths[i] + padding)).join("");
134
- console.log(` ${colors.dim(headerLine)}`);
135
- for (const row of rows) {
136
- const line = row.map((cell, i) => {
137
- const stripped = stripAnsi(cell);
138
- const pad = (colWidths[i] ?? 0) + padding - stripped.length;
139
- return cell + " ".repeat(Math.max(0, pad));
140
- }).join("");
141
- console.log(` ${line}`);
142
- }
143
- }
144
- function printKeyValue(pairs) {
145
- const maxKey = Math.max(...pairs.map(([k]) => k.length));
146
- for (const [key, value] of pairs) {
147
- console.log(` ${colors.dim(key.padEnd(maxKey + 2))}${value}`);
148
- }
149
- }
150
- function filePath(p) {
151
- return colors.purple(p);
152
- }
153
- function agentName(name) {
154
- return colors.green(name);
155
- }
156
- function amber(text) {
157
- return colors.amber(text);
158
- }
159
- function dim(text) {
160
- return colors.dim(text);
161
- }
162
- function stripAnsi(str) {
163
- return str.replace(/\x1b\[[0-9;]*m/g, "");
164
- }
165
-
166
- export { agentName, amber, dim, filePath, formatDuration, formatDurationSince, formatTokens, getIcon, printError, printKeyValue, printSuccess, printTable, printWarning, priorityLabel, setAsciiMode, setNoColor, statusIcon };
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-PBFE5V3G.js';import {b}from'./chunk-POUC4CPC.js';function g(t,i){let e=t.usage;if(!e&&i?.statsFallback&&(e=t.stats?.usage),e&&typeof e.input_tokens=="number"){let o=e.input_tokens,u=typeof e.output_tokens=="number"?e.output_tokens:0;return a(o,u)}}function k(t,i,e,o){async function*u(){let a=false,r=null,d=null,c=new Promise(s=>{t.on("close",n=>{r=n,s();}),t.on("error",n=>{d=n,s();});});if(t.stdout)for await(let s of b(t.stdout)){if(o?.aborted)break;let n=i(s);n&&(n.type==="done"&&(a=true),yield n);}if(await c,d&&!o?.aborted&&!a)throw d;if(r!==0&&r!==null&&!o?.aborted&&!a)throw new Error(`${e} process exited with code ${r}`)}return u()}export{g as a,k as b};//# sourceMappingURL=chunk-IZYSGYXG.js.map
2
- //# sourceMappingURL=chunk-IZYSGYXG.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/infrastructure/adapters/utils.ts"],"names":["extractTokens","parsed","opts","usage","input","output","createTokenUsage","createStreamingEvents","proc","parseEvent","adapterName","signal","generate","gotDoneEvent","exitCode","exitError","exitPromise","resolve","code","err","line","readLines","event"],"mappings":"wEAoBO,SAASA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACuB,CACvB,IAAIC,CAAAA,CAAQF,CAAAA,CAAO,KAAA,CAOnB,GALI,CAACE,CAAAA,EAASD,CAAAA,EAAM,aAAA,GAElBC,CAAAA,CADcF,EAAO,KAAA,EACN,KAAA,CAAA,CAGbE,CAAAA,EAAS,OAAOA,CAAAA,CAAM,YAAA,EAAiB,QAAA,CAAU,CACnD,IAAMC,CAAAA,CAAQD,CAAAA,CAAM,YAAA,CACdE,CAAAA,CAAS,OAAOF,CAAAA,CAAM,aAAA,EAAkB,QAAA,CAAWA,CAAAA,CAAM,cAAgB,CAAA,CAC/E,OAAOG,CAAAA,CAAiBF,CAAAA,CAAOC,CAAM,CACvC,CAEF,CAYO,SAASE,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,EAC4B,CAC5B,eAAgBC,CAAAA,EAAuC,CACrD,IAAIC,CAAAA,CAAe,KAAA,CAEfC,CAAAA,CAA0B,IAAA,CAC1BC,CAAAA,CAA0B,IAAA,CACxBC,CAAAA,CAAc,IAAI,QAAeC,CAAAA,EAAY,CACjDT,CAAAA,CAAK,EAAA,CAAG,QAAUU,CAAAA,EAAS,CAAEJ,CAAAA,CAAWI,CAAAA,CAAMD,IAAW,CAAC,CAAA,CAC1DT,CAAAA,CAAK,EAAA,CAAG,OAAA,CAAUW,CAAAA,EAAQ,CAAEJ,EAAYI,CAAAA,CAAKF,CAAAA,GAAW,CAAC,EAC3D,CAAC,CAAA,CAED,GAAIT,CAAAA,CAAK,OACP,UAAA,IAAiBY,CAAAA,IAAQC,CAAAA,CAAUb,CAAAA,CAAK,MAAM,CAAA,CAAG,CAC/C,GAAIG,GAAQ,OAAA,CAAS,MACrB,IAAMW,CAAAA,CAAQb,EAAWW,CAAI,CAAA,CACzBE,CAAAA,GACEA,CAAAA,CAAM,OAAS,MAAA,GAAQT,CAAAA,CAAe,IAAA,CAAA,CAC1C,MAAMS,CAAAA,EAEV,CAKF,GAFA,MAAMN,EAEFD,CAAAA,EAAa,CAACJ,CAAAA,EAAQ,OAAA,EAAW,CAACE,CAAAA,CACpC,MAAME,CAAAA,CAER,GAAID,IAAa,CAAA,EAAKA,CAAAA,GAAa,IAAA,EAAQ,CAACH,GAAQ,OAAA,EAAW,CAACE,CAAAA,CAC9D,MAAM,IAAI,KAAA,CAAM,CAAA,EAAGH,CAAW,CAAA,0BAAA,EAA6BI,CAAQ,CAAA,CAAE,CAEzE,CAEA,OAAOF,GACT","file":"chunk-IZYSGYXG.js","sourcesContent":["/**\n * Shared utilities for agent adapters.\n *\n * Deduplicates extractTokens and streaming event generation logic\n * common to claude, codex, and cursor adapters.\n */\n\nimport type { ChildProcess } from 'node:child_process';\nimport type { AgentEvent } from './interface.js';\nimport { readLines } from '../process/process-manager.js';\nimport { createTokenUsage } from '../../domain/run.js';\n\nexport type TokenInfo = { input: number; output: number; total: number };\n\n/**\n * Extract token usage from a parsed JSON event.\n *\n * @param parsed - The parsed JSON object from an adapter event line.\n * @param opts.statsFallback - If true, also checks `parsed.stats?.usage` (Claude-specific).\n */\nexport function extractTokens(\n parsed: Record<string, unknown>,\n opts?: { statsFallback?: boolean },\n): TokenInfo | undefined {\n let usage = parsed.usage as Record<string, unknown> | undefined;\n\n if (!usage && opts?.statsFallback) {\n const stats = parsed.stats as Record<string, unknown> | undefined;\n usage = stats?.usage as Record<string, unknown> | undefined;\n }\n\n if (usage && typeof usage.input_tokens === 'number') {\n const input = usage.input_tokens;\n const output = typeof usage.output_tokens === 'number' ? usage.output_tokens : 0;\n return createTokenUsage(input, output);\n }\n return undefined;\n}\n\n/**\n * Create an async generator that streams AgentEvents from a child process.\n *\n * Handles: exit promise setup, line-by-line reading, abort signal, exit code checking.\n *\n * @param proc - The spawned child process.\n * @param parseEvent - Adapter-specific function to parse a line into an AgentEvent.\n * @param adapterName - Name used in error messages (e.g. \"Claude\", \"Codex\").\n * @param signal - Optional abort signal.\n */\nexport function createStreamingEvents(\n proc: ChildProcess,\n parseEvent: (line: string) => AgentEvent | null,\n adapterName: string,\n signal?: AbortSignal,\n): AsyncGenerator<AgentEvent> {\n async function* generate(): AsyncGenerator<AgentEvent> {\n let gotDoneEvent = false;\n\n let exitCode: number | null = null;\n let exitError: Error | null = null;\n const exitPromise = new Promise<void>((resolve) => {\n proc.on('close', (code) => { exitCode = code; resolve(); });\n proc.on('error', (err) => { exitError = err; resolve(); });\n });\n\n if (proc.stdout) {\n for await (const line of readLines(proc.stdout)) {\n if (signal?.aborted) break;\n const event = parseEvent(line);\n if (event) {\n if (event.type === 'done') gotDoneEvent = true;\n yield event;\n }\n }\n }\n\n await exitPromise;\n\n if (exitError && !signal?.aborted && !gotDoneEvent) {\n throw exitError;\n }\n if (exitCode !== 0 && exitCode !== null && !signal?.aborted && !gotDoneEvent) {\n throw new Error(`${adapterName} process exited with code ${exitCode}`);\n }\n }\n\n return generate();\n}\n"]}
@@ -1,107 +0,0 @@
1
- #!/usr/bin/env node
2
- import { mkdtemp, writeFile, readFile, unlink, rm } from 'fs/promises';
3
- import { tmpdir } from 'os';
4
- import { join } from 'path';
5
- import { spawn } from 'child_process';
6
-
7
- async function openInEditor(initialContent, opts = {}) {
8
- const { extension = ".yml", prefix = "orch-" } = opts;
9
- const editor = process.env["EDITOR"] || process.env["VISUAL"] || "vi";
10
- const dir = await mkdtemp(join(tmpdir(), prefix));
11
- const filePath = join(dir, `edit${extension}`);
12
- await writeFile(filePath, initialContent, "utf8");
13
- try {
14
- const parts = editor.split(/\s+/);
15
- const child = spawn(parts[0], [...parts.slice(1), filePath], { stdio: "inherit" });
16
- await new Promise((resolve, reject) => {
17
- child.on("close", (code) => {
18
- if (code === 0) resolve();
19
- else reject(new Error(`Editor exited with code ${code}`));
20
- });
21
- child.on("error", reject);
22
- });
23
- return await readFile(filePath, "utf8");
24
- } finally {
25
- await unlink(filePath).catch(() => {
26
- });
27
- await rm(dir, { recursive: true }).catch(() => {
28
- });
29
- }
30
- }
31
- function toEditorContent(fields) {
32
- const lines = [
33
- "---",
34
- `title: ${fields.title}`,
35
- `priority: ${fields.priority}`,
36
- "---",
37
- "",
38
- fields.description ?? ""
39
- ];
40
- return lines.join("\n");
41
- }
42
- function fromEditorContent(content) {
43
- const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
44
- if (!match) {
45
- return { description: content.trim() || void 0 };
46
- }
47
- const frontmatter = match[1] ?? "";
48
- const body = match[2] ?? "";
49
- const result = {};
50
- for (const line of frontmatter.split("\n")) {
51
- const kv = line.match(/^([\w]+):\s*(.*)$/);
52
- if (!kv) continue;
53
- const key = kv[1];
54
- const value = kv[2] ?? "";
55
- if (key === "title" && value.trim()) {
56
- result.title = value.trim();
57
- } else if (key === "priority") {
58
- const n = parseInt(value.trim(), 10);
59
- if (n >= 1 && n <= 4) result.priority = n;
60
- }
61
- }
62
- const desc = body.trim();
63
- if (desc) result.description = desc;
64
- return result;
65
- }
66
- function agentToEditorContent(fields) {
67
- const lines = [
68
- "# Edit agent configuration.",
69
- "# Lines starting with # are ignored.",
70
- "# Role description goes below the second --- separator.",
71
- "---",
72
- `name: ${fields.name}`,
73
- `model: ${fields.model ?? ""}`,
74
- "---",
75
- "",
76
- fields.role ?? ""
77
- ];
78
- return lines.join("\n");
79
- }
80
- function agentFromEditorContent(content) {
81
- const lines = content.split("\n");
82
- const firstFence = lines.findIndex((l) => l.trimEnd() === "---");
83
- const stripped = (firstFence >= 0 ? [...lines.slice(0, firstFence).filter((l) => !l.startsWith("#")), ...lines.slice(firstFence)] : lines.filter((l) => !l.startsWith("#"))).join("\n");
84
- const match = stripped.trimStart().match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
85
- if (!match) {
86
- const role = stripped.trim();
87
- return { role: role || void 0 };
88
- }
89
- const frontmatter = match[1] ?? "";
90
- const body = match[2] ?? "";
91
- const result = {};
92
- for (const line of frontmatter.split("\n")) {
93
- const kv = line.match(/^([\w]+):\s*(.*)$/);
94
- if (!kv) continue;
95
- const key = kv[1];
96
- const value = kv[2] ?? "";
97
- if (key === "name") {
98
- result.name = value.trim();
99
- } else if (key === "model") {
100
- result.model = value.trim();
101
- }
102
- }
103
- result.role = body.trim();
104
- return result;
105
- }
106
-
107
- export { agentFromEditorContent, agentToEditorContent, fromEditorContent, openInEditor, toEditorContent };
@@ -1,2 +0,0 @@
1
- function n(e,t){return {input:e,output:t,total:e+t}}export{n as a};//# sourceMappingURL=chunk-PBFE5V3G.js.map
2
- //# sourceMappingURL=chunk-PBFE5V3G.js.map