Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 58 additions & 9 deletions templates/agent-routing/dispatch.mts
Original file line number Diff line number Diff line change
Expand Up @@ -57,23 +57,34 @@ function reserveAttempt(path: string, attempt: AttemptBinding): void {
catch { fail('attempt name already reserved; inspect live Herdr state before retry: '+attempt.name); }
try { writeFileSync(fd, JSON.stringify(attempt)+'\n'); } finally { closeSync(fd); }
}
function agentInstance(agent: Record<string,unknown>, pane: string): string {
export function extractAgentInstance(agent: Record<string,unknown>, processInfoResponse?: unknown): string | undefined {
// Herdr schemas may expose different stable identity fields.
for(const field of ['instance_id','agent_id','session_id']) {
const id=agent[field];
if((typeof id==='string' && id.length>0) || (typeof id==='number' && Number.isInteger(id)))
return field+':'+String(id);
}
// When an agent ID is unavailable, a foreground process group can fence replacement.
const info=call('herdr',['pane','process-info','--pane',pane],true);
const state:unknown=info.result;
const term=typeof agent.terminal_id==='string' && agent.terminal_id.length>0 ? 'term:'+agent.terminal_id+':' : '';
if(processInfoResponse===undefined) return undefined;
const top:unknown=isRecord(processInfoResponse) && Object.hasOwn(processInfoResponse,'result')
? processInfoResponse.result : processInfoResponse;
const state:unknown=isRecord(top) && Object.hasOwn(top,'process_info') ? top.process_info : top;
if(isRecord(state)) {
const pgid=state.foreground_pgid ?? state.foreground_process_group_id;
if(typeof pgid==='number' && Number.isInteger(pgid) && pgid>0) return 'pgid:'+pgid;
if(typeof pgid==='number' && Number.isInteger(pgid) && pgid>0) return term+'pgid:'+pgid;
const procs=state.foreground_processes;
if(Array.isArray(procs) && isRecord(procs[0]) && typeof procs[0].pid==='number')
return 'pid:'+String(procs[0].pid);
return term+'pid:'+String(procs[0].pid);
}
return undefined;
}
function agentInstance(agent: Record<string,unknown>, pane: string): string {
const direct=extractAgentInstance(agent);
if(direct) return direct;
// When an agent ID is unavailable, a foreground process group (paired with terminal_id when present) fences replacement.
const info=call('herdr',['pane','process-info','--pane',pane],true);
const resolved=extractAgentInstance(agent,info);
if(resolved) return resolved;
fail('stable live agent identity not available; do not prompt unverified pane');
}
function verifyAttempt(args: Record<string,string>, route: Route): void {
Expand Down Expand Up @@ -114,6 +125,20 @@ function call(binary: string, args: string[], json = false): CliResponse | strin
if (!json) return out.stdout.trim();
try { return JSON.parse(out.stdout) as CliResponse; } catch { fail(binary + ': malformed JSON response'); }
}
export function agentCheckCommand(platform: NodeJS.Platform = process.platform): { binary: string; args: string[] } {
// On Windows native, dotfiles exposes `agent.cmd`; Node >= 20 refuses spawning .cmd directly with shell:false (EINVAL/ETIMEDOUT).
return platform === 'win32'
? { binary: 'cmd.exe', args: ['/d', '/s', '/c', 'agent check'] }
: { binary: 'agent', args: ['check'] };
}
export function isDirectExecution(argv1: string | undefined, moduleUrl: string): boolean {
if (!argv1) return false;
try {
return realpathSync(resolve(argv1)) === realpathSync(fileURLToPath(moduleUrl));
} catch {
return resolve(argv1) === fileURLToPath(moduleUrl);
}
}
export function resolveRoute(config: unknown, role: string): Route {
if (!isRecord(config)) fail('invalid routing config');
if (typeof role !== 'string' || !NAME.test(role)) fail('invalid role');
Expand Down Expand Up @@ -169,7 +194,8 @@ export async function run(argv: string[]): Promise<unknown> {
if (configuredFunction !== undefined && typeof configuredFunction !== 'string') fail('invalid execution function');
const functionName = configuredFunction ?? args.role;
return locked(projectRoot, async () => {
call('agent',['check']);
const agentCheck = agentCheckCommand(process.platform);
call(agentCheck.binary, agentCheck.args);
const snapshot=call('herdr',['api','snapshot'],true);
const decision=planPlacement(snapshot,{
layout:config.layout, functionName, cwd, projectRoot,
Expand Down Expand Up @@ -220,9 +246,32 @@ export async function run(argv: string[]): Promise<unknown> {
pane=split?.result?.pane?.pane_id;
}
if (typeof pane!=='string'||!PANE.test(pane)) fail('layout changed but pane ID unavailable; reconcile before retry');
// Wait briefly for a freshly created shell pane (e.g. WSL .bashrc hooks) to settle before sending the command.
for (let w = 0; w < 12; w++) {
const pi = spawnSync('herdr', ['pane', 'process-info', '--pane', pane], { encoding: 'utf8', timeout: 10000 });
if (pi.status === 0) {
try {
const parsed = JSON.parse(pi.stdout) as CliResponse;
const raw: unknown = parsed?.result;
const st: unknown = isRecord(raw) && Object.hasOwn(raw, 'process_info') ? raw.process_info : raw;
if (isRecord(st) && typeof st.shell_pid === 'number' && typeof st.foreground_process_group_id === 'number') {
const fg = st.foreground_processes;
const busy = Array.isArray(fg) && fg.some((proc) => isRecord(proc) && typeof proc.pid === 'number' && proc.pid !== st.shell_pid);
if (!busy) break;
} else {
break;
}
} catch {
break;
}
} else {
break;
}
await new Promise((ok) => setTimeout(ok, 250));
}
// Provider-scoped command; never switch to herdr agent start --kind.
call('herdr',['pane','run',pane,'agent '+route.harness+' '+route.provider]);
for(let i=0;i<16;i++){
for(let i=0;i<24;i++){
await new Promise(ok=>setTimeout(ok,750));
const probe=spawnSync('herdr',['agent','get',pane],{encoding:'utf8',timeout:20000});
if (probe.status!==0) continue;
Expand Down Expand Up @@ -251,7 +300,7 @@ export async function run(argv: string[]): Promise<unknown> {
verifyAttempt(args,resolveRoute(config,args.role));
return {output:call('herdr',['agent','read',args.target,'--source','recent-unwrapped','--lines','120'])};
}
if (process.argv[1] && resolve(process.argv[1])===fileURLToPath(import.meta.url)) {
if (isDirectExecution(process.argv[1], import.meta.url)) {
run(process.argv.slice(2)).then(value=>console.log(JSON.stringify(value,null,2)),error=>{
console.error('agent-routing: '+(error instanceof Error ? error.message : String(error)));
process.exitCode=1;
Expand Down
47 changes: 46 additions & 1 deletion templates/agent-routing/dispatch.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { spawnSync } from 'node:child_process';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { test } from 'node:test';
import { resolveRoute, parseArgs, discoverProjectRoot } from './dispatch.mts';
import { resolveRoute, parseArgs, discoverProjectRoot, extractAgentInstance, agentCheckCommand, isDirectExecution } from './dispatch.mts';
const here=dirname(fileURLToPath(import.meta.url));
const config=JSON.parse(readFileSync(join(here,'agent-routing.example.json'),'utf8'));
test('free review route stays free and excludes fallback',()=>{
Expand Down Expand Up @@ -66,3 +66,48 @@ test('linked Git worktrees identify the common project root automatically',()=>{
rmSync(root,{recursive:true,force:true});
}
});

test('herdr 0.9.5 nested pane_process_info unwraps and fences agent replacement in same terminal',()=>{
const agent={name:'rev132',agent:'omp',terminal_id:'term_abc123',pane_id:'w9:p2'};
const pinfo1={
id:'cli:pane:process_info',
result:{
type:'pane_process_info',
process_info:{
pane_id:'w9:p2',
shell_pid:1001,
foreground_process_group_id:22148,
foreground_processes:[{pid:22148,name:'omp'}],
},
},
};
const pinfo2={
id:'cli:pane:process_info',
result:{
type:'pane_process_info',
process_info:{
pane_id:'w9:p2',
shell_pid:1001,
foreground_process_group_id:29999,
foreground_processes:[{pid:29999,name:'omp'}],
},
},
};
const id1=extractAgentInstance(agent,pinfo1);
const id2=extractAgentInstance(agent,pinfo2);
assert.equal(id1,'term:term_abc123:pgid:22148');
assert.equal(id2,'term:term_abc123:pgid:29999');
assert.notEqual(id1,id2);
assert.equal(extractAgentInstance(agent,{id:'cli:pane:process_info',result:{type:'pane_process_info',process_info:null}}),undefined);
});

test('agentCheckCommand uses cmd.exe for Windows .cmd shims and direct agent on POSIX',()=>{
assert.deepEqual(agentCheckCommand('win32'),{binary:'cmd.exe',args:['/d','/s','/c','agent check']});
assert.deepEqual(agentCheckCommand('darwin'),{binary:'agent',args:['check']});
assert.deepEqual(agentCheckCommand('linux'),{binary:'agent',args:['check']});
});

test('isDirectExecution resolves symlinked entrypoints instead of silently exiting 0',()=>{
assert.equal(isDirectExecution(undefined,import.meta.url),false);
assert.equal(isDirectExecution(fileURLToPath(import.meta.url),import.meta.url),true);
});
3 changes: 2 additions & 1 deletion templates/agent-routing/layout.mts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ export function resolveLayout(config: unknown = {}, functionName: string) {
return {function:fn, tabLabel, workspaceLabel:config.workspaceLabel, maxPanes, maxTabs, overflow};
}
export function normalizeSnapshot(response: unknown): Snapshot {
const result = obj(response) ? (response.result ?? response) : response;
const raw = obj(response) ? (response.result ?? response) : response;
const result = obj(raw) && Object.hasOwn(raw, 'snapshot') ? raw.snapshot : raw;
if (!obj(result)) fail('invalid snapshot');
return {workspaces:array<Workspace>(result.workspaces,'workspaces'), tabs:array<Tab>(result.tabs,'tabs'),
panes:array<Pane>(result.panes,'panes'), agents:array<Agent>(result.agents,'agents')};
Expand Down
21 changes: 21 additions & 0 deletions templates/agent-routing/layout.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,30 @@ test('existing user pane cannot be taken over as a worker',()=>{
});
test('missing or inconsistent state does not create additional layout',()=>{
assert.throws(()=>normalizeSnapshot({result:{tabs:[],panes:[],agents:[]}}),/workspaces/);
assert.throws(()=>normalizeSnapshot({id:'cli:api:snapshot',result:{type:'session_snapshot',snapshot:null}}),/invalid snapshot/);
const s=clone(active);s.result.tabs[1].pane_count=1;
assert.equal(planPlacement(s,opts).action,'blocked');
});
test('herdr 0.9.5 nested session_snapshot payload unwraps and reuses existing workspace',()=>{
const wrapped={
id:'cli:api:snapshot',
result:{
type:'session_snapshot',
snapshot:{
protocol:22,
version:'0.9.5',
workspaces:active.result.workspaces,
tabs:active.result.tabs,
panes:active.result.panes,
agents:active.result.agents,
},
},
};
const p=planPlacement(wrapped,opts);
assert.equal(p.action,'split-pane');
assert.equal(p.workspace,'w1');
assert.equal(p.tab,'w1:t2');
});
test('unknown functions and unsafe configuration fail closed',()=>{
assert.throws(()=>resolveLayout({},'arbitrary'),/unknown execution function/);
assert.throws(()=>resolveLayout({preferredPanesPerTab:8},'review'),/1..6/);
Expand Down
Loading