@installagent/sdk 0.11.0 → 0.13.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,118 @@
1
+ import { type ManifestBuild } from "./portal-sync-builds.js";
2
+ /** Read by `ia build-estimate`. Lives in 1Password (team-techs); `ia env fill` writes it. */
3
+ export declare const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
4
+ /** The model for the estimate: the one Agent Zero uses for structured extraction. */
5
+ export declare const BUILD_ESTIMATE_MODEL = "gemini-3.8-flash";
6
+ /** The spec text sent per build is cut to this many characters. */
7
+ export declare const SPEC_CHAR_CAP = 24000;
8
+ /** The basis line is cut to this many characters. */
9
+ export declare const BASIS_CHAR_CAP = 300;
10
+ export type HoursRange = [number, number];
11
+ export interface BuildEstimateOptions {
12
+ /** The client repo, or a directory inside it. Default: the current directory. */
13
+ repoDir?: string;
14
+ /** One build slug. Default: every active row with no estimate. */
15
+ build?: string;
16
+ /** Re-estimate a row that already has `est_hours`. */
17
+ force?: boolean;
18
+ /** The spec file to read for `build` (relative to the repo), instead of the lookup. */
19
+ spec?: string;
20
+ /** Write `est_hours` into CLIENT.md for every row estimated. Default false. */
21
+ write?: boolean;
22
+ /** Defaults to $GEMINI_API_KEY. */
23
+ apiKey?: string;
24
+ model?: string;
25
+ fetchImpl?: typeof fetch;
26
+ }
27
+ export type BuildEstimateOutcome =
28
+ /** The model answered with a valid range. */
29
+ "estimated"
30
+ /** Not estimated on purpose (it already has one, without --force). */
31
+ | "skipped"
32
+ /** No estimate: no spec, a failed call, or a bad reply. Never a guessed number. */
33
+ | "error";
34
+ export interface BuildEstimateRow {
35
+ build: string;
36
+ name: string;
37
+ outcome: BuildEstimateOutcome;
38
+ /** The estimate already in CLIENT.md, if any. */
39
+ current: HoursRange | null;
40
+ low?: number;
41
+ high?: number;
42
+ /** One sentence naming the main work, with any amount removed. */
43
+ basis?: string;
44
+ /** Where the spec text came from, e.g. "docs/08-intake-tech-spec.md". */
45
+ spec?: string;
46
+ /** Why it was skipped or failed. */
47
+ reason?: string;
48
+ }
49
+ export interface BuildEstimateResult {
50
+ repoDir: string;
51
+ model: string;
52
+ rows: BuildEstimateRow[];
53
+ /** True when CLIENT.md was changed. */
54
+ written: boolean;
55
+ /** The builds whose `est_hours` was written. */
56
+ writtenBuilds: string[];
57
+ }
58
+ /** Removes email addresses and phone numbers. */
59
+ export declare function redactContactDetails(text: string): string;
60
+ /** Removes money amounts: the CLI never prints dollars. */
61
+ export declare function removeMoney(text: string): string;
62
+ /** `docs/<NN->?<build>(-tech)?-spec.md` → true for this build. */
63
+ export declare function isBuildSpecFile(fileName: string, build: string): boolean;
64
+ /**
65
+ * The section of a tech spec that names the build (its slug, name or
66
+ * workflow id): the first heading that names it, else the first section whose
67
+ * own text does. Null when none does.
68
+ */
69
+ export declare function specSectionFor(markdown: string, row: Pick<ManifestBuild, "build" | "name" | "workflowId">): {
70
+ heading: string;
71
+ text: string;
72
+ } | null;
73
+ /** An n8n export → its node count and node types, never anything else. */
74
+ export declare function workflowNodeSummary(workflow: unknown): {
75
+ nodeCount: number;
76
+ nodeTypes: Record<string, number>;
77
+ } | null;
78
+ export interface EstimatePromptInput {
79
+ type: "agent" | "app";
80
+ name: string;
81
+ description: string;
82
+ spec: {
83
+ source: string;
84
+ text: string;
85
+ };
86
+ workflow: {
87
+ nodeCount: number;
88
+ nodeTypes: Record<string, number>;
89
+ } | null;
90
+ }
91
+ /** The one prompt per build. Contact details are removed from every text field. */
92
+ export declare function buildEstimatePrompt(input: EstimatePromptInput): string;
93
+ /**
94
+ * The model's reply → a range and a basis, or an error. A reply that is not
95
+ * exactly whole hours with low <= high is refused: never a guessed number.
96
+ */
97
+ export declare function parseEstimateReply(raw: string): {
98
+ ok: true;
99
+ low: number;
100
+ high: number;
101
+ basis: string;
102
+ } | {
103
+ ok: false;
104
+ error: string;
105
+ };
106
+ /**
107
+ * CLIENT.md with `est_hours` set on the given rows and nothing else changed:
108
+ * the block keeps its layout, and the result is re-parsed to prove that only
109
+ * those rows' `estHours` moved. Throws rather than write anything else.
110
+ */
111
+ export declare function setEstHours(clientMd: string, updates: Map<string, HoursRange>): string;
112
+ /**
113
+ * Estimates the market hours of a client repo's builds: one Gemini call per
114
+ * build, a range of whole hours each. With `write`, sets `est_hours` on the
115
+ * estimated rows of CLIENT.md (only that field moves); the technician commits
116
+ * it. Never knows the rate, never prints a dollar figure.
117
+ */
118
+ export declare function buildEstimate(options?: BuildEstimateOptions): Promise<BuildEstimateResult>;
@@ -0,0 +1,480 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
4
+ import { BUILDS_MANIFEST_END, BUILDS_MANIFEST_START, parseBuildsManifest, } from "./portal-sync-builds.js";
5
+ // ─── `ia build-estimate`: market hours per build, for the portal's cost range ──
6
+ //
7
+ // One AI call per build answers: how many hours would a typical US freelance
8
+ // automation developer bill to deliver this, spec to go-live? The answer is a
9
+ // range of whole hours. `--write` puts it in the build's `## Builds` row of
10
+ // CLIENT.md as `"est_hours": [low, high]`; `ia portal sync-builds` carries it
11
+ // to the portal, which multiplies it by the one market rate set in portal
12
+ // admin when it renders the card.
13
+ //
14
+ // Money rule: this module never knows the rate and never prints a dollar
15
+ // figure. It reads only hours, and it removes any amount from the model's
16
+ // one-line basis before it returns it.
17
+ //
18
+ // What leaves the machine (one Gemini request per build): the row's type,
19
+ // name and description; the build's spec text, capped, with email addresses
20
+ // and phone numbers removed; and for an agent, the node count and node types
21
+ // of its workflow export. Never node parameters, credentials, or CLIENT.md.
22
+ /** Read by `ia build-estimate`. Lives in 1Password (team-techs); `ia env fill` writes it. */
23
+ export const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
24
+ /** The model for the estimate: the one Agent Zero uses for structured extraction. */
25
+ export const BUILD_ESTIMATE_MODEL = "gemini-3.8-flash";
26
+ /** The spec text sent per build is cut to this many characters. */
27
+ export const SPEC_CHAR_CAP = 24_000;
28
+ /** The basis line is cut to this many characters. */
29
+ export const BASIS_CHAR_CAP = 300;
30
+ const GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta";
31
+ const GEMINI_TIMEOUT_MS = 120_000;
32
+ /** Gemini's structured-output schema for one estimate. */
33
+ const ESTIMATE_SCHEMA = {
34
+ type: "OBJECT",
35
+ properties: {
36
+ low: { type: "INTEGER" },
37
+ high: { type: "INTEGER" },
38
+ basis: { type: "STRING" },
39
+ },
40
+ required: ["low", "high", "basis"],
41
+ propertyOrdering: ["low", "high", "basis"],
42
+ };
43
+ // ─── Pure helpers (exported for tests) ──────────────────────────────────────
44
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
45
+ // A North American or international phone number, as written in docs:
46
+ // +1 (555) 010-0199, 555.010.0199, +44 20 7946 0958. Not part of a longer token.
47
+ const PHONE = /(?<![\w+])(?:\+\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)|\d{2,4})[\s.-]?\d{3,4}[\s.-]?\d{3,4}(?![\w])/g;
48
+ /** Removes email addresses and phone numbers. */
49
+ export function redactContactDetails(text) {
50
+ return text.replace(EMAIL, "[email]").replace(PHONE, (match) => {
51
+ // A run of digits with no separator and fewer than 10 digits is a number, not a phone.
52
+ const digits = match.replace(/\D/g, "");
53
+ return digits.length >= 10 ? "[phone]" : match;
54
+ });
55
+ }
56
+ // 12,000 · 4.5 · 8k · 1.2 M
57
+ const AMOUNT = String.raw `\d[\d,]*(?:\.\d+)?(?:\s?[kKmM]\b)?`;
58
+ // 8k–12k · 8,000 to $12,000
59
+ const AMOUNT_RANGE = String.raw `${AMOUNT}(?:\s?(?:-|–|to)\s?\$?${AMOUNT})?`;
60
+ const MONEY = [
61
+ // $12,000 · US$90 · $90/h · $8k–12k
62
+ new RegExp(String.raw `(?:US)?\$\s?${AMOUNT_RANGE}(?:\s?(?:\/|per\s)\s?(?:h|hr|hour)\b)?`, "g"),
63
+ // 12,000 USD · 8k–12k USD · 90 dollars
64
+ new RegExp(String.raw `\b${AMOUNT_RANGE}\s?(?:USD|dollars?)\b`, "gi"),
65
+ ];
66
+ /** Removes money amounts: the CLI never prints dollars. */
67
+ export function removeMoney(text) {
68
+ return MONEY.reduce((out, pattern) => out.replace(pattern, "[amount removed]"), text);
69
+ }
70
+ /** `docs/<NN->?<build>(-tech)?-spec.md` → true for this build. */
71
+ export function isBuildSpecFile(fileName, build) {
72
+ if (!fileName.endsWith("-spec.md"))
73
+ return false;
74
+ const stem = fileName.replace(/^\d+-/, "").replace(/(?:-tech)?-spec\.md$/, "");
75
+ return stem === build;
76
+ }
77
+ function markdownSections(markdown) {
78
+ const lines = markdown.replace(/\r\n/g, "\n").split("\n");
79
+ const headings = [];
80
+ let inFence = false;
81
+ lines.forEach((line, index) => {
82
+ if (/^\s*```/.test(line))
83
+ inFence = !inFence;
84
+ const match = inFence ? null : /^(#{1,6})\s+(.*)$/.exec(line);
85
+ if (match?.[1] && match[2] !== undefined) {
86
+ headings.push({ heading: match[2].trim(), level: match[1].length, line: index });
87
+ }
88
+ });
89
+ return headings.map((heading, i) => {
90
+ const later = headings.slice(i + 1);
91
+ const sectionEnd = later.find((next) => next.level <= heading.level)?.line ?? lines.length;
92
+ const ownEnd = later[0]?.line ?? lines.length;
93
+ return {
94
+ heading: heading.heading,
95
+ level: heading.level,
96
+ text: lines.slice(heading.line, sectionEnd).join("\n"),
97
+ ownText: lines.slice(heading.line, ownEnd).join("\n"),
98
+ };
99
+ });
100
+ }
101
+ /**
102
+ * The section of a tech spec that names the build (its slug, name or
103
+ * workflow id): the first heading that names it, else the first section whose
104
+ * own text does. Null when none does.
105
+ */
106
+ export function specSectionFor(markdown, row) {
107
+ const needles = [row.build, row.name, row.workflowId]
108
+ .filter((value) => Boolean(value))
109
+ .map((value) => value.toLowerCase());
110
+ const names = (text) => needles.some((needle) => text.toLowerCase().includes(needle));
111
+ // Skip the document title (level 1): it holds everything.
112
+ const sections = markdownSections(markdown).filter((section) => section.level > 1);
113
+ const found = sections.find((section) => names(section.heading)) ??
114
+ sections.find((section) => names(section.ownText));
115
+ return found ? { heading: found.heading, text: found.text } : null;
116
+ }
117
+ function cap(text) {
118
+ return text.length > SPEC_CHAR_CAP ? `${text.slice(0, SPEC_CHAR_CAP)}\n[…cut]` : text;
119
+ }
120
+ /** An n8n export → its node count and node types, never anything else. */
121
+ export function workflowNodeSummary(workflow) {
122
+ if (typeof workflow !== "object" || workflow === null)
123
+ return null;
124
+ const nodes = workflow.nodes;
125
+ if (!Array.isArray(nodes))
126
+ return null;
127
+ const nodeTypes = {};
128
+ for (const node of nodes) {
129
+ const type = typeof node === "object" &&
130
+ node !== null &&
131
+ typeof node.type === "string"
132
+ ? node.type
133
+ : "unknown";
134
+ nodeTypes[type] = (nodeTypes[type] ?? 0) + 1;
135
+ }
136
+ return { nodeCount: nodes.length, nodeTypes };
137
+ }
138
+ /** The one prompt per build. Contact details are removed from every text field. */
139
+ export function buildEstimatePrompt(input) {
140
+ const nodeTypes = input.workflow
141
+ ? Object.entries(input.workflow.nodeTypes)
142
+ .sort(([a], [b]) => a.localeCompare(b))
143
+ .map(([type, count]) => (count > 1 ? `${type} ×${count}` : type))
144
+ .join(", ")
145
+ : "";
146
+ return [
147
+ "You estimate the effort to deliver a software build.",
148
+ "",
149
+ "Question: how many hours would a typical US freelance automation developer bill to deliver",
150
+ "the build below, from spec to go-live? Count design, build, test, deploy and handoff.",
151
+ "Do not count ongoing support or maintenance. Do not count the client's own time.",
152
+ "",
153
+ "Answer with JSON only, in this shape:",
154
+ '{"low": <whole hours>, "high": <whole hours>, "basis": "<one sentence>"}',
155
+ "- low and high are whole numbers of hours, 1 or more, with low <= high: a realistic range.",
156
+ "- basis is one sentence of at most 30 words that names the main pieces of work.",
157
+ "- Never mention money, rates or prices.",
158
+ "",
159
+ "Build:",
160
+ `- Type: ${input.type === "agent" ? "agent (an automation that runs as an n8n workflow)" : "app (a website or a web app)"}`,
161
+ `- Name: ${redactContactDetails(input.name)}`,
162
+ `- Description: ${redactContactDetails(input.description)}`,
163
+ ...(input.workflow
164
+ ? [`- Workflow: ${input.workflow.nodeCount} nodes. Node types: ${nodeTypes}`]
165
+ : []),
166
+ "",
167
+ `Spec (${input.spec.source}):`,
168
+ '"""',
169
+ cap(redactContactDetails(input.spec.text)),
170
+ '"""',
171
+ ].join("\n");
172
+ }
173
+ /**
174
+ * The model's reply → a range and a basis, or an error. A reply that is not
175
+ * exactly whole hours with low <= high is refused: never a guessed number.
176
+ */
177
+ export function parseEstimateReply(raw) {
178
+ const refused = {
179
+ ok: false,
180
+ error: "the model's reply is not {low, high, basis} with whole hours, low ≤ high",
181
+ };
182
+ let parsed;
183
+ try {
184
+ parsed = JSON.parse(raw.replace(/```(?:json)?/g, "").trim());
185
+ }
186
+ catch {
187
+ return refused;
188
+ }
189
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
190
+ return refused;
191
+ const { low, high, basis } = parsed;
192
+ if (!Number.isSafeInteger(low) || !Number.isSafeInteger(high))
193
+ return refused;
194
+ if (low < 1 || low > high)
195
+ return refused;
196
+ const sentence = typeof basis === "string" ? removeMoney(basis.replace(/\s+/g, " ").trim()) : "";
197
+ if (!sentence)
198
+ return refused;
199
+ return {
200
+ ok: true,
201
+ low: low,
202
+ high: high,
203
+ basis: sentence.length > BASIS_CHAR_CAP ? `${sentence.slice(0, BASIS_CHAR_CAP)}…` : sentence,
204
+ };
205
+ }
206
+ /** The spans of the top-level objects of a JSON array text, skipping strings. */
207
+ function topLevelObjectSpans(json) {
208
+ const spans = [];
209
+ let depth = 0;
210
+ let inString = false;
211
+ let start = -1;
212
+ for (let i = 0; i < json.length; i++) {
213
+ const char = json[i];
214
+ if (inString) {
215
+ if (char === "\\")
216
+ i++;
217
+ else if (char === '"')
218
+ inString = false;
219
+ continue;
220
+ }
221
+ if (char === '"')
222
+ inString = true;
223
+ else if (char === "{" || char === "[") {
224
+ if (char === "{" && depth === 1)
225
+ start = i;
226
+ depth++;
227
+ }
228
+ else if (char === "}" || char === "]") {
229
+ depth--;
230
+ if (char === "}" && depth === 1 && start >= 0) {
231
+ spans.push({ start, end: i + 1 });
232
+ start = -1;
233
+ }
234
+ }
235
+ }
236
+ return spans;
237
+ }
238
+ /** Sets `est_hours` in one row object's text, keeping its layout. */
239
+ function setRowHours(objectText, hours) {
240
+ const value = `[${hours[0]}, ${hours[1]}]`;
241
+ const existing = /("est_hours"\s*:\s*)\[[^\]]*\]/;
242
+ if (existing.test(objectText))
243
+ return objectText.replace(existing, `$1${value}`);
244
+ const close = objectText.lastIndexOf("}");
245
+ const body = objectText.slice(0, close).replace(/\s*$/, "");
246
+ const tail = objectText.slice(body.length);
247
+ const keyLine = /\n([ \t]*)"build"\s*:/.exec(objectText);
248
+ if (keyLine)
249
+ return `${body},\n${keyLine[1]}"est_hours": ${value}${tail}`;
250
+ return `${body}, "est_hours": ${value}${tail}`;
251
+ }
252
+ /**
253
+ * CLIENT.md with `est_hours` set on the given rows and nothing else changed:
254
+ * the block keeps its layout, and the result is re-parsed to prove that only
255
+ * those rows' `estHours` moved. Throws rather than write anything else.
256
+ */
257
+ export function setEstHours(clientMd, updates) {
258
+ const before = parseBuildsManifest(clientMd);
259
+ if (before.state !== "ok")
260
+ throw new Error("CLIENT.md ## Builds is not valid — fix it first");
261
+ const start = clientMd.indexOf(BUILDS_MANIFEST_START);
262
+ const end = clientMd.indexOf(BUILDS_MANIFEST_END);
263
+ const block = clientMd.slice(start, end);
264
+ const fence = /```json\s*\n([\s\S]*?)\n\s*```/.exec(block);
265
+ if (!fence?.[1])
266
+ throw new Error("CLIENT.md ## Builds has no ```json fence");
267
+ const jsonStart = start + fence.index + fence[0].indexOf(fence[1]);
268
+ const json = fence[1];
269
+ let edited = json;
270
+ const spans = topLevelObjectSpans(json);
271
+ // Right to left, so an edit never moves a span still to come.
272
+ for (const span of [...spans].reverse()) {
273
+ const objectText = json.slice(span.start, span.end);
274
+ const build = JSON.parse(objectText).build;
275
+ const hours = typeof build === "string" ? updates.get(build) : undefined;
276
+ if (!hours)
277
+ continue;
278
+ edited = `${edited.slice(0, span.start)}${setRowHours(objectText, hours)}${edited.slice(span.end)}`;
279
+ }
280
+ const next = `${clientMd.slice(0, jsonStart)}${edited}${clientMd.slice(jsonStart + json.length)}`;
281
+ const after = parseBuildsManifest(next);
282
+ const expected = before.rows.map((row) => {
283
+ const hours = updates.get(row.build);
284
+ return hours ? { ...row, estHours: hours } : row;
285
+ });
286
+ const unsafe = new Error("could not edit the ## Builds block safely — nothing written");
287
+ if (after.state !== "ok" || after.rows.length !== expected.length)
288
+ throw unsafe;
289
+ for (const [index, row] of after.rows.entries()) {
290
+ if (JSON.stringify(sortKeys(row)) !== JSON.stringify(sortKeys(expected[index])))
291
+ throw unsafe;
292
+ }
293
+ for (const build of updates.keys()) {
294
+ if (!before.rows.some((row) => row.build === build))
295
+ throw unsafe;
296
+ }
297
+ return next;
298
+ }
299
+ function sortKeys(value) {
300
+ return value
301
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)))
302
+ : value;
303
+ }
304
+ // ─── I/O ────────────────────────────────────────────────────────────────────
305
+ /** The nearest directory at or above `from` that holds a CLIENT.md. */
306
+ function findClientRepo(from) {
307
+ let dir = resolve(from);
308
+ for (;;) {
309
+ if (existsSync(join(dir, "CLIENT.md")))
310
+ return dir;
311
+ const parent = dirname(dir);
312
+ if (parent === dir)
313
+ return null;
314
+ dir = parent;
315
+ }
316
+ }
317
+ async function readSpec(repoDir, row, specOverride) {
318
+ if (specOverride) {
319
+ const path = resolve(repoDir, specOverride);
320
+ if (!existsSync(path))
321
+ throw new Error(`no spec file at ${specOverride}`);
322
+ // Forward slashes on every OS: the source is printed and sent in the prompt.
323
+ const source = relative(repoDir, path).split(sep).join("/");
324
+ return { source, text: await readFile(path, "utf8") };
325
+ }
326
+ const docsDir = join(repoDir, "docs");
327
+ const docs = existsSync(docsDir) ? (await readdir(docsDir)).sort() : [];
328
+ const own = docs.filter((file) => isBuildSpecFile(file, row.build)).pop();
329
+ if (own)
330
+ return { source: `docs/${own}`, text: await readFile(join(docsDir, own), "utf8") };
331
+ const techSpec = join(docsDir, "02-tech-spec.md");
332
+ if (!existsSync(techSpec))
333
+ return null;
334
+ const text = await readFile(techSpec, "utf8");
335
+ const section = specSectionFor(text, row);
336
+ if (section)
337
+ return { source: `docs/02-tech-spec.md § ${section.heading}`, text: section.text };
338
+ return { source: "docs/02-tech-spec.md (first part)", text };
339
+ }
340
+ async function readWorkflowSummary(repoDir, workflowId) {
341
+ if (!workflowId)
342
+ return null;
343
+ const dir = join(repoDir, "workflows");
344
+ if (!existsSync(dir))
345
+ return null;
346
+ for (const file of (await readdir(dir)).filter((name) => name.endsWith(".json")).sort()) {
347
+ let workflow;
348
+ try {
349
+ workflow = JSON.parse(await readFile(join(dir, file), "utf8"));
350
+ }
351
+ catch {
352
+ continue;
353
+ }
354
+ if (workflow?.id === workflowId) {
355
+ return workflowNodeSummary(workflow);
356
+ }
357
+ }
358
+ return null;
359
+ }
360
+ async function askGemini(prompt, apiKey, model, fetchImpl) {
361
+ const res = await fetchImpl(`${GEMINI_API_BASE}/models/${encodeURIComponent(model)}:generateContent`, {
362
+ method: "POST",
363
+ headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
364
+ signal: AbortSignal.timeout(GEMINI_TIMEOUT_MS),
365
+ body: JSON.stringify({
366
+ contents: [{ role: "user", parts: [{ text: prompt }] }],
367
+ generationConfig: {
368
+ responseMimeType: "application/json",
369
+ responseSchema: ESTIMATE_SCHEMA,
370
+ },
371
+ }),
372
+ });
373
+ const body = (await res.json().catch(() => null));
374
+ if (!res.ok) {
375
+ throw new Error(`Gemini answered HTTP ${res.status}: ${body?.error?.message ?? "no detail"}`);
376
+ }
377
+ return (body?.candidates?.[0]?.content?.parts ?? []).map((part) => part.text ?? "").join("");
378
+ }
379
+ /**
380
+ * Estimates the market hours of a client repo's builds: one Gemini call per
381
+ * build, a range of whole hours each. With `write`, sets `est_hours` on the
382
+ * estimated rows of CLIENT.md (only that field moves); the technician commits
383
+ * it. Never knows the rate, never prints a dollar figure.
384
+ */
385
+ export async function buildEstimate(options = {}) {
386
+ const repoDir = findClientRepo(options.repoDir ?? process.cwd());
387
+ if (!repoDir)
388
+ throw new Error("no CLIENT.md here or above — run this inside a client repo");
389
+ if (options.spec && !options.build)
390
+ throw new Error("--spec needs --build");
391
+ const clientMdPath = join(repoDir, "CLIENT.md");
392
+ const clientMd = await readFile(clientMdPath, "utf8");
393
+ const manifest = parseBuildsManifest(clientMd);
394
+ if (manifest.state === "invalid") {
395
+ throw new Error(`CLIENT.md ## Builds is invalid: ${manifest.errors.join("; ")}`);
396
+ }
397
+ if (manifest.state !== "ok") {
398
+ throw new Error("CLIENT.md has no filled ## Builds block — list the builds first");
399
+ }
400
+ let candidates;
401
+ if (options.build) {
402
+ const row = manifest.rows.find((r) => r.build === options.build);
403
+ if (!row)
404
+ throw new Error(`no build "${options.build}" in CLIENT.md ## Builds`);
405
+ candidates = [row];
406
+ }
407
+ else {
408
+ candidates = manifest.rows.filter((row) => row.status === "active");
409
+ }
410
+ const model = options.model ?? BUILD_ESTIMATE_MODEL;
411
+ const fetchImpl = options.fetchImpl ?? fetch;
412
+ const needsCall = candidates.some((row) => options.force || !row.estHours);
413
+ const apiKey = options.apiKey ?? process.env[GEMINI_API_KEY_ENV];
414
+ if (needsCall && !apiKey) {
415
+ throw new Error(`${GEMINI_API_KEY_ENV} is not set — run \`ia env fill\` (team-techs vault)`);
416
+ }
417
+ const rows = [];
418
+ for (const row of candidates) {
419
+ const base = { build: row.build, name: row.name, current: row.estHours ?? null };
420
+ if (row.estHours && !options.force) {
421
+ rows.push({ ...base, outcome: "skipped", reason: "has an estimate — --force to redo it" });
422
+ continue;
423
+ }
424
+ const spec = await readSpec(repoDir, row, options.spec);
425
+ if (!spec) {
426
+ rows.push({
427
+ ...base,
428
+ outcome: "error",
429
+ reason: "no spec found (docs/<build>-spec.md or docs/02-tech-spec.md) — pass --spec",
430
+ });
431
+ continue;
432
+ }
433
+ const prompt = buildEstimatePrompt({
434
+ type: row.type,
435
+ name: row.name,
436
+ description: row.description,
437
+ spec,
438
+ workflow: row.type === "agent" ? await readWorkflowSummary(repoDir, row.workflowId) : null,
439
+ });
440
+ try {
441
+ const reply = parseEstimateReply(await askGemini(prompt, apiKey, model, fetchImpl));
442
+ rows.push(reply.ok
443
+ ? {
444
+ ...base,
445
+ outcome: "estimated",
446
+ low: reply.low,
447
+ high: reply.high,
448
+ basis: reply.basis,
449
+ spec: spec.source,
450
+ }
451
+ : { ...base, outcome: "error", spec: spec.source, reason: reply.error });
452
+ }
453
+ catch (error) {
454
+ rows.push({
455
+ ...base,
456
+ outcome: "error",
457
+ spec: spec.source,
458
+ reason: error instanceof Error ? error.message : String(error),
459
+ });
460
+ }
461
+ }
462
+ const updates = new Map();
463
+ for (const row of rows) {
464
+ if (row.outcome === "estimated" && row.low !== undefined && row.high !== undefined) {
465
+ updates.set(row.build, [row.low, row.high]);
466
+ }
467
+ }
468
+ let written = false;
469
+ if (options.write && updates.size > 0) {
470
+ await writeFile(clientMdPath, setEstHours(clientMd, updates), "utf8");
471
+ written = true;
472
+ }
473
+ return {
474
+ repoDir,
475
+ model,
476
+ rows,
477
+ written,
478
+ writtenBuilds: written ? [...updates.keys()] : [],
479
+ };
480
+ }
@@ -1,3 +1,4 @@
1
+ import { GEMINI_API_KEY_ENV } from "./build-estimate.js";
1
2
  /** `required` fails `ia doctor` when unset; `optional` only warns. */
2
3
  export type EnvVarTier = "required" | "optional";
3
4
  /**
@@ -48,8 +49,8 @@ export interface EnvVarSpec {
48
49
  export declare const DEFAULT_TECH_VAULT = "team-techs";
49
50
  /** Payments / DB / deploy secrets — granted case-by-case. */
50
51
  export declare const INFRA_VAULT = "team-admin";
51
- /** Only `ia secrets mint gemini-api-key` reads it, so it has no owning module. */
52
- export declare const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
52
+ /** Owned by build-estimate.ts (`ia build-estimate`); re-exported here as before. */
53
+ export { GEMINI_API_KEY_ENV };
53
54
  /** Read by apps/slack-agent (relay.ts, feedback.ts) — an app, so it has no SDK module. */
54
55
  export declare const SLACK_RELAY_SECRET_ENV = "SLACK_RELAY_SECRET";
55
56
  /** Read by nothing; registered so every team-techs item is accounted for. */
@@ -1,4 +1,5 @@
1
1
  import { N8N_API_KEY_ENV, N8N_API_URL_ENV } from "./agent-templates.js";
2
+ import { GEMINI_API_KEY_ENV } from "./build-estimate.js";
2
3
  import { HOURS_EXPORT_SECRET_ENV } from "./claude-hours.js";
3
4
  import { GITHUB_API_TOKEN_ENV } from "./client-build.js";
4
5
  import { AIRTABLE_API_TOKEN_ENV, GOOGLE_SERVICE_ACCOUNT_KEY_ENV } from "./client-drive.js";
@@ -12,8 +13,8 @@ export const DEFAULT_TECH_VAULT = "team-techs";
12
13
  /** Payments / DB / deploy secrets — granted case-by-case. */
13
14
  export const INFRA_VAULT = "team-admin";
14
15
  const OP_DEFAULT_FIELD = "value";
15
- /** Only `ia secrets mint gemini-api-key` reads it, so it has no owning module. */
16
- export const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
16
+ /** Owned by build-estimate.ts (`ia build-estimate`); re-exported here as before. */
17
+ export { GEMINI_API_KEY_ENV };
17
18
  /** Read by apps/slack-agent (relay.ts, feedback.ts) — an app, so it has no SDK module. */
18
19
  export const SLACK_RELAY_SECRET_ENV = "SLACK_RELAY_SECRET";
19
20
  /** Read by nothing; registered so every team-techs item is accounted for. */
@@ -186,7 +187,7 @@ export const ENV_VARS = [
186
187
  source: "vault",
187
188
  doctor: false,
188
189
  vault: DEFAULT_TECH_VAULT,
189
- neededBy: "ia secrets mint gemini-api-key",
190
+ neededBy: "ia build-estimate, ia secrets mint gemini-api-key",
190
191
  howToGet: inTechVault,
191
192
  section: SECTION_DRIVERS,
192
193
  },
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { type AccessCheckItem, type AccessCheckOptions, type AccessCheckResult, type AccessService, type AccessStatus, accessCheck, classifyKey, clientVaultFor, } from "./access-check.js";
2
2
  export { type AgentMirrorOptions, type AgentMirrorResult, checkAgentMirror, type FetchLiveWorkflowsOptions, fetchLiveWorkflows, type LiveWorkflow, type MirrorRow, type MirrorState, type MirrorSummary, } from "./agent-mirror.js";
3
3
  export { type AgentBankOptions, type AgentTemplateInfo, type AgentTemplateMatch, type CreateFromTemplateInput, type CreateFromTemplateResult, createFromAgentTemplate, type ListAgentTemplatesResult, listAgentTemplates, N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, type SanitizedWorkflow, type SaveAgentTemplateInput, type SaveAgentTemplateOptions, type SaveAgentTemplateResult, type SearchAgentTemplatesOptions, type SearchAgentTemplatesResult, type SopState, type StrippedCredential, sanitizeN8nWorkflow, saveAgentTemplate, searchAgentTemplates, } from "./agent-templates.js";
4
+ export { BASIS_CHAR_CAP, BUILD_ESTIMATE_MODEL, type BuildEstimateOptions, type BuildEstimateOutcome, type BuildEstimateResult, type BuildEstimateRow, buildEstimate, buildEstimatePrompt, type EstimatePromptInput, type HoursRange, isBuildSpecFile, parseEstimateReply, redactContactDetails, removeMoney, SPEC_CHAR_CAP, setEstHours, specSectionFor, workflowNodeSummary, } from "./build-estimate.js";
4
5
  export { CLAUDE_CONFIG_DIR_ENV, type ClaudeHoursExportOptions, type ClaudeHoursExportResult, type ClaudeHoursSummaryRow, compactClaudeHoursExport, type DeliverClaudeHoursExportOptions, type DeliverClaudeHoursExportResult, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, type SaveClaudeHoursExportOptions, type SendClaudeHoursExportOptions, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
5
6
  export { ClientBuildAuthError, type ClientBuildDoc, type ClientBuildOptions, type ClientBuildResult, clientBuild, GITHUB_API_TOKEN_ENV, } from "./client-build.js";
6
7
  export { type ClientCall, type ClientContextOptions, type ClientContextResult, clientContext, } from "./client-context.js";
@@ -39,7 +40,7 @@ export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
39
40
  export { defaultOpTitle, type MintImpls, type MintToOpOptions, type MintToOpRequest, type MintToOpResult, mintToOnePassword, } from "./op-store.js";
40
41
  export { type PingResult, ping } from "./ping.js";
41
42
  export { detectPlatform, detectPlatformInfo, detectShell, opNeedsAnotherShell, type Platform, type PlatformInfo, type Shell, } from "./platform.js";
42
- export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_BUILD_TYPES, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_URL_ENV, type PortalAddUserInput, type PortalAddUserResult, PortalAdminAuthError, type PortalAdminOptions, type PortalAgent, type PortalAgentSyncRow, type PortalBuild, type PortalBuildType, type PortalCreateAgentInput, type PortalCreateBuildInput, type PortalCreateOrgInput, type PortalCreateOrgResult, type PortalListAgentsResult, type PortalListBuildsResult, type PortalListOrgsResult, type PortalOrg, type PortalOrgUser, PortalRequestError, type PortalSetAgentNameInput, type PortalSetAgentNameResult, type PortalSetAgentStatusInput, type PortalSetAgentStatusResult, type PortalSetAgentTriageResult, type PortalSetAgentWorkflowInput, type PortalSetAgentWorkflowResult, type PortalSetBuildDetailsInput, type PortalSetBuildDetailsResult, type PortalSetBuildStatusInput, type PortalSetDriveFolderResult, type PortalSetPasswordResult, type PortalSetUserInput, type PortalSetUserResult, type PortalSyncRunsResult, type PortalTriageBackfillResult, type PortalTriageProvider, type PortalTriageRecordsPage, portalAddUser, portalBackfillTriageRecords, portalBuildType, portalBuildWorkflowId, portalCreateAgent, portalCreateBuild, portalCreateOrg, portalListAgents, portalListBuilds, portalListOrgs, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetBuildDetails, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSetUser, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
43
+ export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_BUILD_TYPES, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_TODO_ACCESS_TABS, PORTAL_TODO_CHANGES, PORTAL_TODO_KINDS, PORTAL_URL_ENV, type PortalAddTodoInput, type PortalAddTodoResult, type PortalAddUserInput, type PortalAddUserResult, PortalAdminAuthError, type PortalAdminOptions, type PortalAgent, type PortalAgentSyncRow, type PortalBuild, type PortalBuildType, type PortalCreateAgentInput, type PortalCreateBuildInput, type PortalCreateOrgInput, type PortalCreateOrgResult, type PortalListAgentsResult, type PortalListBuildsResult, type PortalListOrgsResult, type PortalListTodosResult, type PortalOrg, type PortalOrgUser, PortalRequestError, type PortalSetAgentNameInput, type PortalSetAgentNameResult, type PortalSetAgentStatusInput, type PortalSetAgentStatusResult, type PortalSetAgentTriageResult, type PortalSetAgentWorkflowInput, type PortalSetAgentWorkflowResult, type PortalSetBuildDetailsInput, type PortalSetBuildDetailsResult, type PortalSetBuildStatusInput, type PortalSetDriveFolderResult, type PortalSetPasswordResult, type PortalSetTodoInput, type PortalSetTodoResult, type PortalSetUserInput, type PortalSetUserResult, type PortalSyncRunsResult, type PortalTodo, type PortalTodoAccessTab, type PortalTodoChange, type PortalTodoKind, type PortalTodoStatus, type PortalTriageBackfillResult, type PortalTriageProvider, type PortalTriageRecordsPage, portalAddTodo, portalAddUser, portalBackfillTriageRecords, portalBuildType, portalBuildWorkflowId, portalCreateAgent, portalCreateBuild, portalCreateOrg, portalListAgents, portalListBuilds, portalListOrgs, portalListTodos, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetBuildDetails, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSetTodo, portalSetUser, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
43
44
  export { BUILD_DESCRIPTION_MAX, BUILD_NAME_MAX, BUILDS_MANIFEST_END, BUILDS_MANIFEST_START, type BuildsManifest, type BuildsManifestSource, type BuildsManifestState, type BuildsSyncAction, type BuildsSyncActionResult, type BuildsSyncOptions, type BuildsSyncOrgResult, type BuildsSyncPlan, type BuildsSyncResult, type ManifestBuild, type ManifestBuildStatus, parseBuildsManifest, planBuildsSync, type RemoteClientMdReader, syncBuilds, } from "./portal-sync-builds.js";
44
45
  export { expectedGithubAccount, type PrOpenOptions, type PrOpenResult, parseGithubRemote, prOpen, } from "./pr-open.js";
45
46
  export { CLIENT_LINE_MAX, parseRoadmapRows, ROADMAP_LABELS, ROADMAP_SOURCES, type RoadmapMigrateClient, type RoadmapMigrateOptions, type RoadmapMigrateResult, type RoadmapMigrateRow, type RoadmapRow, roadmapMigrate, } from "./roadmap-migrate.js";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  export { accessCheck, classifyKey, clientVaultFor, } from "./access-check.js";
5
5
  export { checkAgentMirror, fetchLiveWorkflows, } from "./agent-mirror.js";
6
6
  export { createFromAgentTemplate, listAgentTemplates, N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, sanitizeN8nWorkflow, saveAgentTemplate, searchAgentTemplates, } from "./agent-templates.js";
7
+ export { BASIS_CHAR_CAP, BUILD_ESTIMATE_MODEL, buildEstimate, buildEstimatePrompt, isBuildSpecFile, parseEstimateReply, redactContactDetails, removeMoney, SPEC_CHAR_CAP, setEstHours, specSectionFor, workflowNodeSummary, } from "./build-estimate.js";
7
8
  export { CLAUDE_CONFIG_DIR_ENV, compactClaudeHoursExport, deliverClaudeHoursExport, exportClaudeHours, HOURS_EXPORT_DIR, HOURS_EXPORT_SCHEMA, HOURS_EXPORT_SECRET_ENV, HOURS_EXPORT_SECRET_HEADER, HOURS_EXPORT_WEBHOOK_URL, PROMPT_WINDOW_MINUTES, parseLedgerDate, parseMinuteIso, saveClaudeHoursExport, sendClaudeHoursExport, TOOL_INPUT_PATH_KEYS, UNATTRIBUTED_SLUG, } from "./claude-hours.js";
8
9
  export { ClientBuildAuthError, clientBuild, GITHUB_API_TOKEN_ENV, } from "./client-build.js";
9
10
  export { clientContext, } from "./client-context.js";
@@ -42,7 +43,7 @@ export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
42
43
  export { defaultOpTitle, mintToOnePassword, } from "./op-store.js";
43
44
  export { ping } from "./ping.js";
44
45
  export { detectPlatform, detectPlatformInfo, detectShell, opNeedsAnotherShell, } from "./platform.js";
45
- export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_BUILD_TYPES, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_URL_ENV, PortalAdminAuthError, PortalRequestError, portalAddUser, portalBackfillTriageRecords, portalBuildType, portalBuildWorkflowId, portalCreateAgent, portalCreateBuild, portalCreateOrg, portalListAgents, portalListBuilds, portalListOrgs, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetBuildDetails, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSetUser, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
46
+ export { DEFAULT_PORTAL_URL, PORTAL_ADMIN_SECRET_ENV, PORTAL_BUILD_TYPES, PORTAL_PASSWORD_WARNING, PORTAL_SYNC_MAX_DAYS, PORTAL_TODO_ACCESS_TABS, PORTAL_TODO_CHANGES, PORTAL_TODO_KINDS, PORTAL_URL_ENV, PortalAdminAuthError, PortalRequestError, portalAddTodo, portalAddUser, portalBackfillTriageRecords, portalBuildType, portalBuildWorkflowId, portalCreateAgent, portalCreateBuild, portalCreateOrg, portalListAgents, portalListBuilds, portalListOrgs, portalListTodos, portalReadTriageRecords, portalSetAgentName, portalSetAgentStatus, portalSetAgentTriage, portalSetAgentWorkflow, portalSetBuildDetails, portalSetBuildName, portalSetBuildStatus, portalSetBuildTriage, portalSetBuildWorkflow, portalSetDriveFolder, portalSetOrgSlackChannel, portalSetPassword, portalSetTodo, portalSetUser, portalSyncRuns, validatePortalBuildFields, } from "./portal-admin.js";
46
47
  export { BUILD_DESCRIPTION_MAX, BUILD_NAME_MAX, BUILDS_MANIFEST_END, BUILDS_MANIFEST_START, parseBuildsManifest, planBuildsSync, syncBuilds, } from "./portal-sync-builds.js";
47
48
  export { expectedGithubAccount, parseGithubRemote, prOpen, } from "./pr-open.js";
48
49
  export { CLIENT_LINE_MAX, parseRoadmapRows, ROADMAP_LABELS, ROADMAP_SOURCES, roadmapMigrate, } from "./roadmap-migrate.js";
@@ -68,6 +68,12 @@ export interface PortalBuild {
68
68
  url?: string | null;
69
69
  /** ISO time the build was registered (its go-live date). Absent on portals older than 2026-10-16. */
70
70
  createdAt?: string;
71
+ /**
72
+ * Market hours to build it, [low, high] (CLIENT.md `est_hours`); null = no
73
+ * estimate. Hours only: the rate lives in the portal. Absent on portals
74
+ * older than INS-1380.
75
+ */
76
+ estHours?: [number, number] | null;
71
77
  }
72
78
  /** Old name of `PortalBuild`, kept as an alias until the full rename. */
73
79
  export type PortalAgent = PortalBuild;
@@ -229,6 +235,72 @@ export declare function portalAddUser(input: PortalAddUserInput, options?: Porta
229
235
  */
230
236
  export declare function portalSetUser(input: PortalSetUserInput, options?: PortalAdminOptions): Promise<PortalSetUserResult>;
231
237
  export declare function portalListOrgs(options?: PortalAdminOptions): Promise<PortalListOrgsResult>;
238
+ export type PortalTodoKind = "question" | "action" | "access";
239
+ export declare const PORTAL_TODO_KINDS: readonly PortalTodoKind[];
240
+ export type PortalTodoAccessTab = "overview" | "vault" | "new";
241
+ export declare const PORTAL_TODO_ACCESS_TABS: readonly PortalTodoAccessTab[];
242
+ export type PortalTodoChange = "confirm" | "reopen" | "cancel";
243
+ export declare const PORTAL_TODO_CHANGES: readonly PortalTodoChange[];
244
+ export type PortalTodoStatus = "open" | "waiting_on_us" | "done" | "canceled";
245
+ export interface PortalTodo {
246
+ id: string;
247
+ /** Set on an item that a seed file or a sync made; null for a hand-made item. */
248
+ key: string | null;
249
+ kind: PortalTodoKind;
250
+ title: string;
251
+ detail: string | null;
252
+ accessTab: PortalTodoAccessTab | null;
253
+ accessSystem: string | null;
254
+ /** `waiting_on_us` = the client ticked it and staff have not confirmed it. */
255
+ status: PortalTodoStatus;
256
+ /** The answer text is the client's own words; read it on the admin page. */
257
+ hasAnswer: boolean;
258
+ clientDoneAt: string | null;
259
+ confirmedAt: string | null;
260
+ sortOrder: number;
261
+ }
262
+ export interface PortalListTodosResult {
263
+ slug: string;
264
+ todos: PortalTodo[];
265
+ }
266
+ export interface PortalAddTodoInput {
267
+ slug: string;
268
+ kind: PortalTodoKind;
269
+ /** The client reads the title and the detail: no email address, no price. */
270
+ title: string;
271
+ detail?: string;
272
+ /** The Access tab the item's button opens. */
273
+ accessTab?: PortalTodoAccessTab;
274
+ /** With `accessTab: "new"` only: the system name that prefills the credential form. */
275
+ accessSystem?: string;
276
+ sortOrder?: number;
277
+ }
278
+ export interface PortalAddTodoResult {
279
+ slug: string;
280
+ todo: PortalTodo;
281
+ }
282
+ export interface PortalSetTodoInput {
283
+ slug: string;
284
+ /** The item's id, from `portalListTodos`. */
285
+ item: string;
286
+ change: PortalTodoChange;
287
+ }
288
+ export interface PortalSetTodoResult {
289
+ slug: string;
290
+ todo: PortalTodo;
291
+ /** False when the item was already in that state. */
292
+ changed: boolean;
293
+ }
294
+ /** One org's To-do items in display order, canceled ones included (GET /api/admin/todos). */
295
+ export declare function portalListTodos(slug: string, options?: PortalAdminOptions): Promise<PortalListTodosResult>;
296
+ /** Add one To-do item to an org (POST /api/admin/todos). */
297
+ export declare function portalAddTodo(input: PortalAddTodoInput, options?: PortalAdminOptions): Promise<PortalAddTodoResult>;
298
+ /**
299
+ * Confirm, reopen or cancel one To-do item (PATCH /api/admin/todos). `confirm`
300
+ * locks the item for the client; `cancel` hides it from the client and keeps
301
+ * the row; `reopen` clears the tick, the confirm and a cancel. Never deletes.
302
+ */
303
+ export declare function portalSetTodo(input: PortalSetTodoInput, options?: PortalAdminOptions): Promise<PortalSetTodoResult>;
232
304
  /**
233
305
  * The client-side check of a create: an agent needs its n8n workflow id, an
234
306
  * app must not carry one, and a url (either type) must be https. The portal
@@ -272,6 +344,8 @@ export interface PortalSetBuildDetailsInput {
272
344
  description?: string;
273
345
  /** Omit to leave as is; null clears the Open link. https only. */
274
346
  url?: string | null;
347
+ /** Omit to leave as is; null clears it. [low, high]: whole hours, 1 or more, low ≤ high. */
348
+ estHours?: [number, number] | null;
275
349
  }
276
350
  export interface PortalSetBuildDetailsResult {
277
351
  org: string;
@@ -279,16 +353,21 @@ export interface PortalSetBuildDetailsResult {
279
353
  previous: {
280
354
  description: string;
281
355
  url: string | null;
356
+ estHours?: [number, number] | null;
282
357
  };
283
358
  description: string;
284
359
  url: string | null;
360
+ /** Absent on portals older than INS-1380. */
361
+ estHours?: [number, number] | null;
285
362
  /** False when nothing differed — the call is idempotent. */
286
363
  changed: boolean;
287
364
  }
288
365
  /**
289
366
  * Change the card text under a build's name: its description and/or its url
290
- * (an app's Open link). Before this route (team-web, 2026-10-31) only the
291
- * create could set either. A portal without the route answers 404.
367
+ * (an app's Open link), and its market-hours estimate (`estHours`, never a
368
+ * dollar figure). Before this route (team-web, 2026-10-31) only the create
369
+ * could set either. A portal without the route answers 404; a portal older
370
+ * than INS-1380 refuses a call that sends only `estHours`.
292
371
  */
293
372
  export declare function portalSetBuildDetails(input: PortalSetBuildDetailsInput, options?: PortalAdminOptions): Promise<PortalSetBuildDetailsResult>;
294
373
  /**
@@ -146,6 +146,61 @@ export async function portalSetUser(input, options = {}) {
146
146
  export async function portalListOrgs(options = {}) {
147
147
  return portalRequest("GET", "/api/admin/orgs", options);
148
148
  }
149
+ export const PORTAL_TODO_KINDS = ["question", "action", "access"];
150
+ export const PORTAL_TODO_ACCESS_TABS = ["overview", "vault", "new"];
151
+ export const PORTAL_TODO_CHANGES = ["confirm", "reopen", "cancel"];
152
+ const TODO_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
153
+ /** One org's To-do items in display order, canceled ones included (GET /api/admin/todos). */
154
+ export async function portalListTodos(slug, options = {}) {
155
+ const org = normalizeSlug(slug, "org");
156
+ return portalRequest("GET", `/api/admin/todos?slug=${encodeURIComponent(org)}`, options);
157
+ }
158
+ /** Add one To-do item to an org (POST /api/admin/todos). */
159
+ export async function portalAddTodo(input, options = {}) {
160
+ const slug = normalizeSlug(input.slug, "org");
161
+ if (!PORTAL_TODO_KINDS.includes(input.kind)) {
162
+ throw new Error(`kind must be ${PORTAL_TODO_KINDS.join("|")}`);
163
+ }
164
+ const title = input.title.trim();
165
+ if (!title)
166
+ throw new Error("the title is empty");
167
+ if (input.accessTab !== undefined && !PORTAL_TODO_ACCESS_TABS.includes(input.accessTab)) {
168
+ throw new Error(`access tab must be ${PORTAL_TODO_ACCESS_TABS.join("|")}`);
169
+ }
170
+ const accessSystem = input.accessSystem?.trim();
171
+ if (accessSystem && input.accessTab !== "new") {
172
+ throw new Error("--access-system goes with --access-tab new only");
173
+ }
174
+ if (input.sortOrder !== undefined && !Number.isInteger(input.sortOrder)) {
175
+ throw new Error("the order must be a whole number");
176
+ }
177
+ const detail = input.detail?.trim();
178
+ return portalRequest("POST", "/api/admin/todos", options, {
179
+ slug,
180
+ kind: input.kind,
181
+ title,
182
+ ...(detail ? { detail } : {}),
183
+ ...(input.accessTab ? { accessTab: input.accessTab } : {}),
184
+ ...(accessSystem ? { accessSystem } : {}),
185
+ ...(input.sortOrder !== undefined ? { sortOrder: input.sortOrder } : {}),
186
+ });
187
+ }
188
+ /**
189
+ * Confirm, reopen or cancel one To-do item (PATCH /api/admin/todos). `confirm`
190
+ * locks the item for the client; `cancel` hides it from the client and keeps
191
+ * the row; `reopen` clears the tick, the confirm and a cancel. Never deletes.
192
+ */
193
+ export async function portalSetTodo(input, options = {}) {
194
+ const slug = normalizeSlug(input.slug, "org");
195
+ const item = input.item.trim().toLowerCase();
196
+ if (!TODO_ID_PATTERN.test(item)) {
197
+ throw new Error("give the full item id from `ia portal list-todo`");
198
+ }
199
+ if (!PORTAL_TODO_CHANGES.includes(input.change)) {
200
+ throw new Error(`change must be ${PORTAL_TODO_CHANGES.join("|")}`);
201
+ }
202
+ return portalRequest("PATCH", "/api/admin/todos", options, { slug, item, change: input.change });
203
+ }
149
204
  // ─── Builds registry (named `agents` before 2026-10-13) ─────────────────────
150
205
  //
151
206
  // The portal renamed its `agents` registry to `builds` and added a build type
@@ -239,10 +294,19 @@ export async function portalSetBuildName(input, options = {}) {
239
294
  export async function portalSetAgentName(input, options = {}) {
240
295
  return portalSetBuildName({ slug: input.slug, build: input.agent, name: input.name }, options);
241
296
  }
297
+ /** [low, high]: two whole numbers of hours, 1 or more, low ≤ high. */
298
+ function isHoursRange(value) {
299
+ return (Array.isArray(value) &&
300
+ value.length === 2 &&
301
+ value.every((hours) => Number.isSafeInteger(hours) && hours > 0) &&
302
+ value[0] <= value[1]);
303
+ }
242
304
  /**
243
305
  * Change the card text under a build's name: its description and/or its url
244
- * (an app's Open link). Before this route (team-web, 2026-10-31) only the
245
- * create could set either. A portal without the route answers 404.
306
+ * (an app's Open link), and its market-hours estimate (`estHours`, never a
307
+ * dollar figure). Before this route (team-web, 2026-10-31) only the create
308
+ * could set either. A portal without the route answers 404; a portal older
309
+ * than INS-1380 refuses a call that sends only `estHours`.
246
310
  */
247
311
  export async function portalSetBuildDetails(input, options = {}) {
248
312
  const slug = normalizeSlug(input.slug, "org");
@@ -253,14 +317,18 @@ export async function portalSetBuildDetails(input, options = {}) {
253
317
  const url = input.url === null ? null : input.url?.trim();
254
318
  if (url && !isHttpsUrl(url))
255
319
  throw new Error(`url must be an https:// address (got "${url}")`);
256
- if (description === undefined && url === undefined) {
257
- throw new Error("give a description and/or a url to change");
320
+ if (input.estHours !== undefined && input.estHours !== null && !isHoursRange(input.estHours)) {
321
+ throw new Error("estHours must be [low, high]: two whole numbers of hours, 1 or more, low ≤ high");
322
+ }
323
+ if (description === undefined && url === undefined && input.estHours === undefined) {
324
+ throw new Error("give a description, a url and/or estHours to change");
258
325
  }
259
326
  return portalRequest("POST", `${BUILDS_PATH}/details`, options, {
260
327
  slug,
261
328
  agent: build,
262
329
  ...(description !== undefined ? { description } : {}),
263
330
  ...(url !== undefined ? { url: url || null } : {}),
331
+ ...(input.estHours !== undefined ? { estHours: input.estHours } : {}),
264
332
  });
265
333
  }
266
334
  /**
@@ -19,6 +19,12 @@ export interface ManifestBuild {
19
19
  status: ManifestBuildStatus;
20
20
  /** Absent = not managed here; null = explicitly not a triage agent. */
21
21
  triage?: PortalTriageProvider | null;
22
+ /**
23
+ * Market hours to build it, [low, high], from `ia build-estimate`. Never a
24
+ * dollar figure: the portal turns it into a cost range when it renders.
25
+ * Absent = no estimate yet.
26
+ */
27
+ estHours?: [number, number];
22
28
  }
23
29
  export type BuildsManifestState =
24
30
  /** No markers: the repo predates the manifest. Skipped. */
@@ -46,6 +52,8 @@ export type BuildsSyncAction = {
46
52
  url: string | null;
47
53
  status: ManifestBuildStatus;
48
54
  triage: PortalTriageProvider | null;
55
+ /** Set after the create, through the details route. */
56
+ estHours: [number, number] | null;
49
57
  } | {
50
58
  kind: "repoint";
51
59
  build: string;
@@ -67,6 +75,11 @@ export type BuildsSyncAction = {
67
75
  from: string | null;
68
76
  to: string | null;
69
77
  };
78
+ /** Market hours, never dollars. */
79
+ estHours?: {
80
+ from: [number, number] | null;
81
+ to: [number, number] | null;
82
+ };
70
83
  } | {
71
84
  kind: "status";
72
85
  build: string;
@@ -117,6 +130,8 @@ export interface BuildsSyncOrgResult {
117
130
  actions: BuildsSyncActionResult[];
118
131
  registryOnly: BuildsSyncPlan["registryOnly"];
119
132
  conflicts: string[];
133
+ /** Active manifest rows with no `est_hours` (an info line, never a change). */
134
+ unestimated: number;
120
135
  }
121
136
  export interface BuildsSyncResult {
122
137
  applied: boolean;
@@ -127,6 +142,8 @@ export interface BuildsSyncResult {
127
142
  actionCount: number;
128
143
  /** Apply only: actions the portal refused. */
129
144
  failedCount: number;
145
+ /** Active builds, across all orgs, whose row has no `est_hours`. */
146
+ unestimatedCount: number;
130
147
  }
131
148
  /** Reads `clients/client-<slug>/CLIENT.md` from GitHub when the repo is not cloned. Null = not there. */
132
149
  export type RemoteClientMdReader = (slug: string) => Promise<string | null>;
@@ -149,7 +166,7 @@ export interface BuildsSyncOptions {
149
166
  /**
150
167
  * Compares every client repo's `## Builds` manifest with the portal's builds
151
168
  * registry and, with `apply`, moves the registry to match: create, rename,
152
- * description/url, status, triage, repoint. Never deletes, never touches
169
+ * description/url/est_hours, status, triage, repoint. Never deletes, never touches
153
170
  * Install Agent's own org, never writes a client repo. A second run after an
154
171
  * apply plans nothing.
155
172
  */
@@ -12,8 +12,10 @@ import { portalBuildType, portalBuildWorkflowId, portalCreateBuild, portalListBu
12
12
  // manifest does not name is reported, not changed.
13
13
  //
14
14
  // The validator below has a twin in client-template (`ci/builds-manifest.mjs`,
15
- // repo-lint rule 11). The repos never import each other, so a rule change
16
- // lands in both files in the same piece of work.
15
+ // repo-lint rule 11) and a read-only copy in the portal
16
+ // (team-web/apps/portal/lib/builds-manifest.ts, whose drift test runs all
17
+ // three). The repos never import each other, so a rule change lands in all
18
+ // three files in the same piece of work.
17
19
  export const BUILDS_MANIFEST_START = "<!-- BUILDS:START -->";
18
20
  export const BUILDS_MANIFEST_END = "<!-- BUILDS:END -->";
19
21
  export const BUILD_NAME_MAX = 120;
@@ -29,7 +31,15 @@ const ROW_KEYS = new Set([
29
31
  "url",
30
32
  "status",
31
33
  "triage",
34
+ "est_hours",
32
35
  ]);
36
+ /** `est_hours`: [low, high], two positive whole numbers, low ≤ high. */
37
+ function isHoursRange(value) {
38
+ return (Array.isArray(value) &&
39
+ value.length === 2 &&
40
+ value.every((hours) => Number.isSafeInteger(hours) && hours > 0) &&
41
+ value[0] <= value[1]);
42
+ }
33
43
  function isHttps(value) {
34
44
  try {
35
45
  return new URL(value).protocol === "https:" && value.startsWith("https://");
@@ -95,6 +105,8 @@ function readRow(raw, index, errors) {
95
105
  row.triage !== "gmail" &&
96
106
  row.triage !== "outlook")
97
107
  fail("triage must be gmail|outlook (or null)");
108
+ if (row.est_hours !== undefined && !isHoursRange(row.est_hours))
109
+ fail("est_hours must be [low, high]: two positive whole numbers, low ≤ high");
98
110
  if (errors.length > before)
99
111
  return null;
100
112
  return {
@@ -106,6 +118,9 @@ function readRow(raw, index, errors) {
106
118
  url,
107
119
  status: row.status,
108
120
  ...(row.triage !== undefined ? { triage: row.triage } : {}),
121
+ ...(isHoursRange(row.est_hours)
122
+ ? { estHours: [row.est_hours[0], row.est_hours[1]] }
123
+ : {}),
109
124
  };
110
125
  }
111
126
  /** Reads and validates the `## Builds` block of a CLIENT.md. Pure. */
@@ -163,6 +178,9 @@ export function parseBuildsManifest(clientMd) {
163
178
  }
164
179
  return errors.length > 0 ? { state: "invalid", rows: [], errors } : { state: "ok", rows, errors };
165
180
  }
181
+ function sameHours(a, b) {
182
+ return a === null || b === null ? a === b : a[0] === b[0] && a[1] === b[1];
183
+ }
166
184
  /**
167
185
  * Plans one org. Pure: `registry` is every build in the registry (all orgs),
168
186
  * because an n8n workflow id is unique across the whole registry.
@@ -222,6 +240,7 @@ export function planBuildsSync(org, manifest, registry) {
222
240
  url: row.url,
223
241
  status: row.status,
224
242
  triage: row.triage ?? null,
243
+ estHours: row.estHours ?? null,
225
244
  });
226
245
  continue;
227
246
  }
@@ -240,7 +259,16 @@ export function planBuildsSync(org, manifest, registry) {
240
259
  if (row.type === "app" && currentUrl !== row.url) {
241
260
  details.url = { from: currentUrl, to: row.url };
242
261
  }
243
- if (details.description || details.url)
262
+ // A portal older than INS-1380 does not report the field: leave it alone.
263
+ // The manifest is the only writer, so a row with no est_hours clears it.
264
+ if (current.estHours !== undefined) {
265
+ const currentHours = current.estHours ?? null;
266
+ const wantedHours = row.estHours ?? null;
267
+ if (!sameHours(currentHours, wantedHours)) {
268
+ details.estHours = { from: currentHours, to: wantedHours };
269
+ }
270
+ }
271
+ if (details.description || details.url || details.estHours)
244
272
  followUps.push(details);
245
273
  if (current.status !== row.status) {
246
274
  followUps.push({ kind: "status", build: row.build, from: current.status, to: row.status });
@@ -311,6 +339,8 @@ async function applyAction(action, org, portal) {
311
339
  await portalSetBuildStatus({ ...ref, status: action.status }, portal);
312
340
  if (action.triage)
313
341
  await portalSetBuildTriage({ ...ref, provider: action.triage }, portal);
342
+ if (action.estHours)
343
+ await portalSetBuildDetails({ ...ref, estHours: action.estHours }, portal);
314
344
  return;
315
345
  case "repoint":
316
346
  await portalSetBuildWorkflow({ ...ref, workflowId: action.to }, portal);
@@ -323,6 +353,7 @@ async function applyAction(action, org, portal) {
323
353
  ...ref,
324
354
  ...(action.description ? { description: action.description.to } : {}),
325
355
  ...(action.url ? { url: action.url.to } : {}),
356
+ ...(action.estHours ? { estHours: action.estHours.to } : {}),
326
357
  }, portal);
327
358
  return;
328
359
  case "status":
@@ -336,7 +367,7 @@ async function applyAction(action, org, portal) {
336
367
  /**
337
368
  * Compares every client repo's `## Builds` manifest with the portal's builds
338
369
  * registry and, with `apply`, moves the registry to match: create, rename,
339
- * description/url, status, triage, repoint. Never deletes, never touches
370
+ * description/url/est_hours, status, triage, repoint. Never deletes, never touches
340
371
  * Install Agent's own org, never writes a client repo. A second run after an
341
372
  * apply plans nothing.
342
373
  */
@@ -375,7 +406,7 @@ export async function syncBuilds(options) {
375
406
  errors.push(error instanceof Error ? error.message : String(error));
376
407
  }
377
408
  }
378
- const empty = { actions: [], registryOnly: [], conflicts: [] };
409
+ const empty = { actions: [], registryOnly: [], conflicts: [], unestimated: 0 };
379
410
  if (clientMd === null) {
380
411
  orgs.push({ org, source, manifest: "no-repo", errors, ...empty });
381
412
  continue;
@@ -411,6 +442,7 @@ export async function syncBuilds(options) {
411
442
  actions,
412
443
  registryOnly: plan.registryOnly,
413
444
  conflicts: plan.conflicts,
445
+ unestimated: manifest.rows.filter((row) => row.status === "active" && !row.estHours).length,
414
446
  });
415
447
  }
416
448
  const all = orgs.flatMap((org) => org.actions);
@@ -420,5 +452,6 @@ export async function syncBuilds(options) {
420
452
  skippedOrgs,
421
453
  actionCount: all.length,
422
454
  failedCount: all.filter((a) => typeof a.outcome === "object").length,
455
+ unestimatedCount: orgs.reduce((sum, org) => sum + org.unestimated, 0),
423
456
  };
424
457
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@installagent/sdk",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Install Agent's shared SDK for internal team operations (client repos, n8n workflows, docs search, and more).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -49,6 +49,7 @@ installagent/
49
49
  | Build/edit anything *for* a client (spec, workflow, diagram, PDF, site, agent) | `clients/client-<slug>/` | that repo's `CADENCE.md` (how to ship it) + `AGENT.md` + `CLIENT.md` |
50
50
  | Ship a change into a client repo without causing drift (feature, fix, scope change) | `clients/client-<slug>/CADENCE.md` | it *is* the read — five stages + the surface matrix |
51
51
  | Answer "what did we ship for X / does it work?" | `clients/client-<slug>/docs/00-delivery-log.md` + `evidence/` | same |
52
+ | A build goes live (its portal card + estimated build cost) | the `## Builds` row in `clients/client-<slug>/CLIENT.md` + `ia build-estimate --build <slug> --write` (market hours, never dollars) | that repo's `CADENCE.md` (row *A build goes live*) + team hub → Techs → Client engagement → Estimated build cost |
52
53
  | Check or change deal status | **Airtable (`Clients - Master`)** — never a file in git | — |
53
54
  | Build or edit an n8n workflow (ours or a client's) | **check `agents/` (the bank) first**, then the client repo's `workflows/` or `team-infra/n8n-workflows/` | `agents/README.md` + `team-infra/skills/n8n-workflow.md` |
54
55
  | An n8n workflow sends a PDF on to a size-capped step (a Vercel app, an email, an LLM, a vendor upload) | the **`pdf` compress service** on the n8n box (`http://pdf:8080`): compress first, keep the size gate, keep the original on any error | `team-infra/skills/n8n-workflow.md` § 3 + `team-infra/pdf-service/README.md` |
@@ -56,6 +56,7 @@ secrets).
56
56
  | Weekly triage summary into the client's channel | `ia portal set-org-slack-channel --slug <slug> --channel <C…>` (`none` clears it) — the digest only posts for an org with a channel |
57
57
  | Mint a GCP SA key / Gemini key / Fathom webhook | `ia secrets mint <kind> …` |
58
58
  | Portal org/agent admin (create org, passwords, run sync) | `ia portal <cmd>` — CLI-only, never via MCP |
59
+ | A build went live / "what would this build cost at market rate?" | add its row to `CLIENT.md` `## Builds`, then `ia build-estimate --build <slug>` in the client repo: market hours (low–high) + a one-line basis, from one Gemini call on the build's spec. Hours only — never a rate or a dollar figure, in git, Linear or Slack. Review it, then `--write` sets the row's `est_hours`; commit it with the row. The portal multiplies by its one rate (admin Clients page); `ia portal sync-builds --apply` (account owner) carries it over. `--force` re-estimates a row; `--spec <file>` points it at the right spec |
59
60
 
60
61
  Flags, inputs, and required env vars per command: the generated reference at
61
62
  `team-tools/docs/reference/cli.md` (MCP twins: `mcp-tools.md`). That