oneie 5.2.1 → 5.2.2

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/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oneie",
3
- "version": "5.2.1",
3
+ "version": "5.2.2",
4
4
  "description": "ONE agent CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "commander": "^12.0.0",
23
- "@oneie/sdk": "^0.16.2"
23
+ "@oneie/sdk": "^0.16.3"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@oneie/evals": "^0.2.0",
@@ -1,4 +1,4 @@
1
- export type Plan = 'starter' | 'free' | 'pro' | 'studio' | 'agency' | 'enterprise';
1
+ export type Plan = 'starter' | 'free' | 'pro' | 'agency' | 'enterprise';
2
2
  export interface AgencyConfig {
3
3
  slug: string;
4
4
  name: string;
@@ -60,7 +60,7 @@ export function readClient(path) {
60
60
  name: String(raw.name),
61
61
  slug: String(raw.slug),
62
62
  owner: raw.owner != null ? String(raw.owner) : undefined,
63
- plan: raw.plan ?? 'studio',
63
+ plan: raw.plan ?? 'free',
64
64
  markup_pct: raw.markup_pct != null ? Number(raw.markup_pct) : undefined,
65
65
  monthly_cap: raw.monthly_cap != null ? Number(raw.monthly_cap) : undefined,
66
66
  brand_lock: raw.brand_lock != null ? Boolean(raw.brand_lock) : undefined,
package/dist/src/group.js CHANGED
@@ -37,7 +37,7 @@ export function groupCmd() {
37
37
  .description('Bulk-provision Groups from a CSV file (idempotent — skips existing slugs)')
38
38
  .requiredOption('--csv <path>', 'CSV file with slug,name[,contacts] columns')
39
39
  .option('--segment <segment>', 'ICP segment tag written to each workspace_settings row', 'ICP-1')
40
- .option('--plan <plan>', 'Billing plan for each group', 'studio')
40
+ .option('--plan <plan>', 'Billing plan for each group', 'free')
41
41
  .option('--parent <slug>', 'Parent group slug (defaults to authenticated workspace)')
42
42
  .option('--batch-size <n>', 'Rows per HTTP batch', '50')
43
43
  .option('--api <url>', 'API base URL', DEFAULT_API)
@@ -0,0 +1,34 @@
1
+ import { type Asker } from '@oneie/sdk/tasks-bulk';
2
+ export interface AskFailure {
3
+ retryable: boolean;
4
+ httpStatus: number;
5
+ error: string;
6
+ }
7
+ /** EX_TEMPFAIL — the exit code a caller can branch on to retry. */
8
+ export declare const RETRYABLE_EXIT = 75;
9
+ export declare class AskError extends Error {
10
+ readonly retryable: boolean;
11
+ readonly httpStatus: number;
12
+ readonly receiver: string;
13
+ constructor(receiver: string, f: AskFailure);
14
+ }
15
+ export declare function isRetryableStatus(status: number): boolean;
16
+ export declare function classifyResponse(receiver: string, status: number, text: string): {
17
+ ok: true;
18
+ body: unknown;
19
+ } | {
20
+ ok: false;
21
+ failure: AskFailure;
22
+ };
23
+ /**
24
+ * The verdict to attach to a message, or none. The CLI keeps the last failure in one
25
+ * slot; a message that does not carry that failure's text is about something else,
26
+ * and a stale 502 must never turn an unrelated refusal into "retry me".
27
+ */
28
+ export declare function failureFor(msg: string, last: AskFailure | undefined): AskFailure | undefined;
29
+ export declare function exitCodeFor(f: AskFailure | undefined): number;
30
+ export declare function makeAsker(base: string, opts: {
31
+ fetchImpl?: typeof fetch;
32
+ headers: Record<string, string>;
33
+ onFailure?: (f: AskFailure) => void;
34
+ }): Asker;
@@ -0,0 +1,126 @@
1
+ import { unwrapAsk } from '@oneie/sdk/tasks-bulk';
2
+ import { askPath } from './api-path.js';
3
+ /** EX_TEMPFAIL — the exit code a caller can branch on to retry. */
4
+ export const RETRYABLE_EXIT = 75;
5
+ export class AskError extends Error {
6
+ retryable;
7
+ httpStatus;
8
+ receiver;
9
+ constructor(receiver, f) {
10
+ super(f.error);
11
+ this.name = 'AskError';
12
+ this.retryable = f.retryable;
13
+ this.httpStatus = f.httpStatus;
14
+ this.receiver = receiver;
15
+ }
16
+ }
17
+ export function isRetryableStatus(status) {
18
+ if (status === 0 || status === 408 || status === 429)
19
+ return true;
20
+ if (status === 502 || status === 503 || status === 504)
21
+ return true;
22
+ if (status >= 520 && status <= 529)
23
+ return true;
24
+ return false;
25
+ }
26
+ function extractTitleLabel(text) {
27
+ // Remove all HTML tags to get raw text
28
+ const noTags = text.replace(/<[^>]*>/g, '');
29
+ // Collapse whitespace
30
+ const collapsed = noTags.replace(/\s+/g, ' ').trim();
31
+ if (!collapsed)
32
+ return '';
33
+ // Try to extract title from original HTML
34
+ const titleMatch = text.match(/<title[^>]*>([^<]*)<\/title>/i);
35
+ if (titleMatch) {
36
+ const title = titleMatch[1].trim();
37
+ if (title)
38
+ return title.slice(0, 60);
39
+ }
40
+ return collapsed.slice(0, 60);
41
+ }
42
+ export function classifyResponse(receiver, status, text) {
43
+ let body;
44
+ let parseOk = false;
45
+ try {
46
+ body = text.length === 0 ? undefined : JSON.parse(text);
47
+ parseOk = true;
48
+ }
49
+ catch {
50
+ // not JSON
51
+ }
52
+ if (parseOk) {
53
+ // The door's own error envelope ({ ok:false, outcome, retryable, httpStatus },
54
+ // feat/collab-receivers 9623fe50b) carries `outcome` too — read its verdict
55
+ // before the pass-through below mistakes it for a receiver refusal.
56
+ const e = body;
57
+ if (e && typeof e === 'object' && e.ok === false && typeof e.retryable === 'boolean') {
58
+ const httpStatus = typeof e.httpStatus === 'number' ? e.httpStatus : status;
59
+ return { ok: false, failure: { retryable: e.retryable, httpStatus, error: `${receiver} → ${status} ${typeof e.error === 'string' ? e.error : 'error'}` } };
60
+ }
61
+ if (typeof body === 'object' && body !== null && 'outcome' in body) {
62
+ return { ok: true, body };
63
+ }
64
+ if (status >= 200 && status < 300) {
65
+ return { ok: true, body };
66
+ }
67
+ // failure: use body fields if present
68
+ const b = body;
69
+ const retryable = typeof b?.retryable === 'boolean' ? b.retryable : isRetryableStatus(status);
70
+ const httpStatus = typeof b?.httpStatus === 'number' ? b.httpStatus : status;
71
+ const errorMsg = typeof b?.error === 'string' ? b.error : 'error';
72
+ return {
73
+ ok: false,
74
+ failure: { retryable, httpStatus, error: `${receiver} → ${status} ${errorMsg}` },
75
+ };
76
+ }
77
+ // Non-JSON response
78
+ const label = extractTitleLabel(text);
79
+ const error = `${receiver} → ${status} non-JSON response (${label})`;
80
+ // Ensure no raw '<html>' appears
81
+ const cleanError = error.replace(/<html>/gi, '[html]');
82
+ return {
83
+ ok: false,
84
+ failure: { retryable: isRetryableStatus(status), httpStatus: status, error: cleanError },
85
+ };
86
+ }
87
+ /**
88
+ * The verdict to attach to a message, or none. The CLI keeps the last failure in one
89
+ * slot; a message that does not carry that failure's text is about something else,
90
+ * and a stale 502 must never turn an unrelated refusal into "retry me".
91
+ */
92
+ export function failureFor(msg, last) {
93
+ return last && msg.includes(last.error) ? last : undefined;
94
+ }
95
+ export function exitCodeFor(f) {
96
+ return f?.retryable ? RETRYABLE_EXIT : 1;
97
+ }
98
+ export function makeAsker(base, opts) {
99
+ return async (receiver, data) => {
100
+ const url = askPath(base, receiver);
101
+ let res;
102
+ try {
103
+ res = await (opts.fetchImpl ?? fetch)(url, {
104
+ method: 'POST',
105
+ headers: opts.headers,
106
+ body: JSON.stringify({ data }),
107
+ });
108
+ }
109
+ catch (e) {
110
+ const failure = {
111
+ retryable: true,
112
+ httpStatus: 0,
113
+ error: `${receiver} → network: ${e instanceof Error ? e.message : String(e)}`,
114
+ };
115
+ opts.onFailure?.(failure);
116
+ throw new AskError(receiver, failure);
117
+ }
118
+ const text = await res.text();
119
+ const classified = classifyResponse(receiver, res.status, text);
120
+ if (!classified.ok) {
121
+ opts.onFailure?.(classified.failure);
122
+ throw new AskError(receiver, classified.failure);
123
+ }
124
+ return unwrapAsk(receiver, classified.body);
125
+ };
126
+ }
@@ -0,0 +1,86 @@
1
+ import { type Asker, type BoardRes, type BulkRes } from '@oneie/sdk/tasks-bulk';
2
+ /** All valid Flow IDs */
3
+ export declare const FLOWS: readonly ["card", "page", "write", "secure", "decide", "operate", "recon", "rollup"];
4
+ export type FlowId = (typeof FLOWS)[number];
5
+ /** Row metadata used to derive a flow */
6
+ export interface FlowRow {
7
+ role?: string | null;
8
+ family?: string | null;
9
+ rung?: string | null;
10
+ }
11
+ /** Valid role values (labels and signals) */
12
+ export declare const ROLES: readonly ["leaf", "epic", "operate", "decision", "recon", "settle", "dupe"];
13
+ /** Valid rung values */
14
+ export declare const RUNGS: readonly ["trivial", "contained", "shaped", "irreversible"];
15
+ /** Valid family values */
16
+ export declare const FAMILIES: readonly ["copy", "doc", "chain", "security", "schema", "astro-page", "puck-block", "ts-lib", "react-component", "react-hook", "receiver", "interface", "worker", "d1", "workflow", "eval", "test-gate", "perf"];
17
+ /** Compute the FlowId from a FlowRow (exact spec port) */
18
+ export declare function flowOf(row: FlowRow): FlowId | null;
19
+ /** Format a flow line for notes */
20
+ export declare function flowNote(flow: FlowId): string;
21
+ /** Check if notes already contain a Flow: line */
22
+ export declare function hasFlowLine(notes: string | null | undefined): boolean;
23
+ /** Append a flow line to notes (never modify existing text) */
24
+ export declare function appendFlowNote(notes: string | null | undefined, flow: FlowId): string;
25
+ export type SignalSource = 'notes' | 'tags' | 'classified';
26
+ export interface BoardRowIn {
27
+ tid: string;
28
+ name?: string;
29
+ status?: string;
30
+ notes?: string | null;
31
+ tags?: string[];
32
+ }
33
+ export interface ClassifiedRow {
34
+ tid: string;
35
+ role?: string | null;
36
+ family?: string | null;
37
+ rung?: string | null;
38
+ flow?: string | null;
39
+ }
40
+ /** Read signals from notes, tags, and classified data in priority order */
41
+ export declare function readSignals(row: BoardRowIn, classified?: ClassifiedRow): {
42
+ signals: FlowRow;
43
+ sources: SignalSource[];
44
+ };
45
+ export interface FlowPlanEdit {
46
+ tid: string;
47
+ notes: string;
48
+ addTags: string[];
49
+ }
50
+ export interface FlowPlan {
51
+ counts: Record<FlowId, number>;
52
+ placed: number;
53
+ unplaced: string[];
54
+ alreadyTagged: string[];
55
+ mismatches: {
56
+ tid: string;
57
+ computed: FlowId | null;
58
+ file: string;
59
+ }[];
60
+ bySource: Record<SignalSource, number>;
61
+ edits: FlowPlanEdit[];
62
+ }
63
+ /** Build a plan for applying flow tags to board rows */
64
+ export declare function planFlowTags(rows: BoardRowIn[], classified?: ClassifiedRow[]): FlowPlan;
65
+ export interface RunFlowOpts {
66
+ workspace?: string;
67
+ tree?: boolean;
68
+ status?: string;
69
+ apply?: boolean;
70
+ maxAgeSec?: number;
71
+ now?: number;
72
+ board?: BoardRes;
73
+ fresh?: boolean;
74
+ }
75
+ export interface RunFlowResult {
76
+ ok: boolean;
77
+ dryRun: boolean;
78
+ plan?: FlowPlan;
79
+ total?: number;
80
+ asOf?: string;
81
+ truncated?: unknown;
82
+ applied?: BulkRes;
83
+ error?: string;
84
+ }
85
+ /** Orchestrate the flow tag operation: plan and optionally apply */
86
+ export declare function runFlow(ask: Asker, classified: ClassifiedRow[], opts: RunFlowOpts): Promise<RunFlowResult>;
@@ -0,0 +1,230 @@
1
+ import { boardAllWith, bulkAllWith, } from '@oneie/sdk/tasks-bulk';
2
+ // ── Constants ──────────────────────────────────────────────────────────
3
+ /** All valid Flow IDs */
4
+ export const FLOWS = ['card', 'page', 'write', 'secure', 'decide', 'operate', 'recon', 'rollup'];
5
+ /** Valid role values (labels and signals) */
6
+ export const ROLES = ['leaf', 'epic', 'operate', 'decision', 'recon', 'settle', 'dupe'];
7
+ /** Valid rung values */
8
+ export const RUNGS = ['trivial', 'contained', 'shaped', 'irreversible'];
9
+ /** Valid family values */
10
+ export const FAMILIES = [
11
+ 'copy', 'doc', 'chain', 'security', 'schema', 'astro-page', 'puck-block',
12
+ 'ts-lib', 'react-component', 'react-hook', 'receiver', 'interface', 'worker',
13
+ 'd1', 'workflow', 'eval', 'test-gate', 'perf',
14
+ ];
15
+ // ── Derivation helpers ─────────────────────────────────────────────────
16
+ /** Compute the FlowId from a FlowRow (exact spec port) */
17
+ export function flowOf(row) {
18
+ const { role, rung, family } = row;
19
+ if (role === 'decision')
20
+ return 'decide';
21
+ if (role === 'operate')
22
+ return 'operate';
23
+ if (role === 'recon')
24
+ return 'recon';
25
+ if (role === 'epic' || role === 'dupe' || role === 'settle')
26
+ return 'rollup';
27
+ if (role !== 'leaf')
28
+ return null;
29
+ if (!rung || !RUNGS.includes(rung))
30
+ return null;
31
+ if (family == null)
32
+ return null;
33
+ if (['copy', 'doc'].includes(family))
34
+ return 'write';
35
+ if (rung === 'irreversible' || ['chain', 'security', 'schema'].includes(family))
36
+ return 'secure';
37
+ if (['astro-page', 'puck-block'].includes(family))
38
+ return 'page';
39
+ if (['ts-lib', 'react-component', 'react-hook', 'receiver', 'interface', 'worker', 'd1', 'workflow', 'eval', 'test-gate', 'perf'].includes(family)) {
40
+ return rung === 'shaped' ? 'secure' : 'card';
41
+ }
42
+ return null;
43
+ }
44
+ /** Format a flow line for notes */
45
+ export function flowNote(flow) {
46
+ return `Flow: ${flow}`;
47
+ }
48
+ /** Check if notes already contain a Flow: line */
49
+ export function hasFlowLine(notes) {
50
+ return /^[ \t]*flow[ \t]*:/im.test(notes ?? '');
51
+ }
52
+ /** Append a flow line to notes (never modify existing text) */
53
+ export function appendFlowNote(notes, flow) {
54
+ const line = flowNote(flow);
55
+ if (!notes)
56
+ return line;
57
+ return notes.endsWith('\n') ? notes + line : notes + '\n' + line;
58
+ }
59
+ /** Read signals from notes, tags, and classified data in priority order */
60
+ export function readSignals(row, classified) {
61
+ const signals = {};
62
+ const fieldSources = {};
63
+ // Helper: try to extract a value from a notes line
64
+ function getNotesValue(label, valid) {
65
+ const re = new RegExp(`^[ \\t]*${label}[ \\t]*:[ \\t]*([a-z0-9-]+)[ \\t\\r]*$`, 'im');
66
+ const m = re.exec(row.notes ?? '');
67
+ if (m) {
68
+ const val = m[1].toLowerCase();
69
+ if (valid.includes(val))
70
+ return val;
71
+ }
72
+ return undefined;
73
+ }
74
+ // Helper: try to extract a value from tags
75
+ function getTagValue(prefix, valid) {
76
+ if (!row.tags)
77
+ return undefined;
78
+ for (const tag of row.tags) {
79
+ const re = new RegExp(`^${prefix}-([a-z0-9-]+)$`, 'i');
80
+ const m = re.exec(tag);
81
+ if (m) {
82
+ const val = m[1].toLowerCase();
83
+ if (valid.includes(val))
84
+ return val;
85
+ }
86
+ }
87
+ return undefined;
88
+ }
89
+ // Role
90
+ const roleFromNotes = getNotesValue('role', ROLES);
91
+ const roleFromTags = getTagValue('role', ROLES);
92
+ const roleFromClassified = classified && ROLES.includes(classified.role ?? '') ? classified.role : undefined;
93
+ const role = roleFromNotes ?? roleFromTags ?? roleFromClassified;
94
+ if (role !== undefined) {
95
+ signals.role = role;
96
+ if (roleFromNotes !== undefined)
97
+ fieldSources['role'] = 'notes';
98
+ else if (roleFromTags !== undefined)
99
+ fieldSources['role'] = 'tags';
100
+ else if (roleFromClassified !== undefined)
101
+ fieldSources['role'] = 'classified';
102
+ }
103
+ // Family
104
+ const familyFromNotes = getNotesValue('family', FAMILIES);
105
+ const familyFromTags = getTagValue('family', FAMILIES);
106
+ const familyFromClassified = classified && FAMILIES.includes(classified.family ?? '') ? classified.family : undefined;
107
+ const family = familyFromNotes ?? familyFromTags ?? familyFromClassified;
108
+ if (family !== undefined) {
109
+ signals.family = family;
110
+ if (familyFromNotes !== undefined)
111
+ fieldSources['family'] = 'notes';
112
+ else if (familyFromTags !== undefined)
113
+ fieldSources['family'] = 'tags';
114
+ else if (familyFromClassified !== undefined)
115
+ fieldSources['family'] = 'classified';
116
+ }
117
+ // Rung
118
+ const rungFromNotes = getNotesValue('rung', RUNGS);
119
+ const rungFromTags = getTagValue('rung', RUNGS);
120
+ const rungFromClassified = classified && RUNGS.includes(classified.rung ?? '') ? classified.rung : undefined;
121
+ const rung = rungFromNotes ?? rungFromTags ?? rungFromClassified;
122
+ if (rung !== undefined) {
123
+ signals.rung = rung;
124
+ if (rungFromNotes !== undefined)
125
+ fieldSources['rung'] = 'notes';
126
+ else if (rungFromTags !== undefined)
127
+ fieldSources['rung'] = 'tags';
128
+ else if (rungFromClassified !== undefined)
129
+ fieldSources['rung'] = 'classified';
130
+ }
131
+ // Build sources list preserving priority order and only those that contributed at least one field
132
+ const sources = [];
133
+ const usedSources = new Set(Object.values(fieldSources));
134
+ if (usedSources.has('notes'))
135
+ sources.push('notes');
136
+ if (usedSources.has('tags'))
137
+ sources.push('tags');
138
+ if (usedSources.has('classified'))
139
+ sources.push('classified');
140
+ return { signals, sources };
141
+ }
142
+ /** Build a plan for applying flow tags to board rows */
143
+ export function planFlowTags(rows, classified = []) {
144
+ const classifiedByTid = new Map();
145
+ for (const c of classified) {
146
+ if (!classifiedByTid.has(c.tid))
147
+ classifiedByTid.set(c.tid, c);
148
+ }
149
+ const seen = new Set();
150
+ const counts = { card: 0, page: 0, write: 0, secure: 0, decide: 0, operate: 0, recon: 0, rollup: 0 };
151
+ const unplaced = [];
152
+ const alreadyTagged = [];
153
+ const mismatches = [];
154
+ const bySource = { notes: 0, tags: 0, classified: 0 };
155
+ const edits = [];
156
+ let placed = 0;
157
+ for (const row of rows) {
158
+ if (seen.has(row.tid))
159
+ continue;
160
+ seen.add(row.tid);
161
+ if (hasFlowLine(row.notes)) {
162
+ alreadyTagged.push(row.tid);
163
+ continue;
164
+ }
165
+ const cls = classifiedByTid.get(row.tid);
166
+ const { signals, sources } = readSignals(row, cls);
167
+ const computed = flowOf(signals);
168
+ // Mismatch? Only when cls.flow is a non-empty string and differs from computed
169
+ if (cls?.flow && cls.flow !== computed) {
170
+ mismatches.push({ tid: row.tid, computed, file: cls.flow });
171
+ // continue removed – fall through to normal placement logic
172
+ }
173
+ if (computed === null) {
174
+ unplaced.push(row.tid);
175
+ continue;
176
+ }
177
+ for (const s of sources)
178
+ bySource[s]++;
179
+ const newNotes = appendFlowNote(row.notes, computed);
180
+ counts[computed]++;
181
+ placed++;
182
+ edits.push({ tid: row.tid, notes: newNotes, addTags: [`flow-${computed}`] });
183
+ }
184
+ return { counts, placed, unplaced, alreadyTagged, mismatches, bySource, edits };
185
+ }
186
+ /** Orchestrate the flow tag operation: plan and optionally apply */
187
+ export async function runFlow(ask, classified, opts) {
188
+ const board = opts.board ??
189
+ (await boardAllWith(ask, {
190
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
191
+ scope: opts.tree ? 'tree' : undefined,
192
+ status: opts.status ?? 'active',
193
+ include: ['notes'],
194
+ limit: 2000,
195
+ ...(opts.fresh ? { fresh: true } : {}),
196
+ }));
197
+ if (board.ok === false) {
198
+ return { ok: false, dryRun: !opts.apply, error: board.error ?? 'tasks:board failed' };
199
+ }
200
+ const plan = planFlowTags(board.tasks ?? [], classified);
201
+ if (!opts.apply) {
202
+ return { ok: true, dryRun: true, plan, total: board.total, asOf: board.asOf, truncated: board.truncated };
203
+ }
204
+ // Apply refusals
205
+ if (opts.board) {
206
+ return { ok: false, dryRun: false, plan, error: 'apply_needs_live_read' };
207
+ }
208
+ if (board.truncated?.rows !== undefined) {
209
+ return { ok: false, dryRun: false, plan, error: 'apply_refused_truncated' };
210
+ }
211
+ const maxAge = opts.maxAgeSec ?? 120;
212
+ if (!Number.isFinite(maxAge) || maxAge < 0) {
213
+ return { ok: false, dryRun: false, plan, error: 'apply_refused_bad_max_age' };
214
+ }
215
+ const asOf = board.asOf;
216
+ const t = asOf ? Date.parse(asOf) : NaN;
217
+ const age = (opts.now ?? Date.now()) - t;
218
+ if (!Number.isFinite(age) || age > maxAge * 1000) {
219
+ return { ok: false, dryRun: false, plan, error: 'apply_refused_stale' };
220
+ }
221
+ if (plan.edits.length === 0) {
222
+ return { ok: true, dryRun: false, plan, applied: undefined };
223
+ }
224
+ const applied = await bulkAllWith(ask, {
225
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
226
+ edits: plan.edits,
227
+ });
228
+ const ok = applied.ok !== false && (applied.failed ?? 0) === 0;
229
+ return { ok, dryRun: false, plan, total: board.total, asOf, truncated: board.truncated, applied };
230
+ }
@@ -0,0 +1,20 @@
1
+ import type { Seat } from './tasks-lens.js';
2
+ export type RosterResult = {
3
+ ok: true;
4
+ seats: Seat[];
5
+ source: string;
6
+ } | {
7
+ ok: false;
8
+ error: string;
9
+ };
10
+ /** Keep only well-formed seats; a role with no id is not addressable. */
11
+ export declare function toSeats(raw: unknown): Seat[];
12
+ /** The roster route answers on the web host only — never the gateway. */
13
+ export declare function webBase(base: string): string;
14
+ export declare function loadRoster(opts: {
15
+ base: string;
16
+ workspace?: string;
17
+ file?: string;
18
+ headers: Record<string, string>;
19
+ fetchImpl?: typeof fetch;
20
+ }): Promise<RosterResult>;
@@ -0,0 +1,79 @@
1
+ // roster — where a seat's stake is read from, for `brief --as` / `route` / `next`.
2
+ //
3
+ // The stake is the persona's `subscribes:` and its place in the chart is `reports_to:`.
4
+ // Both are served by ONE route, GET /api/agents/roster (one.ie/web — the same parse of
5
+ // `{slug}/agents/*.md` that world:sync-subscriptions turns into follows rows), so the
6
+ // lens and the router read one declaration. Three facts measured 2026-09-28 shape this:
7
+ // - the route lives on the web host only: api.one.ie answers it 404, so the base is
8
+ // rewritten to one.ie whatever --api says;
9
+ // - `source=workspace` needs authority over the group (403 for a key that lacks it),
10
+ // `source=fleet` needs only a world key — so we fall back to the bundled fleet and SAY
11
+ // so, because fleet is not what the router reads for a group with its own personas;
12
+ // - the shared gateway service key is not a world key (401 no_session on both), so
13
+ // `--roster <file>` (a saved response) is the door for a caller holding only that.
14
+ import { readFileSync } from 'node:fs';
15
+ /** Keep only well-formed seats; a role with no id is not addressable. */
16
+ export function toSeats(raw) {
17
+ const list = Array.isArray(raw) ? raw : raw && typeof raw === 'object' && Array.isArray(raw.roles) ? raw.roles : [];
18
+ const out = [];
19
+ for (const r of list) {
20
+ if (!r || typeof r.id !== 'string' || !r.id)
21
+ continue;
22
+ out.push({
23
+ id: r.id,
24
+ ...(typeof r.tier === 'string' ? { tier: r.tier } : {}),
25
+ reportsTo: typeof r.reportsTo === 'string' && r.reportsTo ? r.reportsTo : null,
26
+ subscribes: Array.isArray(r.subscribes) ? r.subscribes.filter((t) => typeof t === 'string') : [],
27
+ });
28
+ }
29
+ return out;
30
+ }
31
+ /** The roster route answers on the web host only — never the gateway. */
32
+ export function webBase(base) {
33
+ return new URL(base).hostname === 'api.one.ie' ? 'https://one.ie' : base;
34
+ }
35
+ export async function loadRoster(opts) {
36
+ if (opts.file) {
37
+ try {
38
+ const seats = toSeats(JSON.parse(readFileSync(opts.file, 'utf8')));
39
+ if (!seats.length)
40
+ return { ok: false, error: `--roster ${opts.file}: no roles in it (want {roles:[{id,reportsTo,subscribes}]})` };
41
+ return { ok: true, seats, source: `file ${opts.file}` };
42
+ }
43
+ catch (e) {
44
+ return { ok: false, error: `--roster: ${e instanceof Error ? e.message : String(e)}` };
45
+ }
46
+ }
47
+ if (!opts.workspace)
48
+ return { ok: false, error: 'reading a seat lens needs --workspace (whose roster?), --roster <file>, or --tags' };
49
+ const f = opts.fetchImpl ?? fetch;
50
+ const web = webBase(opts.base);
51
+ const url = (source) => `${web}/api/agents/roster?slug=${encodeURIComponent(opts.workspace)}${source ? `&source=${source}` : ''}`;
52
+ const refusals = [];
53
+ for (const source of [undefined, 'fleet']) {
54
+ let res;
55
+ try {
56
+ res = await f(url(source), { headers: opts.headers });
57
+ }
58
+ catch (e) {
59
+ refusals.push(`${source ?? 'workspace'}: ${e instanceof Error ? e.message : String(e)}`);
60
+ continue;
61
+ }
62
+ const text = await res.text();
63
+ if (!res.ok) {
64
+ refusals.push(`${source ?? 'workspace'}: ${res.status} ${text.slice(0, 80)}`);
65
+ continue;
66
+ }
67
+ try {
68
+ const seats = toSeats(JSON.parse(text));
69
+ if (seats.length) {
70
+ return { ok: true, seats, source: source === 'fleet' ? 'fleet (bundled agents — NOT this group\'s own personas; the router reads those)' : `workspace ${opts.workspace}` };
71
+ }
72
+ refusals.push(`${source ?? 'workspace'}: empty roster`);
73
+ }
74
+ catch {
75
+ refusals.push(`${source ?? 'workspace'}: ${res.status} not JSON`);
76
+ }
77
+ }
78
+ return { ok: false, error: `could not read the roster (${refusals.join('; ')}) — pass --roster <file> or --tags` };
79
+ }
@@ -0,0 +1,31 @@
1
+ import type { Row } from './tasks-digest.js';
2
+ /** One seat from the org roster: its id, tier, who it reports to, and its staked (subscribed) bare tags. */
3
+ export interface Seat {
4
+ id: string;
5
+ tier?: string;
6
+ reportsTo: string | null;
7
+ subscribes: string[];
8
+ }
9
+ /** A seat's lens: its bare tags (sorted, never '*'), itself + every seat below it (sorted), and all=true when it staked '*'. */
10
+ export interface Lens {
11
+ seat: string;
12
+ tags: string[];
13
+ seats: string[];
14
+ all: boolean;
15
+ }
16
+ export type LensResult = {
17
+ ok: true;
18
+ lens: Lens;
19
+ } | {
20
+ ok: false;
21
+ error: string;
22
+ };
23
+ /**
24
+ * BUILD LENS — A director owns a stake, not just its own assignments.
25
+ * Walks the reporting tree downward to find every direct/indirect report.
26
+ */
27
+ export declare function buildLens(roster: Seat[], seat: string): LensResult;
28
+ /**
29
+ * LENS ROWS — Keep rows that match the lens (tag stake or assignee descended from the seat).
30
+ */
31
+ export declare function lensRows(rows: Row[], lens: Lens): Row[];