@oxgeneral/orch 0.2.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.
- package/LICENSE +21 -0
- package/dist/App-CPQPQTZU.js +4751 -0
- package/dist/agent-J62U7ABO.js +157 -0
- package/dist/chunk-2B32FPEB.js +11 -0
- package/dist/chunk-2B32FPEB.js.map +1 -0
- package/dist/chunk-2VSAM7RH.js +166 -0
- package/dist/chunk-33QNTNR6.js +46 -0
- package/dist/chunk-45K2XID7.js +29 -0
- package/dist/chunk-6GFVB6EK.js +101 -0
- package/dist/chunk-6HENRUYZ.js +2 -0
- package/dist/chunk-6HENRUYZ.js.map +1 -0
- package/dist/chunk-AELEEEV3.js +92 -0
- package/dist/chunk-AELEEEV3.js.map +1 -0
- package/dist/chunk-CHIP7O6V.js +83 -0
- package/dist/chunk-CIIE6LNG.js +217 -0
- package/dist/chunk-E3TCKHU6.js +13 -0
- package/dist/chunk-E3TCKHU6.js.map +1 -0
- package/dist/chunk-ED47GL3F.js +29 -0
- package/dist/chunk-HNKJ4IF7.js +177 -0
- package/dist/chunk-HXYAZGLP.js +15 -0
- package/dist/chunk-IRN2U2NE.js +79 -0
- package/dist/chunk-IZYSGYXG.js +2 -0
- package/dist/chunk-IZYSGYXG.js.map +1 -0
- package/dist/chunk-O5AO5QIR.js +76 -0
- package/dist/chunk-P6ATSXGL.js +107 -0
- package/dist/chunk-PBFE5V3G.js +2 -0
- package/dist/chunk-PBFE5V3G.js.map +1 -0
- package/dist/chunk-PNE6LQRF.js +5 -0
- package/dist/chunk-POUC4CPC.js +2 -0
- package/dist/chunk-POUC4CPC.js.map +1 -0
- package/dist/chunk-TX7WOFCW.js +59 -0
- package/dist/chunk-VTA74YWX.js +291 -0
- package/dist/chunk-XI4TU6VU.js +50 -0
- package/dist/chunk-ZU6AY2VU.js +2 -0
- package/dist/chunk-ZU6AY2VU.js.map +1 -0
- package/dist/claude-GH6P2DC5.js +4 -0
- package/dist/claude-S47YTIHU.js +2 -0
- package/dist/claude-S47YTIHU.js.map +1 -0
- package/dist/cli.js +205 -0
- package/dist/codex-2CH57B7G.js +2 -0
- package/dist/codex-2CH57B7G.js.map +1 -0
- package/dist/codex-U7LTJTX6.js +115 -0
- package/dist/config-VN4MYHSY.js +75 -0
- package/dist/container-74P43KDY.js +1532 -0
- package/dist/context-EPHCF34F.js +83 -0
- package/dist/cursor-3DI5GKRF.js +92 -0
- package/dist/cursor-QFUNKPCQ.js +2 -0
- package/dist/cursor-QFUNKPCQ.js.map +1 -0
- package/dist/doctor-BK46WCQ5.js +67 -0
- package/dist/doctor-service-A34DHPKI.js +2 -0
- package/dist/doctor-service-NTWBWOM2.js +2 -0
- package/dist/doctor-service-NTWBWOM2.js.map +1 -0
- package/dist/goal-KGAIM3ZK.js +110 -0
- package/dist/index.d.ts +1356 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/init-QBWCEDCI.js +152 -0
- package/dist/logs-PYEKMQE2.js +207 -0
- package/dist/msg-BBIPCGDO.js +95 -0
- package/dist/orchestrator-TAFBYQQ5.js +2 -0
- package/dist/orchestrator-TAFBYQQ5.js.map +1 -0
- package/dist/orchestrator-VGYKSOZJ.js +1292 -0
- package/dist/output-5VQVCJ2K.js +2 -0
- package/dist/process-manager-HUVNAPQV.js +2 -0
- package/dist/process-manager-TLZOTO4Y.js +2 -0
- package/dist/process-manager-TLZOTO4Y.js.map +1 -0
- package/dist/registry-PQWRVNF2.js +2 -0
- package/dist/registry-UQAHK77P.js +2 -0
- package/dist/registry-UQAHK77P.js.map +1 -0
- package/dist/run-4GSZFGQZ.js +95 -0
- package/dist/shell-5ZNXFGXV.js +3 -0
- package/dist/shell-OGTSH4RJ.js +3 -0
- package/dist/shell-OGTSH4RJ.js.map +1 -0
- package/dist/status-KIISF542.js +56 -0
- package/dist/task-NUCRHYW7.js +209 -0
- package/dist/team-IBUP5XV4.js +97 -0
- package/dist/template-engine-322SCRR6.js +2 -0
- package/dist/template-engine-322SCRR6.js.map +1 -0
- package/dist/template-engine-3CDRZNMJ.js +3 -0
- package/dist/tui-WWZA73IO.js +225 -0
- package/dist/update-RJ4IYACQ.js +64 -0
- package/dist/update-check-4RV7Z6WT.js +2 -0
- package/dist/workspace-manager-47KI7B27.js +179 -0
- package/dist/workspace-manager-7M46ESUL.js +2 -0
- package/dist/workspace-manager-7M46ESUL.js.map +1 -0
- package/package.json +79 -0
- package/readme.md +270 -0
|
@@ -0,0 +1,157 @@
|
|
|
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-2VSAM7RH.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 };
|
|
@@ -0,0 +1,11 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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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.\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"]}
|
|
@@ -0,0 +1,166 @@
|
|
|
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, icons, printError, printKeyValue, printSuccess, printTable, printWarning, priorityLabel, setAsciiMode, setNoColor, statusIcon };
|
|
@@ -0,0 +1,46 @@
|
|
|
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 };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// src/infrastructure/adapters/registry.ts
|
|
3
|
+
var AdapterRegistry = class {
|
|
4
|
+
adapters = /* @__PURE__ */ new Map();
|
|
5
|
+
register(adapter) {
|
|
6
|
+
this.adapters.set(adapter.kind, adapter);
|
|
7
|
+
}
|
|
8
|
+
get(kind) {
|
|
9
|
+
return this.adapters.get(kind);
|
|
10
|
+
}
|
|
11
|
+
require(kind) {
|
|
12
|
+
const adapter = this.adapters.get(kind);
|
|
13
|
+
if (!adapter) {
|
|
14
|
+
throw new Error(`Unknown adapter: "${kind}". Available: ${this.listKinds().join(", ")}`);
|
|
15
|
+
}
|
|
16
|
+
return adapter;
|
|
17
|
+
}
|
|
18
|
+
list() {
|
|
19
|
+
return Array.from(this.adapters.values());
|
|
20
|
+
}
|
|
21
|
+
listKinds() {
|
|
22
|
+
return Array.from(this.adapters.keys());
|
|
23
|
+
}
|
|
24
|
+
has(kind) {
|
|
25
|
+
return this.adapters.has(kind);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export { AdapterRegistry };
|
|
@@ -0,0 +1,101 @@
|
|
|
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 };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class{adapters=new Map;register(t){this.adapters.set(t.kind,t);}get(t){return this.adapters.get(t)}require(t){let r=this.adapters.get(t);if(!r)throw new Error(`Unknown adapter: "${t}". Available: ${this.listKinds().join(", ")}`);return r}list(){return Array.from(this.adapters.values())}listKinds(){return Array.from(this.adapters.keys())}has(t){return this.adapters.has(t)}};export{e as a};//# sourceMappingURL=chunk-6HENRUYZ.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-6HENRUYZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|