@cohortapp/agent-sdk 2.18.37 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,263 @@
1
+ /**
2
+ * lib/org/first-run.mjs — what a seat does the first time it runs after
3
+ * Launch (Genesis WS6, M4).
4
+ *
5
+ * 1. ONBOARD — a read-only pass over the team's channels and docs:
6
+ * `messaging.channels`, `messaging.history` (rooms the seat has joined) and
7
+ * `files.list`. Every method is `sideEffecting:false` in the protocol (a
8
+ * test pins it). Nothing is posted, reacted to, marked read or created on
9
+ * the org; the digest is written to the seat's own disk
10
+ * (state/org/onboarding.json) for the brief to draw on.
11
+ * 2. BRIEF — one agent-created job (lib/scheduling/dynamic-jobs, the
12
+ * existing "remind X at 9am" path) that briefs the team lead at the next
13
+ * 09:00 in the seat's timezone. The dynamic-jobs cadence fires it through
14
+ * the normal send path, so the send-gate and the governance gate apply.
15
+ *
16
+ * Who is the team lead: the first HUMAN up the seat's reports-to chain
17
+ * (escalation-chain.mjs), falling back to a human `reportsTo`. ASSUMPTION
18
+ * (recorded in the WS6 report): the whoami DTO carries no explicit team-lead
19
+ * field, and the person a seat reports to is who its brief is for.
20
+ *
21
+ * The CHIEF OF STAFF does not brief proactively. Its first action is owned by
22
+ * the creator ("brief your Chief of Staff"), so it onboards and then WAITS for
23
+ * the creator's first DM. Recognised by slug `chief-of-staff`, or by a pending
24
+ * `firstAction` of kind `brief_chief_of_staff` naming this seat.
25
+ *
26
+ * Team mode: `off` → nothing at all (the pass is re-checked every beat, so the
27
+ * moment the team switches the seat on it runs); `assist` → the brief is a
28
+ * DRAFT for the lead; `run` / null → the brief is sent.
29
+ *
30
+ * Old server (no governance fields): nothing — `planFirstRun` returns `none`.
31
+ * The state file makes every step run once; a restart resumes where it left.
32
+ *
33
+ * @module lib/org/first-run
34
+ */
35
+
36
+ "use strict";
37
+
38
+ import { existsSync, readFileSync } from "node:fs";
39
+ import { join } from "node:path";
40
+
41
+ import { writeJsonAtomic } from "../fs-atomic.mjs";
42
+ import { CHIEF_OF_STAFF_SLUG } from "./genesis-contract.mjs";
43
+
44
+ export const FIRST_RUN_STATE_REL = join("state", "org", "first-run.json");
45
+ export const ONBOARDING_DIGEST_REL = join("state", "org", "onboarding.json");
46
+
47
+ /** The read-only methods the onboarding pass may call — and only these. */
48
+ export const ONBOARDING_METHODS = Object.freeze(["messaging.channels", "messaging.history", "files.list"]);
49
+
50
+ /** Bounds on the pass, so a large workspace costs a bounded number of reads. */
51
+ export const MAX_CHANNELS = 10;
52
+ export const HISTORY_LIMIT = 20;
53
+ export const FILES_LIMIT = 50;
54
+
55
+ /** The brief's local hour. */
56
+ export const BRIEF_HOUR = 9;
57
+
58
+ /** States that end the first run. */
59
+ const TERMINAL = new Set(["brief_scheduled", "waiting_for_creator"]);
60
+
61
+ /**
62
+ * Is this seat the Chief of Staff? Pure.
63
+ * @param {{slug?: string|null, memberId?: string|null, firstAction?: object|null}} o
64
+ */
65
+ export function isChiefOfStaff({ slug, memberId, firstAction }) {
66
+ if (slug && String(slug).toLowerCase() === CHIEF_OF_STAFF_SLUG) return true;
67
+ return !!(
68
+ firstAction &&
69
+ firstAction.kind === "brief_chief_of_staff" &&
70
+ memberId &&
71
+ firstAction.memberId === memberId
72
+ );
73
+ }
74
+
75
+ /**
76
+ * The next step. Pure.
77
+ *
78
+ * @param {object} o
79
+ * @param {{present:boolean, governance:object|null}} o.record loadGovernance()
80
+ * @param {string|null} [o.slug]
81
+ * @param {string|null} [o.memberId]
82
+ * @param {object|null} [o.state] the persisted first-run state
83
+ * @returns {{action: "none"|"wait"|"onboard"|"schedule_brief"|"wait_for_creator", reason: string}}
84
+ */
85
+ export function planFirstRun({ record, slug = null, memberId = null, state = null }) {
86
+ if (!record || !record.present || !record.governance) return { action: "none", reason: "no_governance" };
87
+ const s = state || {};
88
+ if (TERMINAL.has(s.status)) return { action: "none", reason: s.status };
89
+ const g = record.governance;
90
+ if (g.teamMode === "off") return { action: "wait", reason: "team_mode_off" };
91
+ if (!s.onboardedAt) return { action: "onboard", reason: "first_run" };
92
+ if (isChiefOfStaff({ slug, memberId, firstAction: g.firstAction })) {
93
+ return { action: "wait_for_creator", reason: "chief_of_staff" };
94
+ }
95
+ return { action: "schedule_brief", reason: "onboarded" };
96
+ }
97
+
98
+ /** Read the first-run state. Never throws. */
99
+ export function readFirstRunState(agentRoot) {
100
+ try {
101
+ const p = join(agentRoot, FIRST_RUN_STATE_REL);
102
+ if (!existsSync(p)) return null;
103
+ const v = JSON.parse(readFileSync(p, "utf8"));
104
+ return v && typeof v === "object" ? v : null;
105
+ } catch {
106
+ // An unreadable state file reads as "never run": the pass is read-only and
107
+ // the brief job is idempotent on `briefJobId`, so re-running is harmless.
108
+ return null;
109
+ }
110
+ }
111
+
112
+ function writeState(agentRoot, state) {
113
+ try {
114
+ writeJsonAtomic(join(agentRoot, FIRST_RUN_STATE_REL), state);
115
+ return true;
116
+ } catch (err) {
117
+ try { console.warn(`[first-run] could not persist state (${err && err.message ? err.message : err})`); } catch { /* never throw from logging */ }
118
+ return false;
119
+ }
120
+ }
121
+
122
+ /** @param {unknown} r */
123
+ const listOf = (r, key) => (Array.isArray(r) ? r : r && Array.isArray(r[key]) ? r[key] : []);
124
+
125
+ /**
126
+ * The read-only onboarding pass. Only ONBOARDING_METHODS are called.
127
+ * @param {(method: string, params: object) => Promise<object>} read
128
+ * @returns {Promise<{channels: object[], files: object[], errors: string[]}>}
129
+ */
130
+ export async function onboardingPass(read) {
131
+ const errors = [];
132
+ const guarded = async (method, params) => {
133
+ if (!ONBOARDING_METHODS.includes(method)) throw new Error(`onboarding may not call ${method}`);
134
+ try {
135
+ const f = await read(method, params);
136
+ if (f && f.ok) return f.result;
137
+ errors.push(`${method}: ${(f && f.error && f.error.code) || "failed"}`);
138
+ } catch (err) {
139
+ errors.push(`${method}: ${err && err.message ? err.message : err}`);
140
+ }
141
+ return null;
142
+ };
143
+
144
+ const chRes = await guarded("messaging.channels", {});
145
+ const rooms = listOf(chRes, "channels")
146
+ .filter((c) => c && c.id && c.joined !== false && String(c.kind || "").toUpperCase() !== "DM" && !c.archived)
147
+ .slice(0, MAX_CHANNELS);
148
+ const channels = [];
149
+ for (const c of rooms) {
150
+ const h = await guarded("messaging.history", { channelId: String(c.id), limit: HISTORY_LIMIT });
151
+ const msgs = listOf(h, "messages");
152
+ const last = msgs.reduce((acc, m) => {
153
+ const t = m && (m.createdAt || m.ts);
154
+ return t && (!acc || String(t) > acc) ? String(t) : acc;
155
+ }, null);
156
+ channels.push({
157
+ id: String(c.id),
158
+ name: c.name || c.slug || null,
159
+ topic: c.topic || null,
160
+ recentMessages: msgs.length,
161
+ lastActivityAt: last,
162
+ // A short, bounded excerpt so the brief can say what the room is about.
163
+ excerpt: msgs.slice(-5).map((m) => String((m && (m.body || m.text)) || "").slice(0, 200)).filter(Boolean),
164
+ });
165
+ }
166
+ const fRes = await guarded("files.list", { limit: FILES_LIMIT });
167
+ const files = listOf(fRes, "files")
168
+ .concat(listOf(fRes, "items"))
169
+ .filter((f) => f && (f.id || f.name))
170
+ .slice(0, FILES_LIMIT)
171
+ .map((f) => ({ id: f.id || null, name: f.name || f.title || null, kind: f.kind || null, updatedAt: f.updatedAt || null }));
172
+ return { channels, files, errors };
173
+ }
174
+
175
+ /**
176
+ * Run whatever step is due. Called from the presence beat; cheap once done.
177
+ *
178
+ * @param {object} o
179
+ * @param {string} o.agentRoot
180
+ * @param {{present:boolean, governance:object|null, memberId?:string|null, slug?:string|null}} o.record
181
+ * @param {{base:string, token:string, orgId?:string}} o.conn
182
+ * @param {string|null} [o.slug]
183
+ * @param {string|null} [o.leadMemberId] first human up the chain
184
+ * @param {string} [o.tz]
185
+ * @param {number} [o.now]
186
+ * @param {object} [deps] - { callImpl, createJobImpl, nextCronAfterImpl }
187
+ * @returns {Promise<{ok:boolean, action:string, reason:string, state?:object, error?:string}>}
188
+ */
189
+ export async function runFirstRun(o = {}, deps = {}) {
190
+ const now = Number.isFinite(o.now) ? o.now : Date.now();
191
+ const slug = o.slug || (o.record && o.record.slug) || null;
192
+ const memberId = (o.record && o.record.memberId) || null;
193
+ const state = readFirstRunState(o.agentRoot) || {};
194
+ const plan = planFirstRun({ record: o.record, slug, memberId, state });
195
+ if (plan.action === "none" || plan.action === "wait") return { ok: true, action: plan.action, reason: plan.reason };
196
+
197
+ const conn = o.conn || {};
198
+ if (!conn.base || !conn.token) return { ok: false, action: plan.action, reason: plan.reason, error: "no org credential" };
199
+
200
+ if (plan.action === "onboard") {
201
+ const call = deps.callImpl || (await import("./client.mjs")).call;
202
+ const digest = await onboardingPass((method, params) => call(method, params, conn));
203
+ try {
204
+ writeJsonAtomic(join(o.agentRoot, ONBOARDING_DIGEST_REL), { at: new Date(now).toISOString(), ...digest });
205
+ } catch (err) {
206
+ return { ok: false, action: plan.action, reason: plan.reason, error: `could not write the digest: ${err && err.message ? err.message : err}` };
207
+ }
208
+ const next = { ...state, status: "onboarded", onboardedAt: new Date(now).toISOString(), channels: digest.channels.length, files: digest.files.length, errors: digest.errors };
209
+ writeState(o.agentRoot, next);
210
+ // Fall through to the next step in the same beat.
211
+ return runFirstRun({ ...o, now }, deps);
212
+ }
213
+
214
+ if (plan.action === "wait_for_creator") {
215
+ const next = { ...state, status: "waiting_for_creator", decidedAt: new Date(now).toISOString() };
216
+ writeState(o.agentRoot, next);
217
+ return { ok: true, action: plan.action, reason: plan.reason, state: next };
218
+ }
219
+
220
+ // schedule_brief
221
+ const g = o.record.governance;
222
+ const lead =
223
+ o.leadMemberId ||
224
+ (g.reportsTo && g.reportsTo.kind === "human" ? g.reportsTo.memberId : null);
225
+ if (!lead) {
226
+ const next = { ...state, status: "onboarded", briefBlockedAt: new Date(now).toISOString(), briefBlocked: "no human up the reports-to chain yet" };
227
+ writeState(o.agentRoot, next);
228
+ return { ok: false, action: plan.action, reason: plan.reason, error: "no team lead resolved — retrying on a later beat", state: next };
229
+ }
230
+ const tz = o.tz || "UTC";
231
+ const dj = await import("../scheduling/dynamic-jobs.mjs");
232
+ const nextCron = deps.nextCronAfterImpl || dj.nextCronAfter;
233
+ const at = nextCron(`0 ${BRIEF_HOUR} * * *`, now, tz);
234
+ const draft = g.teamMode === "assist";
235
+ const createJob = deps.createJobImpl || dj.createJob;
236
+ let job;
237
+ try {
238
+ job = createJob({
239
+ agentRoot: o.agentRoot,
240
+ when: { at, tz },
241
+ action: "brief",
242
+ tz,
243
+ now,
244
+ payload: {
245
+ kind: "genesis_first_brief",
246
+ recipientMemberId: lead,
247
+ deliver: draft ? "draft" : "send",
248
+ digest: ONBOARDING_DIGEST_REL,
249
+ instruction:
250
+ (draft
251
+ ? "Draft (do not send) a first brief for your team lead to review: "
252
+ : "DM your team lead a short first brief: ") +
253
+ "what you read across the team's channels and docs (state/org/onboarding.json), what you understand your remit to be, " +
254
+ "and the two or three things you propose to do first, within your decision rights.",
255
+ },
256
+ });
257
+ } catch (err) {
258
+ return { ok: false, action: plan.action, reason: plan.reason, error: `could not schedule the brief: ${err && err.message ? err.message : err}` };
259
+ }
260
+ const next = { ...state, status: "brief_scheduled", briefJobId: job && job.id, briefAt: new Date(at).toISOString(), lead, deliver: draft ? "draft" : "send" };
261
+ writeState(o.agentRoot, next);
262
+ return { ok: true, action: plan.action, reason: plan.reason, state: next };
263
+ }
@@ -0,0 +1,271 @@
1
+ /**
2
+ * lib/org/genesis-contract.mjs — the SDK half of the Genesis redesign's shared
3
+ * contract (WS0, contract version 2).
4
+ *
5
+ * The definition lives in cohort: `src/lib/genesis-contract/contract.ts` (types,
6
+ * unions, defaults, pure rules) and `docs/genesis-redesign/CONTRACT.md`. This
7
+ * file is a hand mirror of the parts the runtime reads. The two repos cannot
8
+ * import each other, so `genesis-contract.test.mjs` regex-reads cohort's source
9
+ * when a checkout sits beside this one and fails on any drift in the enum
10
+ * tuples. The cross-repo pin is the byte-identical fixture
11
+ * `test/fixtures/genesis-contract/whoami-agent.v2.json`.
12
+ *
13
+ * Rules this module keeps:
14
+ * - PURE. No imports, no clock, no env, no I/O. `now` is a parameter.
15
+ * - ADDITIVE. Every governance field is optional on the wire. A server from
16
+ * before the redesign omits them, and {@link readAgentGovernance} returns a
17
+ * named default for each one. It never throws. An unknown enum value (a
18
+ * NEWER server) reads as the default, never as an error, because maestro
19
+ * reads inbound DTOs duck-typed and passes unknown fields through.
20
+ * - Nothing invented. `approvalMode` absent reads as `null` (unknown), not as
21
+ * a guessed mode. Enforcement (WS6) decides what unknown means.
22
+ *
23
+ * Nothing in the runtime consumes this yet. WS6 wires it.
24
+ *
25
+ * @module lib/org/genesis-contract
26
+ */
27
+
28
+ "use strict";
29
+
30
+ /** cohort `GENESIS_CONTRACT_VERSION`. */
31
+ export const GENESIS_CONTRACT_VERSION = 2;
32
+
33
+ /** @param {readonly string[]} tuple @param {unknown} v */
34
+ const member = (tuple, v) => typeof v === "string" && tuple.includes(v);
35
+
36
+ // ── Scenario ─────────────────────────────────────────────────────────────────
37
+
38
+ export const SCENARIOS = Object.freeze(["existing", "venture", "assets"]);
39
+
40
+ /** An old draft or payload with no scenario opens on the venture path. */
41
+ export const DEFAULT_SCENARIO = "venture";
42
+
43
+ /** @param {unknown} v */
44
+ export function isScenario(v) {
45
+ return member(SCENARIOS, v);
46
+ }
47
+
48
+ /** @param {unknown} v @returns {string} */
49
+ export function scenarioOf(v) {
50
+ return isScenario(v) ? /** @type {string} */ (v) : DEFAULT_SCENARIO;
51
+ }
52
+
53
+ // ── Team participation ───────────────────────────────────────────────────────
54
+
55
+ export const TEAM_MODES = Object.freeze(["off", "assist", "run"]);
56
+
57
+ /** @param {unknown} v */
58
+ export function isTeamMode(v) {
59
+ return member(TEAM_MODES, v);
60
+ }
61
+
62
+ // ── Approval mode ────────────────────────────────────────────────────────────
63
+
64
+ export const APPROVAL_MODES = Object.freeze(["all_first_week", "external_only", "none"]);
65
+
66
+ /** @param {unknown} v */
67
+ export function isApprovalMode(v) {
68
+ return member(APPROVAL_MODES, v);
69
+ }
70
+
71
+ /** The wizard's recommended default (A5). Not what an absent DTO field reads as. */
72
+ export const DEFAULT_APPROVAL_MODE = "all_first_week";
73
+
74
+ /** `all_first_week` relaxes to this on day {@link APPROVAL_RELAX_DAYS}. */
75
+ export const RELAXED_APPROVAL_MODE = "external_only";
76
+ export const APPROVAL_RELAX_DAYS = 7;
77
+
78
+ /**
79
+ * The mode in force for one agent at `now`: the agent's override if set, else
80
+ * the workspace mode. `all_first_week` past its relax instant reads as the
81
+ * relaxed mode even before the server's job has rewritten the row, so a late
82
+ * job can never make an agent stricter than the founder was promised.
83
+ * Mirrors cohort `effectiveApprovalMode`.
84
+ *
85
+ * @param {{ workspace: string, override?: string|null, relaxAt?: number|null, now: number }} args
86
+ * @returns {string}
87
+ */
88
+ export function effectiveApprovalMode({ workspace, override, relaxAt, now }) {
89
+ const mode = override ?? workspace;
90
+ if (mode === "all_first_week" && relaxAt != null && now >= relaxAt) {
91
+ return RELAXED_APPROVAL_MODE;
92
+ }
93
+ return mode;
94
+ }
95
+
96
+ /** @param {number} committedAt epoch ms @returns {number} epoch ms */
97
+ export function approvalRelaxAt(committedAt) {
98
+ return committedAt + APPROVAL_RELAX_DAYS * 86_400_000;
99
+ }
100
+
101
+ // ── Plan tiers ───────────────────────────────────────────────────────────────
102
+
103
+ export const PLAN_TIERS = Object.freeze(["light", "pro", "max"]);
104
+
105
+ /** @param {unknown} v */
106
+ export function isPlanTier(v) {
107
+ return member(PLAN_TIERS, v);
108
+ }
109
+
110
+ export const DEFAULT_PLAN_TIER = "light";
111
+
112
+ // ── First action ─────────────────────────────────────────────────────────────
113
+
114
+ export const FIRST_ACTION_KINDS = Object.freeze([
115
+ "brief_chief_of_staff", // path A
116
+ "sign_off_build_plan", // path 2a
117
+ "review_drafted_pr", // path 2b
118
+ ]);
119
+
120
+ /** @param {unknown} v */
121
+ export function isFirstActionKind(v) {
122
+ return member(FIRST_ACTION_KINDS, v);
123
+ }
124
+
125
+ export const CHIEF_OF_STAFF_SLUG = "chief-of-staff";
126
+
127
+ // ── Reports-to chain ─────────────────────────────────────────────────────────
128
+
129
+ /**
130
+ * Read one manager edge. cohort passes a `ReadonlyMap`; a plain object (JSON
131
+ * off the wire) works too.
132
+ * @param {Map<string, string|null>|Record<string, string|null>} edges
133
+ * @param {string} id
134
+ */
135
+ function managerOf(edges, id) {
136
+ if (!edges) return null;
137
+ if (typeof edges.get === "function") return edges.get(id) ?? null;
138
+ return Object.prototype.hasOwnProperty.call(edges, id) ? edges[id] ?? null : null;
139
+ }
140
+
141
+ /**
142
+ * Walk up from `memberId` to the first HUMAN (M3: escalations travel up the
143
+ * chain until a person has them). Returns null when the chain ends, or loops,
144
+ * without one. Callers then fall back to the workspace approver.
145
+ * Mirrors cohort `firstHumanUpChain`.
146
+ *
147
+ * @param {{ memberId: string, edges: Map<string, string|null>|Record<string, string|null>, isHuman: (memberId: string) => boolean }} args
148
+ * @returns {string|null}
149
+ */
150
+ export function firstHumanUpChain({ memberId, edges, isHuman }) {
151
+ const seen = new Set([memberId]);
152
+ let cur = managerOf(edges, memberId);
153
+ while (cur != null && !seen.has(cur)) {
154
+ if (isHuman(cur)) return cur;
155
+ seen.add(cur);
156
+ cur = managerOf(edges, cur);
157
+ }
158
+ return null;
159
+ }
160
+
161
+ // ── Decision rights ──────────────────────────────────────────────────────────
162
+
163
+ /**
164
+ * The Forbidden list an agent actually runs under: its own clauses plus every
165
+ * workspace never, inherited and read-only. De-duplicated case-insensitively,
166
+ * with the workspace rules first so the inherited ones read as the floor.
167
+ * Mirrors cohort `effectiveForbidden`.
168
+ *
169
+ * @param {readonly string[]} own
170
+ * @param {readonly string[]} workspaceNevers
171
+ * @returns {string[]}
172
+ */
173
+ export function effectiveForbidden(own, workspaceNevers) {
174
+ const out = [];
175
+ const seen = new Set();
176
+ for (const c of [...(workspaceNevers || []), ...(own || [])]) {
177
+ if (typeof c !== "string") continue;
178
+ const t = c.trim();
179
+ const k = t.toLowerCase();
180
+ if (!t || seen.has(k)) continue;
181
+ seen.add(k);
182
+ out.push(t);
183
+ }
184
+ return out;
185
+ }
186
+
187
+ // ── The agent-facing projection (whoami / member DTO) ────────────────────────
188
+
189
+ /** @param {unknown} v @returns {string[]} */
190
+ const strings = (v) => (Array.isArray(v) ? v.filter((s) => typeof s === "string") : []);
191
+
192
+ /** @param {unknown} v @returns {number|null} */
193
+ const micros = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null);
194
+
195
+ /** @param {unknown} v @returns {v is Record<string, unknown>} */
196
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
197
+
198
+ /**
199
+ * @typedef {object} AgentGovernance
200
+ * @property {string} planTier "light" | "pro" | "max"
201
+ * @property {{kind: "human"|"agent", memberId: string}|null} reportsTo
202
+ * @property {string|null} approvalMode EFFECTIVE mode as the server computed it; null = unknown
203
+ * @property {{autonomous: string[], escalates: string[], forbidden: string[]}} decisionRights
204
+ * @property {string[]} workspaceNevers
205
+ * @property {{monthlyMicros: number|null, singleActionMicros: number|null}} spendCaps
206
+ * @property {string|null} teamMode "off" | "assist" | "run"
207
+ * @property {{state: "pending", kind: string, memberId: string}|{state: "done", kind: string, memberId: string, doneAt: string}|null} firstAction
208
+ */
209
+
210
+ /**
211
+ * Extract the `AgentGovernanceDTO` fields (cohort `contract.ts`) from a whoami
212
+ * response or a member DTO. Accepts the bare DTO or one wrapped under
213
+ * `member` / `profile` / `result` / `data`, the same wrappers
214
+ * `client.mjs#unwrapProfile` accepts.
215
+ *
216
+ * Any field that is absent (an old server) or malformed reads as its default:
217
+ * planTier "light", reportsTo null, approvalMode null, empty decision rights,
218
+ * no nevers, null caps, teamMode null, firstAction null. It never throws.
219
+ *
220
+ * @param {unknown} input
221
+ * @returns {AgentGovernance}
222
+ */
223
+ export function readAgentGovernance(input) {
224
+ let m = isObj(input) ? input : {};
225
+ if (!("planTier" in m) && !("slug" in m)) {
226
+ for (const key of ["member", "profile", "result", "data"]) {
227
+ if (isObj(m[key])) { m = m[key]; break; }
228
+ }
229
+ }
230
+
231
+ const rt = m.reportsTo;
232
+ const reportsTo =
233
+ isObj(rt) && (rt.kind === "human" || rt.kind === "agent") && typeof rt.memberId === "string" && rt.memberId
234
+ ? { kind: rt.kind, memberId: rt.memberId }
235
+ : null;
236
+
237
+ const dr = isObj(m.decisionRights) ? m.decisionRights : {};
238
+ const caps = isObj(m.spendCaps) ? m.spendCaps : {};
239
+
240
+ const fa = m.firstAction;
241
+ let firstAction = null;
242
+ if (isObj(fa) && isFirstActionKind(fa.kind) && typeof fa.memberId === "string" && fa.memberId) {
243
+ if (fa.state === "pending") firstAction = { state: "pending", kind: fa.kind, memberId: fa.memberId };
244
+ else if (fa.state === "done" && typeof fa.doneAt === "string") {
245
+ firstAction = { state: "done", kind: fa.kind, memberId: fa.memberId, doneAt: fa.doneAt };
246
+ }
247
+ }
248
+
249
+ return {
250
+ planTier: isPlanTier(m.planTier) ? /** @type {string} */ (m.planTier) : DEFAULT_PLAN_TIER,
251
+ reportsTo,
252
+ approvalMode: isApprovalMode(m.approvalMode) ? /** @type {string} */ (m.approvalMode) : null,
253
+ decisionRights: {
254
+ autonomous: strings(dr.autonomous),
255
+ escalates: strings(dr.escalates),
256
+ forbidden: strings(dr.forbidden),
257
+ },
258
+ workspaceNevers: strings(m.workspaceNevers),
259
+ spendCaps: {
260
+ monthlyMicros: micros(caps.monthlyMicros),
261
+ singleActionMicros: micros(caps.singleActionMicros),
262
+ },
263
+ teamMode: isTeamMode(m.teamMode) ? /** @type {string} */ (m.teamMode) : null,
264
+ firstAction,
265
+ // Additive (cohort WS2b): the agent's guardian and team lead, both HUMAN
266
+ // memberIds. Absent on an older server → null, and callers keep their
267
+ // reports-to fallback.
268
+ guardianMemberId: typeof m.guardianMemberId === "string" && m.guardianMemberId ? m.guardianMemberId : null,
269
+ teamLeadMemberId: typeof m.teamLeadMemberId === "string" && m.teamLeadMemberId ? m.teamLeadMemberId : null,
270
+ };
271
+ }