Skip to content
Open
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
132 changes: 132 additions & 0 deletions plugins/bstack/scripts/place.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env node
// Where the orchestrator starts a lane (#325): a slot is one machine and one Claude account.
// place.mjs quota [--settings <file>] probes each Claude account in T3's settings once
// place.mjs pick < {"repo", "tickets", "environments", "quota", "now"?}
// `pick` reads the slots from T3's own answers (capabilities, projects, threads per environment) and
// prints one placement per ticket, each with the line the orchestrator posts on that ticket.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { isMain } from './lib/is-main.mjs';

const USAGE = 'usage: place.mjs quota [--settings <file>] | place.mjs pick < input';
const CLAUDE_DRIVER = 'claudeAgent';
const HOLDS_A_PROCESS = new Set(['running', 'starting', 'preparing', 'queued']);
const PROBE_ARGS = ['-p', '--model', 'haiku', '--output-format', 'stream-json', '--verbose', '--max-turns', '1'];

export const settingsFile = () => path.join(os.homedir(), '.t3', 'userdata', 'settings.json');
const expandHome = dir => (/^~($|[\\/])/.test(dir) ? path.join(os.homedir(), dir.slice(1)) : dir);

export function accounts(settings) {
return Object.entries(settings.providerInstances ?? {})
.filter(([, p]) => p.driver === CLAUDE_DRIVER && p.enabled !== false)
.map(([id, p]) => ({ id, configDir: expandHome(p.config?.homePath ?? '~/.claude') }));
}

export function quotaOf(streamJson) {
const event = streamJson.split('\n').map(line => { try { return JSON.parse(line); } catch { return null; } })
.find(e => e?.type === 'rate_limit_event');
const info = event?.rate_limit_info;
if (!info) return { status: 'unknown' };
const windows = Object.values(info.unifiedWindows ?? {});
const used = Math.max(info.utilization ?? 0, ...windows.map(w => w.utilization ?? 0));
const blocking = windows.filter(w => w.status === 'rejected').map(w => w.resetsAt);
const resetsAt = blocking.length ? Math.max(...blocking) : info.resetsAt;
return { status: info.status, left: Math.round((1 - used) * 100) / 100, resetsAt };
}

const realProbe = configDir => spawnSync('claude', PROBE_ARGS, {
input: 'Reply with OK only.', encoding: 'utf8', timeout: 60000,
env: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
}).stdout ?? '';

export function quota(settings, probe = realProbe) {
return Object.fromEntries(accounts(settings).map(a => [a.id, quotaOf(probe(a.configDir))]));
}

const repoKey = repo => `github.com/${repo}`.toLowerCase();
const utc = epoch => `${new Date(epoch * 1000).toISOString().slice(0, 16).replace('T', ' ')} UTC`;

function slotsOf({ repo, environments, quota: q = {}, now }) {
const accountIds = [...new Set(environments.flatMap(e => (e.capabilities?.providers ?? [])
.filter(p => p.driverKind === CLAUDE_DRIVER).map(p => p.providerInstanceId)))].sort();
const accountName = id => `account ${accountIds.indexOf(id) + 1}`;
const machineName = e => `machine ${e.environmentId.slice(0, 8)}`;
const slots = [];
const skipped = [];
for (const env of environments) {
const project = (env.projects ?? []).find(p => !p.archivedAt && !p.deletedAt
&& p.repositoryIdentity?.canonicalKey?.toLowerCase() === repoKey(repo));
if (!project) { skipped.push(`${machineName(env)} has no clone of the repo`); continue; }
for (const provider of env.capabilities?.providers ?? []) {
if (provider.driverKind !== CLAUDE_DRIVER || !provider.canRunChildTask) continue;
const id = provider.providerInstanceId;
const account = q[id] ?? { status: 'unknown' };
if (account.status === 'rejected' && !(account.resetsAt <= now)) {
skipped.push(`${accountName(id)} at its limit until ${account.resetsAt ? utc(account.resetsAt) : 'an unknown reset'}`);
continue;
}
const running = (env.threads ?? []).filter(t => t.providerInstanceId === id && HOLDS_A_PROCESS.has(t.status)).length;
slots.push({ environmentId: env.environmentId, projectId: project.id, providerInstanceId: id, running,
left: typeof account.left === 'number' ? account.left : null, name: `${machineName(env)}, ${accountName(id)}` });
}
}
return { slots, skipped: [...new Set(skipped)] };
}

const byLoadThenQuota = (a, b) => a.running - b.running || (b.left ?? -1) - (a.left ?? -1)
|| a.environmentId.localeCompare(b.environmentId) || a.providerInstanceId.localeCompare(b.providerInstanceId);

function reasonFor(best, slots, skipped) {
const others = slots.filter(s => s !== best);
const parts = [`fewest running lanes (${best.running}${others.length ? `, against ${others.map(s => s.running).join(', ')}` : ''})`];
const tied = others.filter(s => s.running === best.running);
const percent = left => (left === null ? 'unknown' : `${Math.round(left * 100)} %`);
if (best.left !== null && tied.some(s => (s.left ?? -1) < best.left)) parts.push(`most quota left in the tie (${percent(best.left)}, against ${tied.map(s => percent(s.left)).join(', ')})`);
else if (tied.length) parts.push('a tie, taken in id order');
if (skipped.length) parts.push(`skipped: ${skipped.join('; ')}`);
return parts.join('; ');
}

export function pick(input) {
const { tickets = [], environments } = input;
if (typeof input.repo !== 'string' || !Array.isArray(environments) || !tickets.length) throw new Error('pick needs repo, tickets and environments');
const now = input.now ?? Math.floor(Date.now() / 1000);
const { slots, skipped } = slotsOf({ ...input, now });
if (!slots.length) throw new Error(`no slot for ${input.repo}: ${skipped.join('; ') || 'no Claude account can run a child task'}`);
return tickets.map(ticket => {
const best = [...slots].sort(byLoadThenQuota)[0];
const placement = {
ticket, environmentId: best.environmentId, projectId: best.projectId, providerInstanceId: best.providerInstanceId,
line: `Placement: ${best.name}. Reason: ${reasonFor(best, slots, skipped)}.`,
};
best.running++;
return placement;
});
}

function settingsArg(args) {
if (args.length === 0) return settingsFile();
if (args.length === 2 && args[0] === '--settings') return args[1];
throw new Error(USAGE);
}

const MODES = {
quota: args => `${JSON.stringify(quota(JSON.parse(fs.readFileSync(settingsArg(args), 'utf8').replace(/^/, ''))))}\n`,
pick: () => `${JSON.stringify(pick(JSON.parse(fs.readFileSync(0, 'utf8').replace(/^/, ''))))}\n`,
};

if (isMain(import.meta.url)) {
const mode = MODES[process.argv[2]];
if (!mode) {
process.stderr.write(`${USAGE}\n`);
process.exit(2);
}
try {
process.stdout.write(mode(process.argv.slice(3)));
} catch (e) {
process.stderr.write(`${e.message}\n`);
process.exit(1);
}
}
10 changes: 7 additions & 3 deletions plugins/bstack/skills/orchestrator/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ As `bstack:plan` sizes it: one ticket; a spec with tickets; or questions to the
One lane per ticket, in the ticket's repo, in its own worktree.
1. Model: `node "${CLAUDE_PLUGIN_ROOT}/scripts/model.mjs" lane build <n> -R <owner/repo>` prints `{ model, effort }` (`research` or `mechanical` for those kinds; `--failed <n>` after failed lanes). Map the family to the provider's model id from `orchestrator_capabilities`; `session` means the orchestrator's own model.
2. Brief: `node "${CLAUDE_PLUGIN_ROOT}/scripts/lane.mjs" brief` with `{ "goal", "done", "constraints": [...] }` on stdin. It prints Goal, Done when, Constraints and Result form, in English; it refuses numbered steps, because a brief says what, never how. An open task (research, a question) gets `{ "goal", "done", "open": true }`: a goal and a done-when only.
3. Project: the `t3_project_list` entry whose `repositoryIdentity` names the repo. A repo that moved keeps its old owner there, so compare `gh repo view <remoteUrl> --json nameWithOwner`. No entry: `t3_project_clone` into a folder next to the other projects, then `t3_project_create` on it. Both need a full-access thread; when T3 refuses them (`capability_denied`), registering the repo is an owner question (access), recommended answer: the owner adds the folder as a project in T3.
4. `delegate_task` with that brief as `task`, `isolation: "worktree"`, `mode: "async"`, a `title` of `#<n> <ticket title>`, and `target`: that `projectId`, a Claude `providerInstanceId` that `canRunChildTask` and is not at its limit, `model`, and `options: { "effort": ... }`. When T3 refuses the `projectId` ("A local task runs in this thread's project"), start the lane without it and add the constraint "Work in your own git worktree of <the repo's clone>, made from origin's default branch; remove it when done."
3. Slot: a machine and a Claude account, placed by `node "${CLAUDE_PLUGIN_ROOT}/scripts/place.mjs" pick` with `{ "repo", "tickets", "environments", "quota" }` on stdin. Place every ticket of a round in one call, so they spread.
- `environments`: this machine (the `environmentId` that `t3_environment_links` returns at the top) and each linked one with `status: reachable`, each as `{ environmentId, capabilities, projects, threads }`: the `orchestrator_capabilities` answer, all pages of `t3_project_list`, and `t3_thread_list` with `allProjects`, `includeSubagents` and statuses running, starting, preparing and queued, all for that `environmentId`.
- `quota`: the output of `node "${CLAUDE_PLUGIN_ROOT}/scripts/place.mjs" quota`, once per round. It probes each Claude account in this machine's T3 settings with one small headless call; an account has the same provider instance id on every machine.
- It prints per ticket the `environmentId`, `projectId`, `providerInstanceId` and a `line`. It exits 1 when no slot can take the lane, with why. A repo that moved keeps its old owner in T3, so pass the name T3 shows (`gh repo view <remoteUrl> --json nameWithOwner` to compare). No machine has the repo: `t3_project_clone` into a folder next to the other projects, then `t3_project_create` on it. Both need a full-access thread; when T3 refuses them (`capability_denied`), registering the repo is an owner question (access), recommended answer: the owner adds the folder as a project in T3. Every account at its limit: report it with the reset time.
4. `delegate_task` with that brief as `task`, `isolation: "worktree"`, `mode: "async"`, a `title` of `#<n> <ticket title>`, and `target`: the slot's `environmentId` (left out on this machine), `projectId` and `providerInstanceId`, `model`, and `options: { "effort": ... }`. When T3 refuses the `projectId` ("A local task runs in this thread's project"), start the lane without it and add the constraint "Work in your own git worktree of <the repo's clone>, made from origin's default branch; remove it when done."
5. Post the slot's `line` on the ticket (`gh issue comment`).

Constraints every build brief carries:
- Build issue <url> in <owner/repo> through the bstack ticket and ship playbooks; a `bstack:judge` you start judges.
Expand All @@ -42,7 +46,7 @@ Pipe the lane's last message to `node "${CLAUDE_PLUGIN_ROOT}/scripts/lane.mjs" r
- **Technical** (how to build, which tool, a test approach, and any reversible choice inside the ticket's scope, even one that shapes behaviour): answer it yourself, send the answer to the lane's thread with `t3_thread_send`, and record it on the ticket in one comment (`gh issue comment`: the question, the answer, why).
- **The owner's**: on the stop list of the session rules, or about goal, scope, priority or a product choice no experiment can settle. Collect it; the other lanes go on.
- `capped`: report it with its open findings; what to do at the cap is the owner's until its own ticket says otherwise.
- A lane that failed on the account limit (`Claude API rate limit reached`): start it again on another account from its pushed branch, or report it.
- A lane that failed on the account limit (its result starts with `Claude API rate limit reached`): run `place.mjs quota` again, so that account reads `rejected` until its reset, and start the lane again through `place.mjs pick`. Its brief adds the constraint "Continue from the pushed branch <branch> and its PR; do not start over", with the branch from `gh pr list -R <repo> --search "Closes #<n> in:body" --json number,headRefName` or the ticket's status comment. No pushed branch: start from the default branch.

Before ending a turn with owner questions, ask them all at once, each with your recommended answer. Send the answers to the lanes that asked, and record each on its ticket.

Expand Down
Loading
Loading