@phren/cli 0.3.58 → 0.3.59

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 (75) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +18 -0
  11. package/dist/bridge/account-usage.js +57 -1
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +5 -1
  23. package/dist/bridge/claude-credits.js +37 -29
  24. package/dist/bridge/command.js +12 -3
  25. package/dist/bridge/dispatch-command.js +22 -0
  26. package/dist/bridge/dispatch-returns.d.ts +23 -0
  27. package/dist/bridge/dispatch-returns.js +57 -0
  28. package/dist/bridge/dispatch.d.ts +26 -4
  29. package/dist/bridge/dispatch.js +100 -11
  30. package/dist/bridge/git-host-gitlab.js +2 -1
  31. package/dist/bridge/hand-off-queue.d.ts +71 -0
  32. package/dist/bridge/hand-off-queue.js +38 -0
  33. package/dist/bridge/harnesses.d.ts +12 -0
  34. package/dist/bridge/harnesses.js +20 -4
  35. package/dist/bridge/helper.d.ts +54 -0
  36. package/dist/bridge/helper.js +186 -0
  37. package/dist/bridge/herdr.js +6 -2
  38. package/dist/bridge/hook-fast.d.ts +3 -0
  39. package/dist/bridge/hook-fast.js +10 -2
  40. package/dist/bridge/move-computers.d.ts +15 -1
  41. package/dist/bridge/move-computers.js +123 -26
  42. package/dist/bridge/prompt-deliveries.d.ts +29 -1
  43. package/dist/bridge/prompt-deliveries.js +146 -10
  44. package/dist/bridge/schedule-watch.js +17 -3
  45. package/dist/bridge/server-routes.d.ts +3 -0
  46. package/dist/bridge/server-routes.js +66 -6
  47. package/dist/bridge/server.js +2 -1
  48. package/dist/bridge/session-move.d.ts +59 -1
  49. package/dist/bridge/session-move.js +266 -18
  50. package/dist/bridge/simulators.d.ts +19 -0
  51. package/dist/bridge/simulators.js +93 -13
  52. package/dist/bridge/speech-live.js +132 -22
  53. package/dist/bridge/task-routes.d.ts +16 -16
  54. package/dist/bridge/terminal-herdr.js +6 -1
  55. package/dist/bridge/terminal-tmux.js +9 -5
  56. package/dist/bridge/terminal.d.ts +9 -2
  57. package/dist/bridge/transcript-claude.d.ts +3 -0
  58. package/dist/bridge/transcript-claude.js +175 -29
  59. package/dist/bridge/transcript-preview.d.ts +11 -2
  60. package/dist/bridge/transcript-preview.js +90 -8
  61. package/dist/bridge/turn-records.d.ts +19 -0
  62. package/dist/bridge/turn-records.js +78 -3
  63. package/dist/bridge-hook.mjs +11394 -9961
  64. package/dist/cli-registry.js +2 -2
  65. package/dist/content/citation.d.ts +4 -0
  66. package/dist/content/citation.js +21 -21
  67. package/dist/data/task-contract.d.ts +4 -4
  68. package/dist/governance/policy.js +5 -2
  69. package/dist/index.js +1 -1
  70. package/dist/modules/registry.js +3 -3
  71. package/dist/project-config.d.ts +14 -0
  72. package/dist/project-config.js +40 -1
  73. package/dist/tools/helper.d.ts +3 -0
  74. package/dist/tools/helper.js +44 -0
  75. package/package.json +1 -1
package/README.md CHANGED
@@ -6,7 +6,7 @@ On startup it walks your phren directory, reads all `.md` files, and builds an i
6
6
 
7
7
  Periodic remote checks are off by default. Enable them with `phren config pull-interval 60` to check shared Git stores every minute while running, coordinated across MCP clients using the same store. Changed refs are fetched and applied only as clean fast-forwards; dirty or diverged stores are deferred. Pulled changes refresh the index and existing managed skill/instruction mirrors. Configure this machine with `phren config pull-interval 600` (ten minutes) or `phren config pull-interval off`. Periodic checks are disabled for project-local stores and the manual preset; existing lifecycle hooks are configured separately.
8
8
 
9
- Public surface: 76 MCP implementation tools across 16 catalog modules (search, tasks, findings, notes, memory, data, graph, sessions, ops/review, skills, hooks, config, extraction).
9
+ Public surface: 78 MCP implementation tools across 17 catalog modules (search, tasks, findings, notes, memory, data, graph, sessions, ops/review, skills, hooks, config, extraction).
10
10
 
11
11
  Notable shipped capabilities:
12
12
  - finding lifecycle tools: `supersede_finding`, `retract_finding`, `resolve_contradiction`, `get_contradictions`
@@ -1,7 +1,37 @@
1
1
  import { z } from "zod";
2
+ import { type AuthStatus, type ClaudeHome } from "./claude-accounts.js";
2
3
  import { type Json } from "./protocol.js";
3
4
  export declare const accountAddSchema: z.ZodObject<{
4
5
  slug: z.ZodString;
6
+ email: z.ZodOptional<z.ZodString>;
5
7
  }, z.core.$strict>;
8
+ /** An existing slot's sign-in: `sign-in` opens `claude /login` for it, `sign-in-status` says whether it is signed in. */
9
+ export declare const accountSignInSchema: z.ZodObject<{
10
+ slug: z.ZodString;
11
+ mode: z.ZodEnum<{
12
+ "sign-in": "sign-in";
13
+ "sign-in-status": "sign-in-status";
14
+ }>;
15
+ }, z.core.$strict>;
16
+ /**
17
+ * `claude /login` under the slot's own home, never the pane shell's: a shell that exports CLAUDE_CONFIG_DIR
18
+ * (`~/.claude-work` from the owner's profile) would otherwise sign in that account while the Hook checks this
19
+ * one. The default home the Hook found without CLAUDE_CONFIG_DIR runs with it removed (Claude's own default,
20
+ * where its keychain item lives); every home the Hook found through it, the default one included and even when
21
+ * that is ~/.claude, runs with it set to the home, as the Hook's own status check does. `env` runs a program,
22
+ * not the shell's alias for `claude` (an old local install's `alias claude=~/.claude/local/claude`), so the
23
+ * command names the `claude` the Hook finds on its PATH, when it finds one.
24
+ */
25
+ export declare function loginCommand(home: ClaudeHome, claude?: string | undefined): string;
26
+ /**
27
+ * Sign in an account slot that exists but is signed out, from the phone: opens a pane running `claude /login`
28
+ * for it, as adding an account does, for the owner to finish. A slot already signed in is refused; one whose
29
+ * state Claude did not report opens anyway (logging in again is harmless). `sign-in-status` answers whether
30
+ * it is signed in now: asked afresh while a sign-in pane for the slot is open (the owner is finishing the
31
+ * login there, so a cached answer would lag it), else at most half a minute old when signed out.
32
+ */
33
+ export declare function signInClaudeAccount(input: unknown, server: string, auth?: (home: ClaudeHome, options: {
34
+ fresh: boolean;
35
+ }) => Promise<AuthStatus>): Promise<Json>;
6
36
  /** Open a shell for the owner to complete the existing interactive flow. */
7
37
  export declare function addClaudeAccount(input: unknown, server: string): Promise<Json>;
@@ -1,36 +1,142 @@
1
- import { existsSync } from "node:fs";
1
+ import { accessSync, constants, existsSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { z } from "zod";
4
4
  import { homeDir } from "../home-paths.js";
5
- import { claudeHomes } from "./claude-accounts.js";
5
+ import { badAccountSlug, suggestAccountSlug } from "./claude-account-setup.js";
6
+ import { claudeAuthStatus, claudeHome, claudeHomes, clearAccountCaches, DEFAULT_ACCOUNT, isAccountSlug } from "./claude-accounts.js";
6
7
  import { BridgeError, bridgeRoot } from "./protocol.js";
7
8
  import { terminalProvider } from "./terminal.js";
8
- export const accountAddSchema = z.object({ slug: z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/) }).strict();
9
+ export const accountAddSchema = z.object({ slug: z.string().max(256), email: z.string().max(254).optional() }).strict();
10
+ /** An existing slot's sign-in: `sign-in` opens `claude /login` for it, `sign-in-status` says whether it is signed in. */
11
+ export const accountSignInSchema = z.object({ slug: z.string().max(256), mode: z.enum(["sign-in", "sign-in-status"]) }).strict();
12
+ /** The slot `slug` names, or why there is none. */
13
+ function existingSlot(slug) {
14
+ if (!isAccountSlug(slug))
15
+ throw new BridgeError(400, badAccountSlug(slug), { suggestedSlug: suggestAccountSlug(slug) });
16
+ const home = claudeHome(slug);
17
+ if (!home)
18
+ throw new BridgeError(404, `There is no Claude account "${slug}" on this computer. Add it first.`);
19
+ return home;
20
+ }
21
+ /**
22
+ * `claude /login` under the slot's own home, never the pane shell's: a shell that exports CLAUDE_CONFIG_DIR
23
+ * (`~/.claude-work` from the owner's profile) would otherwise sign in that account while the Hook checks this
24
+ * one. The default home the Hook found without CLAUDE_CONFIG_DIR runs with it removed (Claude's own default,
25
+ * where its keychain item lives); every home the Hook found through it, the default one included and even when
26
+ * that is ~/.claude, runs with it set to the home, as the Hook's own status check does. `env` runs a program,
27
+ * not the shell's alias for `claude` (an old local install's `alias claude=~/.claude/local/claude`), so the
28
+ * command names the `claude` the Hook finds on its PATH, when it finds one.
29
+ */
30
+ export function loginCommand(home, claude = claudeBinary()) {
31
+ const quote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
32
+ const configured = !home.isDefault || home.configFile === path.join(home.dir, ".claude.json");
33
+ const program = claude ? quote(claude) : "claude";
34
+ return configured ? `env CLAUDE_CONFIG_DIR=${quote(home.dir)} ${program} /login` : `env -u CLAUDE_CONFIG_DIR ${program} /login`;
35
+ }
36
+ /** The `claude` executable on the Hook's PATH, else Claude's own local install, else undefined. */
37
+ function claudeBinary() {
38
+ const candidates = [...(process.env.PATH ?? "").split(path.delimiter).filter(Boolean).map(directory => path.join(directory, "claude")),
39
+ path.join(homeDir(), ".claude", "local", "claude")];
40
+ return candidates.find(file => { try {
41
+ accessSync(file, constants.X_OK);
42
+ return statSync(file).isFile();
43
+ }
44
+ catch {
45
+ return false;
46
+ } });
47
+ }
48
+ /** A sign-in pane blocks another for its slot this long: it stays open as a Claude session once signed in. */
49
+ const SIGN_IN_PANE_MS = 10 * 60_000;
50
+ /**
51
+ * Sign in an account slot that exists but is signed out, from the phone: opens a pane running `claude /login`
52
+ * for it, as adding an account does, for the owner to finish. A slot already signed in is refused; one whose
53
+ * state Claude did not report opens anyway (logging in again is harmless). `sign-in-status` answers whether
54
+ * it is signed in now: asked afresh while a sign-in pane for the slot is open (the owner is finishing the
55
+ * login there, so a cached answer would lag it), else at most half a minute old when signed out.
56
+ */
57
+ export async function signInClaudeAccount(input, server, auth = (home, { fresh }) => { if (fresh)
58
+ clearAccountCaches(); return claudeAuthStatus(home); }) {
59
+ const { slug, mode } = accountSignInSchema.parse(input);
60
+ const home = existingSlot(slug);
61
+ const key = `${bridgeRoot()}\0sign-in\0${home.id}`;
62
+ const pending = pendingPanes.get(key);
63
+ const status = await auth(home, { fresh: mode === "sign-in-status" && !!pending && Date.now() - (pending.at ?? 0) < SIGN_IN_PANE_MS });
64
+ // Signed in: the pane that did it is a Claude session now, not a sign-in under way.
65
+ if (status.signedIn)
66
+ pendingPanes.delete(key);
67
+ if (mode === "sign-in-status")
68
+ return { slug: home.id, signedIn: status.signedIn, ...(status.unknown ? { unknown: true } : {}), ...(status.plan ? { plan: status.plan } : {}) };
69
+ if (status.signedIn)
70
+ throw new BridgeError(409, `Claude account "${home.id}" is already signed in.`, { code: "signed-in" });
71
+ if (adding.has(key))
72
+ throw new BridgeError(409, "That Claude account is already being signed in.");
73
+ adding.add(key);
74
+ try {
75
+ if (pending && Date.now() - (pending.at ?? 0) >= SIGN_IN_PANE_MS)
76
+ pendingPanes.delete(key);
77
+ const pane = await openPane(server, key, `Sign in to Claude account ${home.id}`, "That Claude account is already being signed in in an open pane.");
78
+ await terminalProvider().shellCommand(server, pane.pane, loginCommand(home));
79
+ return { target: { server, workspace: pane.workspace, tab: pane.tab, pane: pane.pane, source: "claude" }, terminalOnly: true, slug: home.id };
80
+ }
81
+ finally {
82
+ adding.delete(key);
83
+ }
84
+ }
85
+ /**
86
+ * A new pane for an interactive account step, refused while the last one for `key` is still open. The pane is
87
+ * the one the terminal says it created; a terminal that doesn't say is diffed before and after, one account
88
+ * pane at a time per terminal server, so two sign-ins at once (different slots) never see each other's pane.
89
+ */
90
+ async function openPane(server, key, label, busy) {
91
+ const terminal = terminalProvider();
92
+ if (!terminal.shellCommand)
93
+ throw new BridgeError(503, "This terminal cannot open an interactive account login.");
94
+ return oneAtATime(server, async () => {
95
+ const pending = pendingPanes.get(key);
96
+ // A terminal server that no longer answers holds no open account pane.
97
+ if (pending && (await terminal.listPanes(pending.server).catch(() => [])).some(pane => pane.pane === pending.pane))
98
+ throw new BridgeError(409, busy);
99
+ pendingPanes.delete(key);
100
+ const before = new Set((await terminal.listPanes(server)).map(pane => pane.pane));
101
+ const named = await terminal.create(server, { label, cwd: homeDir() });
102
+ let created;
103
+ if (named)
104
+ created = named;
105
+ else {
106
+ const found = (await terminal.listPanes(server)).filter(pane => !before.has(pane.pane));
107
+ if (found.length !== 1)
108
+ throw new BridgeError(409, "The new account pane could not be identified safely.");
109
+ created = found[0];
110
+ }
111
+ pendingPanes.set(key, { server, pane: created.pane, at: Date.now() });
112
+ return { server, workspace: created.workspace, tab: created.tab, pane: created.pane };
113
+ });
114
+ }
115
+ /** Account panes being opened, by terminal server: the next waits for the last. */
116
+ const opening = new Map();
117
+ function oneAtATime(server, work) {
118
+ const result = (opening.get(server) ?? Promise.resolve()).then(work);
119
+ const tail = result.catch(() => undefined);
120
+ opening.set(server, tail);
121
+ void tail.then(() => { if (opening.get(server) === tail)
122
+ opening.delete(server); });
123
+ return result;
124
+ }
9
125
  const adding = new Set();
10
126
  const pendingPanes = new Map();
11
127
  /** Open a shell for the owner to complete the existing interactive flow. */
12
128
  export async function addClaudeAccount(input, server) {
13
- const { slug } = accountAddSchema.parse(input);
129
+ const { slug, email } = accountAddSchema.parse(input);
130
+ // Answered with a name that would work, so the phone can offer it rather than a bare refusal.
131
+ if (slug === DEFAULT_ACCOUNT || !isAccountSlug(slug))
132
+ throw new BridgeError(400, badAccountSlug(slug, email), { suggestedSlug: suggestAccountSlug(slug, email) });
14
133
  const key = `${bridgeRoot()}\0${slug}`;
15
134
  if (adding.has(key) || claudeHomes().some(home => home.id === slug) || existsSync(path.join(homeDir(), `.claude-${slug}`)))
16
135
  throw new BridgeError(409, "That Claude account already exists or is being added.");
17
136
  adding.add(key);
18
137
  try {
19
- const terminal = terminalProvider();
20
- if (!terminal.shellCommand)
21
- throw new BridgeError(503, "This terminal cannot open an interactive account login.");
22
- const pending = pendingPanes.get(key);
23
- if (pending && (await terminal.listPanes(pending.server)).some(pane => pane.pane === pending.pane))
24
- throw new BridgeError(409, "That Claude account is already being added in an open pane.");
25
- pendingPanes.delete(key);
26
- const before = new Set((await terminal.listPanes(server)).map(pane => pane.pane));
27
- await terminal.create(server, { label: `Add Claude account ${slug}`, cwd: homeDir() });
28
- const created = (await terminal.listPanes(server)).filter(pane => !before.has(pane.pane));
29
- if (created.length !== 1)
30
- throw new BridgeError(409, "The new account pane could not be identified safely.");
31
- const pane = created[0];
32
- pendingPanes.set(key, { server, pane: pane.pane });
33
- await terminal.shellCommand(server, pane.pane, `phren bridge accounts add -- '${slug}'`);
138
+ const pane = await openPane(server, key, `Add Claude account ${slug}`, "That Claude account is already being added in an open pane.");
139
+ await terminalProvider().shellCommand(server, pane.pane, `phren bridge accounts add -- '${slug}'`);
34
140
  return { target: { server, workspace: pane.workspace, tab: pane.tab, pane: pane.pane, source: "claude" }, terminalOnly: true };
35
141
  }
36
142
  finally {
@@ -34,8 +34,15 @@ export declare function quoted(title: string, text: string): string[];
34
34
  /** `head`, then the original brief, cut to fit `limit` with a note saying the full text is in `where`. */
35
35
  export declare function withOriginalBrief(head: string, original: string, limit: number, where: string): string;
36
36
  export interface AccountFailoverOptions {
37
- /** Every connected computer's Claude accounts with their room (`DispatchService.claudeRooms`). */
38
- rooms: () => Promise<ComputerRooms[]>;
37
+ /** Every connected computer's Claude accounts with their room (`DispatchService.claudeRooms`): those the
38
+ * stopped worker's project and each computer's pools and roles let it continue on, and the stopped login. */
39
+ rooms: (context: {
40
+ project: string;
41
+ stopped: {
42
+ computer: string;
43
+ account: string;
44
+ };
45
+ }) => Promise<ComputerRooms[]>;
39
46
  /** Places the continuing worker (`DispatchService.dispatch`); `continues` names the stopped dispatch. */
40
47
  dispatch: (input: Json, origin: unknown, continues: string) => Promise<Json>;
41
48
  peers?: () => Promise<HookPeer[]>;
@@ -134,7 +134,7 @@ export class AccountFailover {
134
134
  return;
135
135
  }
136
136
  const account = receipt.account ?? "default";
137
- const computers = await this.options.rooms();
137
+ const computers = await this.options.rooms({ project: receipt.project, stopped: { computer: receipt.computer, account } });
138
138
  const room = computers.find(item => item.computer === receipt.computer)?.rooms.find(candidate => candidate.account === account);
139
139
  // Never this login again until its window resets, here or wherever else it is signed in.
140
140
  await noteAccountLimit({ key: limitKey(room ?? { account }, receipt.computer), account, until: limitUntil(room) }, this.now);
@@ -0,0 +1,44 @@
1
+ import { type AccountChoice, type AccountRoom } from "./account-choice.js";
2
+ import { type AccountRole } from "./account-pools.js";
3
+ /** An account room with what the harness listing says about its pool, role and login. */
4
+ export interface PolicyRoom extends AccountRoom {
5
+ pool?: string;
6
+ role?: AccountRole;
7
+ console?: boolean;
8
+ }
9
+ /** Whose `allowedPools` a choice must keep to: "project client-a", "computer Desk". No `pools`: any pool. */
10
+ export interface PoolRule {
11
+ owner: string;
12
+ pools?: readonly string[];
13
+ }
14
+ /** A project's rule, from its `phren.project.yaml` in the store (or the team store holding it). */
15
+ export declare function projectRule(phrenPath: string, project: string): PoolRule;
16
+ /** A computer's rule from what its harness listing reports (its Claude entry's `allowedPools`, or that its
17
+ * accounts.yaml can't be read). */
18
+ export declare function computerRule(computer: string, pools: unknown, unreadable?: boolean): PoolRule;
19
+ /** The pool, role and Console flag a listed account carries, checked, onto its room. */
20
+ export declare function withPolicy<T extends AccountRoom>(room: T, listed: {
21
+ pool?: unknown;
22
+ role?: unknown;
23
+ console?: unknown;
24
+ } | undefined): T & PolicyRoom;
25
+ /** Why `room` may not do this work under `rules` at all, or undefined. Applies to a named account too. */
26
+ export declare function poolRefusal(room: Pick<PolicyRoom, "account" | "pool">, rules: readonly PoolRule[]): string | undefined;
27
+ /** Why `room` is never chosen automatically, or undefined. */
28
+ export declare function notAutomatic(room: Pick<PolicyRoom, "role" | "console">): string | undefined;
29
+ /** Whether any pool, role or Console login could change a choice among `rooms` under `rules`. */
30
+ export declare function policyApplies(rooms: readonly PolicyRoom[], rules: readonly PoolRule[]): boolean;
31
+ /** The rooms a rule and the roles allow an automatic choice to take. */
32
+ export declare function allowedRooms<T extends PolicyRoom>(rooms: readonly T[], rules: readonly PoolRule[]): T[];
33
+ /** Whether an allowed room has room to take work: signed in, not out of quota, not `held` (the limits ledger, a
34
+ * worker that just stopped there). */
35
+ export declare const openRoom: (room: PolicyRoom, held?: (room: PolicyRoom) => boolean) => boolean;
36
+ /**
37
+ * `chooseAccount` with pools and roles: rooms a rule refuses or that are not automatic are skipped, with why;
38
+ * the rest are ranked by headroom as before, `last-resort` ones only when no other account has room.
39
+ */
40
+ export declare function choosePolicyAccount(rooms: readonly PolicyRoom[], rules?: readonly PoolRule[], blocked?: (room: AccountRoom) => string | undefined): {
41
+ choice?: AccountChoice;
42
+ skipped: string[];
43
+ lastResort?: true;
44
+ };
@@ -0,0 +1,103 @@
1
+ // Account pools and roles applied to an automatic account choice (dispatch placement, Continue in…, the
2
+ // accounts a stopped worker may continue on). See docs/accounts.md.
3
+ //
4
+ // - A pool rule (a project's or a computer's `allowedPools`) refuses an account outside it, chosen or named.
5
+ // - `off` is never chosen automatically, and neither is a Console (API-billed) login with no role: API accounts
6
+ // are off for automatic use until the owner gives them a role. Both can still be named by hand.
7
+ // - `last-resort` accounts are offered only when no other account (ordinary or `helpers`) fits.
8
+ // With no pools, no roles and no Console logins nothing here changes a choice. A config that can't be read
9
+ // allows no pool rather than any.
10
+ import { readFileSync } from "node:fs";
11
+ import { load } from "js-yaml";
12
+ import { resolveProjectConfigPath } from "../project-config.js";
13
+ import { chooseAccount } from "./account-choice.js";
14
+ import { isAccountRole, isPoolTag, poolAllowed } from "./account-pools.js";
15
+ const REFUSAL_MAX = 280;
16
+ /** A project's rule, from its `phren.project.yaml` in the store (or the team store holding it). */
17
+ export function projectRule(phrenPath, project) {
18
+ const owner = `project ${project}`;
19
+ const file = resolveProjectConfigPath(phrenPath, project);
20
+ if (!file)
21
+ return { owner };
22
+ let text;
23
+ try {
24
+ text = readFileSync(file, "utf8");
25
+ }
26
+ catch (error) {
27
+ if (error.code === "ENOENT" || error.code === "EISDIR")
28
+ return { owner };
29
+ return { owner: `${owner} (its phren.project.yaml can't be read)`, pools: [] };
30
+ }
31
+ let parsed;
32
+ // A broken file that never named allowedPools had no list: it stays "any pool", as before pools existed.
33
+ try {
34
+ parsed = text.trim() ? load(text) : {};
35
+ }
36
+ catch {
37
+ return text.includes("allowedPools") ? { owner: `${owner} (its phren.project.yaml can't be read)`, pools: [] } : { owner };
38
+ }
39
+ const pools = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.allowedPools : undefined;
40
+ return { owner, ...(Array.isArray(pools) ? { pools: pools.filter(isPoolTag) } : {}) };
41
+ }
42
+ /** A computer's rule from what its harness listing reports (its Claude entry's `allowedPools`, or that its
43
+ * accounts.yaml can't be read). */
44
+ export function computerRule(computer, pools, unreadable = false) {
45
+ if (unreadable)
46
+ return { owner: `computer ${computer} (its accounts.yaml can't be read)`, pools: [] };
47
+ return { owner: `computer ${computer}`, ...(Array.isArray(pools) ? { pools: pools.filter(isPoolTag) } : {}) };
48
+ }
49
+ /** The pool, role and Console flag a listed account carries, checked, onto its room. */
50
+ export function withPolicy(room, listed) {
51
+ return { ...room, ...(isPoolTag(listed?.pool) ? { pool: listed.pool } : {}), ...(isAccountRole(listed?.role) ? { role: listed.role } : {}),
52
+ ...(listed?.console === true ? { console: true } : {}) };
53
+ }
54
+ /** Why `room` may not do this work under `rules` at all, or undefined. Applies to a named account too. */
55
+ export function poolRefusal(room, rules) {
56
+ const rule = rules.find(item => !poolAllowed(item.pools, room.pool));
57
+ if (!rule)
58
+ return undefined;
59
+ const listed = rule.pools.length ? `'s allowed pools (${rule.pools.join(", ")})` : "'s allowed pools";
60
+ return `${room.pool ? `its pool ${room.pool}` : "it has no pool, and"} is not in ${rule.owner}${listed}`.slice(0, REFUSAL_MAX);
61
+ }
62
+ /** Why `room` is never chosen automatically, or undefined. */
63
+ export function notAutomatic(room) {
64
+ if (room.role === "off")
65
+ return "role off (chosen only by hand)";
66
+ if (!room.role && room.console)
67
+ return "an API account with no role (chosen only by hand)";
68
+ return undefined;
69
+ }
70
+ /** Whether any pool, role or Console login could change a choice among `rooms` under `rules`. */
71
+ export function policyApplies(rooms, rules) {
72
+ return rules.some(rule => rule.pools) || rooms.some(room => room.role || room.pool || room.console);
73
+ }
74
+ /** The rooms a rule and the roles allow an automatic choice to take. */
75
+ export function allowedRooms(rooms, rules) {
76
+ return rooms.filter(room => !poolRefusal(room, rules) && !notAutomatic(room));
77
+ }
78
+ /** Whether an allowed room has room to take work: signed in, not out of quota, not `held` (the limits ledger, a
79
+ * worker that just stopped there). */
80
+ export const openRoom = (room, held = () => false) => room.usable !== false && !room.exhausted && !held(room);
81
+ /**
82
+ * `chooseAccount` with pools and roles: rooms a rule refuses or that are not automatic are skipped, with why;
83
+ * the rest are ranked by headroom as before, `last-resort` ones only when no other account has room.
84
+ */
85
+ export function choosePolicyAccount(rooms, rules = [], blocked = () => undefined) {
86
+ const skipped = [];
87
+ const allowed = rooms.filter(room => {
88
+ const why = poolRefusal(room, rules) ?? notAutomatic(room);
89
+ if (why)
90
+ skipped.push(`${room.account}: ${why}`);
91
+ return !why;
92
+ });
93
+ const ruledOut = skipped.length ? `; ruled out ${skipped.join(", ")}` : "";
94
+ const first = chooseAccount(allowed.filter(room => room.role !== "last-resort"), blocked);
95
+ if (first.choice)
96
+ return { choice: { account: first.choice.account, reason: `${first.choice.reason}${ruledOut}`.slice(0, 400) }, skipped: [...skipped, ...first.skipped] };
97
+ const last = chooseAccount(allowed.filter(room => room.role === "last-resort"), blocked);
98
+ const all = [...skipped, ...first.skipped, ...last.skipped];
99
+ if (!last.choice)
100
+ return { skipped: all };
101
+ const without = first.skipped.length ? ` (${first.skipped.join(", ")})` : "";
102
+ return { choice: { account: last.choice.account, reason: `last resort, no other account has room${without}; ${last.choice.reason}${ruledOut}`.slice(0, 400) }, skipped: all, lastResort: true };
103
+ }
@@ -0,0 +1,35 @@
1
+ export declare const ACCOUNT_ROLES: readonly ["helpers", "last-resort", "off"];
2
+ export type AccountRole = typeof ACCOUNT_ROLES[number];
3
+ export interface AccountSettings {
4
+ pool?: string;
5
+ role?: AccountRole;
6
+ }
7
+ export declare const isPoolTag: (value: unknown) => value is string;
8
+ export declare const isAccountRole: (value: unknown) => value is AccountRole;
9
+ /** Every slot's pool and role that is set, by slug. For listings: an unreadable file reads as none set. */
10
+ export declare function accountSettings(): Record<string, AccountSettings>;
11
+ /**
12
+ * The slots' pools and roles and this computer's allowed pools, for a caller that enforces them: an
13
+ * `accounts.yaml` that is there but can't be read throws rather than reading as "nothing restricted".
14
+ */
15
+ export declare function accountPolicy(): {
16
+ settings: Record<string, AccountSettings>;
17
+ allowedPools?: string[];
18
+ };
19
+ /** Sets or clears (`null`) a slot's pool and role; a field left out stays as it is. */
20
+ export declare function setAccountSettings(slug: string, change: {
21
+ pool?: string | null;
22
+ role?: AccountRole | null;
23
+ }): Promise<AccountSettings>;
24
+ /** The pools this computer's accounts may do work for, or undefined: any. */
25
+ export declare function computerAllowedPools(): string[] | undefined;
26
+ export declare function setComputerAllowedPools(pools: readonly string[] | null): Promise<string[] | undefined>;
27
+ /** The pools whose accounts may do a project's work, from its `phren.project.yaml`, or undefined: any. */
28
+ export declare function projectAllowedPools(phrenPath: string, project: string): string[] | undefined;
29
+ export declare function setProjectAllowedPools(phrenPath: string, project: string, pools: readonly string[] | null): string[] | undefined;
30
+ /** Whether an account in `pool` may work where `allowed` is the list: no list is any pool; a list leaves out an
31
+ * account with no pool. */
32
+ export declare function poolAllowed(allowed: readonly string[] | undefined, pool: string | undefined): boolean;
33
+ /** `phren bridge accounts pool|role|allowed-pools …`: the lines to print. */
34
+ export declare function accountPoolsCommand(args: readonly string[], projectStore: () => string, exists: (slug: string) => boolean): Promise<string[]>;
35
+ export declare const POOLS_USAGE = "Usage: phren bridge accounts pool <id> <tag>|--clear | role <id> helpers|last-resort|off|--clear | allowed-pools [--project <name>] [<tag>\u2026 | --clear]";
@@ -0,0 +1,171 @@
1
+ // Account pools and roles: which Claude accounts may do which work. All opt-in; a store that sets none behaves
2
+ // exactly as before. See docs/accounts.md.
3
+ //
4
+ // - An account slot's `pool` is a short tag (`personal`, `client-a`) and its `role` says how it is used
5
+ // automatically: `helpers` (helper runs, `last-resort` only when no `helpers` account fits) or `off` (never
6
+ // chosen automatically; still by hand). An account with no role is an ordinary one, as every account was.
7
+ // - A project (its `phren.project.yaml`) and a computer (this Hook's `accounts.yaml`) may list `allowedPools`:
8
+ // the pools whose accounts may do its work. No list means any pool.
9
+ //
10
+ // Kept in `<bridge>/accounts.yaml` beside the labels (`claude`) and the API credits (`credits`):
11
+ // slots: { <slug>: { pool: <tag>, role: helpers | last-resort | off } }
12
+ // allowedPools: [<tag>, …]
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import path from "node:path";
15
+ import { readProjectConfig, resolveProjectConfigPath, setProjectConfigField } from "../project-config.js";
16
+ import { accountsFile, isAccountSlug, parseAccountsYaml, updateAccountsFile } from "./claude-accounts.js";
17
+ import { object } from "./protocol.js";
18
+ /** A project's name, as dispatch takes it (dispatch.ts `projectName`). */
19
+ const PROJECT = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
20
+ export const ACCOUNT_ROLES = ["helpers", "last-resort", "off"];
21
+ const POOL = /^[a-z0-9][a-z0-9-]{0,31}$/;
22
+ const MAX_POOLS = 32;
23
+ export const isPoolTag = (value) => typeof value === "string" && POOL.test(value);
24
+ export const isAccountRole = (value) => typeof value === "string" && ACCOUNT_ROLES.includes(value);
25
+ const poolHelp = "A pool is 1 to 32 lowercase letters, digits and dashes, like personal or client-a.";
26
+ function readSync() {
27
+ try {
28
+ return parseAccountsYaml(readFileSync(accountsFile(), "utf8"));
29
+ }
30
+ catch {
31
+ return {};
32
+ }
33
+ }
34
+ const update = updateAccountsFile;
35
+ const settingsOf = (raw) => {
36
+ const item = object(raw);
37
+ return { ...(isPoolTag(item.pool) ? { pool: item.pool } : {}), ...(isAccountRole(item.role) ? { role: item.role } : {}) };
38
+ };
39
+ const settingsFrom = (parsed) => Object.fromEntries(Object.entries(object(parsed.slots)).filter(([slug]) => isAccountSlug(slug))
40
+ .map(([slug, raw]) => [slug, settingsOf(raw)]).filter(([, settings]) => Object.keys(settings).length));
41
+ /** Every slot's pool and role that is set, by slug. For listings: an unreadable file reads as none set. */
42
+ export function accountSettings() { return settingsFrom(readSync()); }
43
+ /**
44
+ * The slots' pools and roles and this computer's allowed pools, for a caller that enforces them: an
45
+ * `accounts.yaml` that is there but can't be read throws rather than reading as "nothing restricted".
46
+ */
47
+ export function accountPolicy() {
48
+ let text;
49
+ try {
50
+ text = readFileSync(accountsFile(), "utf8");
51
+ }
52
+ catch (error) {
53
+ if (error.code !== "ENOENT")
54
+ throw error;
55
+ }
56
+ let parsed;
57
+ try {
58
+ parsed = parseAccountsYaml(text);
59
+ }
60
+ catch (error) {
61
+ throw new Error(`${accountsFile()} can't be read (${error instanceof Error ? error.message.split("\n")[0] : "bad YAML"}); fix it first.`);
62
+ }
63
+ const allowedPools = poolsOf(parsed.allowedPools);
64
+ return { settings: settingsFrom(parsed), ...(allowedPools ? { allowedPools } : {}) };
65
+ }
66
+ /** Sets or clears (`null`) a slot's pool and role; a field left out stays as it is. */
67
+ export async function setAccountSettings(slug, change) {
68
+ if (!isAccountSlug(slug))
69
+ throw new Error(`"${slug}" is not an account name: use lowercase letters, digits and dashes.`);
70
+ if (change.pool !== undefined && change.pool !== null && !isPoolTag(change.pool))
71
+ throw new Error(poolHelp);
72
+ if (change.role !== undefined && change.role !== null && !isAccountRole(change.role))
73
+ throw new Error(`A role is ${ACCOUNT_ROLES.join(", ")}.`);
74
+ let next = {};
75
+ await update(parsed => {
76
+ const slots = { ...object(parsed.slots) };
77
+ next = settingsOf(slots[slug]);
78
+ for (const key of ["pool", "role"]) {
79
+ if (change[key] === null)
80
+ delete next[key];
81
+ else if (change[key] !== undefined)
82
+ next[key] = change[key];
83
+ }
84
+ if (Object.keys(next).length)
85
+ slots[slug] = next;
86
+ else
87
+ delete slots[slug];
88
+ if (Object.keys(slots).length)
89
+ parsed.slots = slots;
90
+ else
91
+ delete parsed.slots;
92
+ });
93
+ return next;
94
+ }
95
+ /** A list of pool tags as stored: the valid ones, at most MAX_POOLS, or undefined for no list. */
96
+ const poolsOf = (raw) => Array.isArray(raw) ? [...new Set(raw.filter(isPoolTag))].slice(0, MAX_POOLS) : undefined;
97
+ function checkedPools(pools) {
98
+ if (pools === null)
99
+ return null;
100
+ if (!pools.length)
101
+ throw new Error("List at least one pool, or clear the list.");
102
+ if (pools.length > MAX_POOLS)
103
+ throw new Error(`At most ${MAX_POOLS} pools.`);
104
+ for (const pool of pools)
105
+ if (!isPoolTag(pool))
106
+ throw new Error(poolHelp);
107
+ return [...new Set(pools)];
108
+ }
109
+ /** The pools this computer's accounts may do work for, or undefined: any. */
110
+ export function computerAllowedPools() { return poolsOf(readSync().allowedPools); }
111
+ export async function setComputerAllowedPools(pools) {
112
+ const next = checkedPools(pools);
113
+ await update(parsed => { if (next)
114
+ parsed.allowedPools = next;
115
+ else
116
+ delete parsed.allowedPools; });
117
+ return next ?? undefined;
118
+ }
119
+ /** The pools whose accounts may do a project's work, from its `phren.project.yaml`, or undefined: any. */
120
+ export function projectAllowedPools(phrenPath, project) {
121
+ return poolsOf(readProjectConfig(phrenPath, project).allowedPools);
122
+ }
123
+ export function setProjectAllowedPools(phrenPath, project, pools) {
124
+ const next = checkedPools(pools);
125
+ setProjectConfigField(phrenPath, project, "allowedPools", next ?? undefined);
126
+ return next ?? undefined;
127
+ }
128
+ /** Whether an account in `pool` may work where `allowed` is the list: no list is any pool; a list leaves out an
129
+ * account with no pool. */
130
+ export function poolAllowed(allowed, pool) {
131
+ return !allowed || pool !== undefined && allowed.includes(pool);
132
+ }
133
+ /** `phren bridge accounts pool|role|allowed-pools …`: the lines to print. */
134
+ export async function accountPoolsCommand(args, projectStore, exists) {
135
+ const [command, ...rest] = args;
136
+ const known = (slug) => {
137
+ if (!slug || slug.startsWith("-"))
138
+ throw new Error(POOLS_USAGE);
139
+ if (!exists(slug))
140
+ throw new Error(`There is no Claude account "${slug}" on this computer.`);
141
+ return slug;
142
+ };
143
+ const describe = (slug, settings) => `${slug}: pool ${settings.pool ?? "none"}, role ${settings.role ?? "none"}.`;
144
+ if (command === "pool" && rest.length === 2) {
145
+ const slug = known(rest[0]);
146
+ return [describe(slug, await setAccountSettings(slug, { pool: rest[1] === "--clear" ? null : rest[1] }))];
147
+ }
148
+ if (command === "role" && rest.length === 2) {
149
+ const slug = known(rest[0]);
150
+ if (rest[1] !== "--clear" && !isAccountRole(rest[1]))
151
+ throw new Error(`A role is ${ACCOUNT_ROLES.join(", ")}, or --clear.`);
152
+ return [describe(slug, await setAccountSettings(slug, { role: rest[1] === "--clear" ? null : rest[1] }))];
153
+ }
154
+ if (command === "allowed-pools") {
155
+ const at = rest.indexOf("--project"), project = at === -1 ? undefined : rest[at + 1];
156
+ if (at !== -1 && (!project || project.startsWith("-")))
157
+ throw new Error(POOLS_USAGE);
158
+ const configPath = project && PROJECT.test(project) ? resolveProjectConfigPath(projectStore(), project) : null;
159
+ if (project && (!configPath || !existsSync(path.dirname(configPath))))
160
+ throw new Error(`There is no project "${project}" in the store.`);
161
+ const tags = at === -1 ? rest : rest.filter((_, i) => i !== at && i !== at + 1);
162
+ const where = project ? `Project ${project}` : "This computer";
163
+ const show = (pools) => `${where}: ${pools ? `allowed pools ${pools.join(", ")}.` : "any pool."}`;
164
+ if (!tags.length)
165
+ return [show(project ? projectAllowedPools(projectStore(), project) : computerAllowedPools())];
166
+ const pools = tags.length === 1 && tags[0] === "--clear" ? null : tags;
167
+ return [show(project ? setProjectAllowedPools(projectStore(), project, pools) : await setComputerAllowedPools(pools))];
168
+ }
169
+ throw new Error(POOLS_USAGE);
170
+ }
171
+ export const POOLS_USAGE = "Usage: phren bridge accounts pool <id> <tag>|--clear | role <id> helpers|last-resort|off|--clear | allowed-pools [--project <name>] [<tag>… | --clear]";
@@ -17,6 +17,12 @@ export { NEAR_LIMIT_LEFT };
17
17
  * one account. A window whose reset time has passed says `reset` and has no
18
18
  * percent, and a report older than STALE_AFTER_MS is flagged stale.
19
19
  *
20
+ * A Claude home with no readable login and nothing to show is a placeholder
21
+ * named only by its label ("work Team"). When that label names an account
22
+ * some computer reports (its own label, its email, or the email's name with
23
+ * its plan), the placeholder's computer joins that account's row instead of
24
+ * standing as a row of its own (`placeholderTarget`).
25
+ *
20
26
  * `nearLimit` is information: the owner often wants quota used before it
21
27
  * resets. Only `exhausted` (a window at 100% or refusing requests) rules an
22
28
  * account out.
@@ -107,6 +113,18 @@ export declare function accountIdentity(usage: AccountUsage, computer: string):
107
113
  export declare function settleWindow(window: UsageWindow, now: number): AccountWindow;
108
114
  /** Least room across an account's windows, undefined when none has a percent. */
109
115
  export declare function roomLeft(windows: readonly AccountWindow[]): number | undefined;
116
+ export interface NamedAccount {
117
+ labels: readonly string[];
118
+ email?: string;
119
+ plan?: string;
120
+ }
121
+ /**
122
+ * Which identified account a placeholder's label names, by index: one whose
123
+ * home carries the same label, else one whose email, email name, or email
124
+ * name and plan ("sam Team") the label spells. Two equally good matches name
125
+ * neither, and the provider's bare name ("Claude") names nothing.
126
+ */
127
+ export declare function placeholderTarget(label: string | undefined, accounts: readonly NamedAccount[], provider?: string): number | undefined;
110
128
  /** One row per account across every computer's report. */
111
129
  export declare function mergeAccountUsage(reports: readonly ComputerUsage[], now?: number): Pick<AccountUsageView, "accounts" | "noData">;
112
130
  export interface ReadAccountUsageOptions {