@installagent/sdk 0.1.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.
Files changed (94) hide show
  1. package/dist/agent-templates.d.ts +90 -0
  2. package/dist/agent-templates.js +211 -0
  3. package/dist/client-build.d.ts +50 -0
  4. package/dist/client-build.js +155 -0
  5. package/dist/client-context.d.ts +40 -0
  6. package/dist/client-context.js +70 -0
  7. package/dist/client-drive.d.ts +67 -0
  8. package/dist/client-drive.js +278 -0
  9. package/dist/client-intake.d.ts +68 -0
  10. package/dist/client-intake.js +189 -0
  11. package/dist/client-linear.d.ts +30 -0
  12. package/dist/client-linear.js +85 -0
  13. package/dist/docs-search.d.ts +44 -0
  14. package/dist/docs-search.js +187 -0
  15. package/dist/doctor.d.ts +43 -0
  16. package/dist/doctor.js +425 -0
  17. package/dist/env-file.d.ts +25 -0
  18. package/dist/env-file.js +69 -0
  19. package/dist/env-fill.d.ts +43 -0
  20. package/dist/env-fill.js +161 -0
  21. package/dist/env-push.d.ts +37 -0
  22. package/dist/env-push.js +137 -0
  23. package/dist/env-registry.d.ts +49 -0
  24. package/dist/env-registry.js +230 -0
  25. package/dist/exec.d.ts +14 -0
  26. package/dist/exec.js +16 -0
  27. package/dist/fathom-webhook.d.ts +44 -0
  28. package/dist/fathom-webhook.js +123 -0
  29. package/dist/fs-utils.d.ts +9 -0
  30. package/dist/fs-utils.js +34 -0
  31. package/dist/gcp-service-account-key.d.ts +37 -0
  32. package/dist/gcp-service-account-key.js +66 -0
  33. package/dist/gemini-api-key.d.ts +47 -0
  34. package/dist/gemini-api-key.js +132 -0
  35. package/dist/git.d.ts +16 -0
  36. package/dist/git.js +29 -0
  37. package/dist/github-token.d.ts +24 -0
  38. package/dist/github-token.js +30 -0
  39. package/dist/index.d.ts +25 -0
  40. package/dist/index.js +28 -0
  41. package/dist/init.d.ts +47 -0
  42. package/dist/init.js +101 -0
  43. package/dist/linear-project.d.ts +81 -0
  44. package/dist/linear-project.js +192 -0
  45. package/dist/new-client.d.ts +32 -0
  46. package/dist/new-client.js +89 -0
  47. package/dist/ping.d.ts +6 -0
  48. package/dist/ping.js +7 -0
  49. package/dist/portal-admin.d.ts +133 -0
  50. package/dist/portal-admin.js +144 -0
  51. package/dist/sync-templates.d.ts +58 -0
  52. package/dist/sync-templates.js +109 -0
  53. package/dist/template-sync.d.ts +55 -0
  54. package/dist/template-sync.js +90 -0
  55. package/dist/templates.d.ts +19 -0
  56. package/dist/templates.js +24 -0
  57. package/dist/wizard.d.ts +78 -0
  58. package/dist/wizard.js +213 -0
  59. package/package.json +30 -0
  60. package/templates/env.example +60 -0
  61. package/templates/workspace-root/.claude/settings.json +39 -0
  62. package/templates/workspace-root/AGENT.md +205 -0
  63. package/templates/workspace-root/AGENTS.md +11 -0
  64. package/templates/workspace-root/CLAUDE.md +63 -0
  65. package/templates/workspace-root/GEMINI.md +24 -0
  66. package/templates/workspace-root/ONBOARDING.md +164 -0
  67. package/templates/workspace-root/README.md +67 -0
  68. package/templates/workspace-root/skills/CLAUDE.md +79 -0
  69. package/templates/workspace-root/skills/client-deliverables/SKILL.md +131 -0
  70. package/templates/workspace-root/skills/client-deliverables/references/package-layout.md +103 -0
  71. package/templates/workspace-root/skills/client-facing-docs/SKILL.md +131 -0
  72. package/templates/workspace-root/skills/client-facing-docs/references/doc-structures.md +81 -0
  73. package/templates/workspace-root/skills/client-llm-setup/SKILL.md +97 -0
  74. package/templates/workspace-root/skills/client-llm-setup/references/guide-template.md +87 -0
  75. package/templates/workspace-root/skills/client-workflow-diagram/SKILL.md +141 -0
  76. package/templates/workspace-root/skills/client-workflow-diagram/references/excalidraw-format.md +140 -0
  77. package/templates/workspace-root/skills/contract-tech-agnostic/SKILL.md +99 -0
  78. package/templates/workspace-root/skills/contract-tech-agnostic/references/Install_Agent_SOW_Template.docx +0 -0
  79. package/templates/workspace-root/skills/design-system/SKILL.md +118 -0
  80. package/templates/workspace-root/skills/design-system/references/tokens.md +139 -0
  81. package/templates/workspace-root/skills/engagement-spec/SKILL.md +272 -0
  82. package/templates/workspace-root/skills/engagement-spec/references/spec-templates.md +220 -0
  83. package/templates/workspace-root/skills/house-voice/SKILL.md +158 -0
  84. package/templates/workspace-root/skills/house-voice/references/source-copy.md +173 -0
  85. package/templates/workspace-root/skills/ia-cli/SKILL.md +87 -0
  86. package/templates/workspace-root/skills/installagent-brand-kit/SKILL.md +112 -0
  87. package/templates/workspace-root/skills/installagent-brand-kit/assets/installagent-logo.svg +1 -0
  88. package/templates/workspace-root/skills/installagent-brand-kit/assets/installagent-mark.svg +1 -0
  89. package/templates/workspace-root/skills/installagent-brand-kit/references/brand-tokens.md +71 -0
  90. package/templates/workspace-root/skills/installagent-brand-kit/references/branded-pdf.md +66 -0
  91. package/templates/workspace-root/skills/installagent-brand-kit/references/excalidraw-red-theme.md +73 -0
  92. package/templates/workspace-root/skills/installagent-brand-kit/scripts/brand.py +175 -0
  93. package/templates/workspace-root/skills/linear/SKILL.md +186 -0
  94. package/templates/workspace-root/skills/tech-call-prep/SKILL.md +141 -0
@@ -0,0 +1,90 @@
1
+ export declare const N8N_API_URL_ENV = "N8N_API_URL";
2
+ export declare const N8N_API_KEY_ENV = "N8N_API_KEY";
3
+ /** Thrown when the n8n API env pair is missing — half-configured fails closed. */
4
+ export declare class N8nAuthError extends Error {
5
+ }
6
+ export interface SanitizedWorkflow {
7
+ name: string;
8
+ nodes: Array<Record<string, unknown>>;
9
+ connections: Record<string, unknown>;
10
+ settings: Record<string, unknown>;
11
+ }
12
+ export interface StrippedCredential {
13
+ node: string;
14
+ /** n8n credential TYPE (e.g. gmailOAuth2) — never the name or id. */
15
+ type: string;
16
+ }
17
+ /**
18
+ * Reduce a raw n8n workflow payload to the importable core. Everything
19
+ * instance- or client-bound is dropped: ids, timestamps, tags, sharing, meta,
20
+ * pinData/staticData (can embed real client payloads), per-node credentials
21
+ * and webhook ids. Credential TYPES are reported so the manifest can list
22
+ * what a target n8n must provide.
23
+ */
24
+ export declare function sanitizeN8nWorkflow(raw: Record<string, unknown>): {
25
+ workflow: SanitizedWorkflow;
26
+ strippedCredentials: StrippedCredential[];
27
+ };
28
+ export interface AgentBankOptions {
29
+ /** installagent/ workspace root containing agents/; defaults to cwd. */
30
+ workspaceDir?: string;
31
+ }
32
+ export interface SaveAgentTemplateInput {
33
+ workflowId: string;
34
+ /** Bank slug — describes the job, never the client (agents/README.md). */
35
+ template: string;
36
+ }
37
+ export interface SaveAgentTemplateOptions extends AgentBankOptions {
38
+ /** n8n API base incl. /api/v1; defaults to $N8N_API_URL. */
39
+ baseUrl?: string;
40
+ /** Defaults to $N8N_API_KEY. */
41
+ apiKey?: string;
42
+ /** Injectable for tests; defaults to global fetch. */
43
+ fetchImpl?: typeof fetch;
44
+ env?: Record<string, string | undefined>;
45
+ }
46
+ export interface SaveAgentTemplateResult {
47
+ template: string;
48
+ dir: string;
49
+ workflowName: string;
50
+ nodeCount: number;
51
+ strippedCredentials: StrippedCredential[];
52
+ manifestCreated: boolean;
53
+ nextSteps: string[];
54
+ }
55
+ /**
56
+ * Bank a live n8n workflow: fetch by id, sanitize, write
57
+ * agents/<template>/workflow.json (+ template.md scaffold on first save; an
58
+ * existing manifest is never overwritten).
59
+ */
60
+ export declare function saveAgentTemplate(input: SaveAgentTemplateInput, opts?: SaveAgentTemplateOptions): Promise<SaveAgentTemplateResult>;
61
+ export interface AgentTemplateInfo {
62
+ slug: string;
63
+ workflowName: string;
64
+ description: string | null;
65
+ hasManifest: boolean;
66
+ }
67
+ export interface ListAgentTemplatesResult {
68
+ agentsDir: string;
69
+ templates: AgentTemplateInfo[];
70
+ }
71
+ /** Catalog the bank: every agents/<slug>/ dir that holds a workflow.json. */
72
+ export declare function listAgentTemplates(opts?: AgentBankOptions): Promise<ListAgentTemplatesResult>;
73
+ export interface CreateFromTemplateInput {
74
+ template: string;
75
+ /** Where the JSON lands; defaults to the current working directory. */
76
+ destDir?: string;
77
+ }
78
+ export interface CreateFromTemplateResult {
79
+ template: string;
80
+ source: string;
81
+ dest: string;
82
+ workflowName: string;
83
+ nextSteps: string[];
84
+ }
85
+ /**
86
+ * Start a client build from a banked template: copy its workflow.json to
87
+ * <destDir>/<template>.json, ready to import into the client's n8n. Never
88
+ * overwrites.
89
+ */
90
+ export declare function createFromAgentTemplate(input: CreateFromTemplateInput, opts?: AgentBankOptions): Promise<CreateFromTemplateResult>;
@@ -0,0 +1,211 @@
1
+ // The workspace-root agents/ repo is the reusable workflow bank: one dir per
2
+ // template holding a sanitized n8n export (workflow.json) + a human manifest
3
+ // (template.md). See agents/README.md for the conventions. This module is the
4
+ // only writer of that layout — `ia agent save|templates|create` are thin
5
+ // adapters over it.
6
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
7
+ import { join, resolve } from "node:path";
8
+ import { SLUG_PATTERN } from "./new-client.js";
9
+ export const N8N_API_URL_ENV = "N8N_API_URL";
10
+ export const N8N_API_KEY_ENV = "N8N_API_KEY";
11
+ /** Thrown when the n8n API env pair is missing — half-configured fails closed. */
12
+ export class N8nAuthError extends Error {
13
+ }
14
+ /**
15
+ * Reduce a raw n8n workflow payload to the importable core. Everything
16
+ * instance- or client-bound is dropped: ids, timestamps, tags, sharing, meta,
17
+ * pinData/staticData (can embed real client payloads), per-node credentials
18
+ * and webhook ids. Credential TYPES are reported so the manifest can list
19
+ * what a target n8n must provide.
20
+ */
21
+ export function sanitizeN8nWorkflow(raw) {
22
+ const strippedCredentials = [];
23
+ const nodes = (raw.nodes ?? []).map((node) => {
24
+ const { credentials, webhookId: _webhookId, ...keep } = node;
25
+ if (credentials && typeof credentials === "object") {
26
+ for (const type of Object.keys(credentials)) {
27
+ strippedCredentials.push({ node: String(node.name), type });
28
+ }
29
+ }
30
+ return keep;
31
+ });
32
+ return {
33
+ workflow: {
34
+ name: String(raw.name ?? ""),
35
+ nodes,
36
+ connections: raw.connections ?? {},
37
+ settings: raw.settings ?? {},
38
+ },
39
+ strippedCredentials,
40
+ };
41
+ }
42
+ function agentsDir(opts) {
43
+ return resolve(opts.workspaceDir ?? ".", "agents");
44
+ }
45
+ function manifestScaffold(template, workflowName, strippedCredentials) {
46
+ const credLines = strippedCredentials.length > 0
47
+ ? strippedCredentials.map((c) => `- \`${c.type}\` (node: ${c.node})`).join("\n")
48
+ : "- none detected in the export";
49
+ return `# ${template}
50
+
51
+ > Banked from n8n workflow “${workflowName}”. Replace this line with one
52
+ > plain-English paragraph: what the agent does and for whom.
53
+
54
+ ## Required credentials
55
+
56
+ Stripped from workflow.json on save — the target n8n must provide:
57
+
58
+ ${credLines}
59
+
60
+ ## Setup after import
61
+
62
+ - [ ] Recreate the credentials above on the target n8n and reattach to nodes.
63
+ - [ ] Replace client-specific parameter values (search for URLs, ids, names —
64
+ use \`REPLACE_ME_*\` placeholders in the banked copy).
65
+ - [ ] Rename the workflow for the client, activate, register in the portal
66
+ (\`ia portal create-agent\`).
67
+ `;
68
+ }
69
+ /**
70
+ * Bank a live n8n workflow: fetch by id, sanitize, write
71
+ * agents/<template>/workflow.json (+ template.md scaffold on first save; an
72
+ * existing manifest is never overwritten).
73
+ */
74
+ export async function saveAgentTemplate(input, opts = {}) {
75
+ if (!SLUG_PATTERN.test(input.template)) {
76
+ throw new Error(`"${input.template}" is not a valid template slug (lowercase kebab-case, e.g. email-gmail-triage).`);
77
+ }
78
+ const env = opts.env ?? process.env;
79
+ const baseUrl = (opts.baseUrl ?? env[N8N_API_URL_ENV])?.replace(/\/+$/, "");
80
+ const apiKey = opts.apiKey ?? env[N8N_API_KEY_ENV];
81
+ if (!baseUrl || !apiKey) {
82
+ throw new N8nAuthError(`n8n API not configured — set $${N8N_API_URL_ENV} (incl. /api/v1) and $${N8N_API_KEY_ENV} (1Password).`);
83
+ }
84
+ const fetchImpl = opts.fetchImpl ?? fetch;
85
+ const response = await fetchImpl(`${baseUrl}/workflows/${encodeURIComponent(input.workflowId)}`, {
86
+ headers: { "X-N8N-API-KEY": apiKey, accept: "application/json" },
87
+ });
88
+ if (response.status === 404) {
89
+ throw new Error(`No n8n workflow with id "${input.workflowId}" — check the /workflow/<ID> URL.`);
90
+ }
91
+ if (!response.ok) {
92
+ throw new Error(`n8n API ${response.status} fetching workflow ${input.workflowId}`);
93
+ }
94
+ const raw = (await response.json());
95
+ const { workflow, strippedCredentials } = sanitizeN8nWorkflow(raw);
96
+ const dir = join(agentsDir(opts), input.template);
97
+ await mkdir(dir, { recursive: true });
98
+ await writeFile(join(dir, "workflow.json"), `${JSON.stringify(workflow, null, 2)}\n`);
99
+ const manifestPath = join(dir, "template.md");
100
+ let manifestCreated = false;
101
+ try {
102
+ await readFile(manifestPath, "utf8");
103
+ }
104
+ catch {
105
+ await writeFile(manifestPath, manifestScaffold(input.template, workflow.name, strippedCredentials));
106
+ manifestCreated = true;
107
+ }
108
+ return {
109
+ template: input.template,
110
+ dir,
111
+ workflowName: workflow.name,
112
+ nodeCount: workflow.nodes.length,
113
+ strippedCredentials,
114
+ manifestCreated,
115
+ nextSteps: [
116
+ "Review workflow.json for client-specific parameter values (replace with REPLACE_ME_*).",
117
+ manifestCreated
118
+ ? "Fill in the description paragraph in template.md."
119
+ : "template.md already existed — confirm it still matches the export.",
120
+ "Commit the template in the agents/ repo.",
121
+ ],
122
+ };
123
+ }
124
+ /** First plain paragraph line of template.md — the catalog one-liner. */
125
+ function manifestDescription(markdown) {
126
+ for (const line of markdown.split("\n")) {
127
+ const trimmed = line.trim();
128
+ if (!trimmed ||
129
+ trimmed.startsWith("#") ||
130
+ trimmed.startsWith(">") ||
131
+ trimmed.startsWith("<!--"))
132
+ continue;
133
+ return trimmed;
134
+ }
135
+ return null;
136
+ }
137
+ /** Catalog the bank: every agents/<slug>/ dir that holds a workflow.json. */
138
+ export async function listAgentTemplates(opts = {}) {
139
+ const dir = agentsDir(opts);
140
+ let entries;
141
+ try {
142
+ entries = await readdir(dir, { withFileTypes: true });
143
+ }
144
+ catch {
145
+ throw new Error(`No agents/ workflow bank at ${dir} — run from the workspace root or pass --workspace.`);
146
+ }
147
+ const templates = [];
148
+ for (const entry of entries) {
149
+ if (!entry.isDirectory() || entry.name.startsWith("."))
150
+ continue;
151
+ let workflowName;
152
+ try {
153
+ const parsed = JSON.parse(await readFile(join(dir, entry.name, "workflow.json"), "utf8"));
154
+ workflowName = parsed.name ?? entry.name;
155
+ }
156
+ catch {
157
+ continue; // not a template dir
158
+ }
159
+ let description = null;
160
+ let hasManifest = false;
161
+ try {
162
+ description = manifestDescription(await readFile(join(dir, entry.name, "template.md"), "utf8"));
163
+ hasManifest = true;
164
+ }
165
+ catch {
166
+ // manifest missing — listed anyway so `save` gaps are visible
167
+ }
168
+ templates.push({ slug: entry.name, workflowName, description, hasManifest });
169
+ }
170
+ templates.sort((a, b) => a.slug.localeCompare(b.slug));
171
+ return { agentsDir: dir, templates };
172
+ }
173
+ /**
174
+ * Start a client build from a banked template: copy its workflow.json to
175
+ * <destDir>/<template>.json, ready to import into the client's n8n. Never
176
+ * overwrites.
177
+ */
178
+ export async function createFromAgentTemplate(input, opts = {}) {
179
+ const source = join(agentsDir(opts), input.template, "workflow.json");
180
+ let json;
181
+ try {
182
+ json = await readFile(source, "utf8");
183
+ }
184
+ catch {
185
+ const { templates } = await listAgentTemplates(opts).catch(() => ({ templates: [] }));
186
+ const known = templates.map((t) => t.slug).join(", ") || "none banked yet";
187
+ throw new Error(`No template "${input.template}" in the bank (${source}). Known: ${known}.`);
188
+ }
189
+ const workflowName = (JSON.parse(json).name ?? input.template).toString();
190
+ const dest = join(resolve(input.destDir ?? "."), `${input.template}.json`);
191
+ try {
192
+ await writeFile(dest, json, { flag: "wx" });
193
+ }
194
+ catch (error) {
195
+ if (error.code === "EEXIST") {
196
+ throw new Error(`${dest} already exists — move or remove it first.`);
197
+ }
198
+ throw error;
199
+ }
200
+ return {
201
+ template: input.template,
202
+ source,
203
+ dest,
204
+ workflowName,
205
+ nextSteps: [
206
+ "Import the JSON into the client's n8n (Workflows → Import from file).",
207
+ "Recreate credentials and replace REPLACE_ME_* values per the template.md manifest.",
208
+ "Register it for the org: ia portal create-agent (or the portal admin UI).",
209
+ ],
210
+ };
211
+ }
@@ -0,0 +1,50 @@
1
+ import type { ExecFileFn } from "./exec.js";
2
+ export { GITHUB_API_TOKEN_ENV } from "./github-token.js";
3
+ export interface ClientBuildDoc {
4
+ /** Repo-relative path, e.g. "docs/pricing-engine-algorithm.md". */
5
+ path: string;
6
+ /** First `# heading` in the file, falling back to its path. */
7
+ title: string;
8
+ /** Empty for the no-query index; a term-centered excerpt when query matched. */
9
+ snippet: string;
10
+ }
11
+ export interface ClientBuildResult {
12
+ slug: string;
13
+ /** "owner/repo", e.g. "InstallAgent/client-carvision". */
14
+ repo: string;
15
+ query?: string;
16
+ /** Full contents of docs/00-delivery-log.md, or null if the repo has none. */
17
+ deliveryLog: string | null;
18
+ /** Query matches (ranked), or the full doc index when no query was given. */
19
+ docs: ClientBuildDoc[];
20
+ }
21
+ export interface ClientBuildOptions {
22
+ /** Search term(s); omit for a full index of docs/ instead of matches. */
23
+ query?: string;
24
+ /** Max matched docs to return when query is set (default 5). */
25
+ limit?: number;
26
+ /** GitHub token; defaults to $GITHUB_API_TOKEN, then `gh auth token`. */
27
+ token?: string;
28
+ /** Injectable for tests (gh CLI probe); defaults to real execFile. */
29
+ execFileImpl?: ExecFileFn;
30
+ /** Defaults to "InstallAgent". */
31
+ owner?: string;
32
+ /** Defaults to "client-". */
33
+ repoPrefix?: string;
34
+ /** Injectable for tests; defaults to global fetch. */
35
+ fetchImpl?: typeof fetch;
36
+ }
37
+ /** Thrown when the GitHub token is missing or rejected. */
38
+ export declare class ClientBuildAuthError extends Error {
39
+ }
40
+ /**
41
+ * Read-only slice of a client's GitHub build repo (InstallAgent/client-<slug>)
42
+ * via the GitHub contents API — never clones. Returns the delivery log in
43
+ * full plus either doc matches for `query` or a full docs/ index when no
44
+ * query is given. This is the "what are we building / what shipped" source,
45
+ * complementing clientContext's registry brief (team-tools/docs/
46
+ * agent-context-sources-plan.md, track ②).
47
+ *
48
+ * Strictly read-only. Never touches the registry or Airtable.
49
+ */
50
+ export declare function clientBuild(slug: string, options?: ClientBuildOptions): Promise<ClientBuildResult>;
@@ -0,0 +1,155 @@
1
+ import { GITHUB_TOKEN_FIX, resolveGithubToken } from "./github-token.js";
2
+ import { SLUG_PATTERN } from "./new-client.js";
3
+ export { GITHUB_API_TOKEN_ENV } from "./github-token.js";
4
+ const GITHUB_API_BASE_URL = "https://api.github.com";
5
+ const DEFAULT_OWNER = "InstallAgent";
6
+ const DEFAULT_REPO_PREFIX = "client-";
7
+ const DEFAULT_QUERY_LIMIT = 5;
8
+ const FETCH_CONCURRENCY = 6;
9
+ const DELIVERY_LOG_PATH = "docs/00-delivery-log.md";
10
+ /** Thrown when the GitHub token is missing or rejected. */
11
+ export class ClientBuildAuthError extends Error {
12
+ }
13
+ /**
14
+ * Read-only slice of a client's GitHub build repo (InstallAgent/client-<slug>)
15
+ * via the GitHub contents API — never clones. Returns the delivery log in
16
+ * full plus either doc matches for `query` or a full docs/ index when no
17
+ * query is given. This is the "what are we building / what shipped" source,
18
+ * complementing clientContext's registry brief (team-tools/docs/
19
+ * agent-context-sources-plan.md, track ②).
20
+ *
21
+ * Strictly read-only. Never touches the registry or Airtable.
22
+ */
23
+ export async function clientBuild(slug, options = {}) {
24
+ if (slug.startsWith("client-")) {
25
+ throw new Error(`pass the bare slug ("${slug.slice("client-".length)}"), not "${slug}" — the repo prefix is added for you`);
26
+ }
27
+ if (!SLUG_PATTERN.test(slug)) {
28
+ throw new Error(`invalid slug "${slug}" — use lowercase letters, digits, and hyphens`);
29
+ }
30
+ const resolved = await resolveGithubToken({
31
+ token: options.token,
32
+ execFileImpl: options.execFileImpl,
33
+ });
34
+ if (!resolved) {
35
+ throw new ClientBuildAuthError(`GitHub auth required — ${GITHUB_TOKEN_FIX}`);
36
+ }
37
+ const { token, source: tokenSource } = resolved;
38
+ const owner = options.owner ?? DEFAULT_OWNER;
39
+ const repo = `${options.repoPrefix ?? DEFAULT_REPO_PREFIX}${slug}`;
40
+ const fullRepo = `${owner}/${repo}`;
41
+ const fetchImpl = options.fetchImpl ?? fetch;
42
+ const headers = {
43
+ Authorization: `Bearer ${token}`,
44
+ Accept: "application/vnd.github+json",
45
+ "X-GitHub-Api-Version": "2022-11-28",
46
+ };
47
+ async function getContents(path) {
48
+ const res = await fetchImpl(`${GITHUB_API_BASE_URL}/repos/${fullRepo}/contents/${path}`, {
49
+ headers,
50
+ });
51
+ if (res.status === 404)
52
+ return undefined;
53
+ if (res.status === 401 || res.status === 403) {
54
+ throw new ClientBuildAuthError(`GitHub rejected the ${tokenSource} token reading ${fullRepo}/${path} (HTTP ${res.status}) — ` +
55
+ `check it is valid and can read ${fullRepo}.`);
56
+ }
57
+ if (!res.ok) {
58
+ throw new Error(`GET ${fullRepo}/${path} failed: HTTP ${res.status}`);
59
+ }
60
+ return (await res.json());
61
+ }
62
+ async function getFile(path) {
63
+ const data = await getContents(path);
64
+ if (!data || Array.isArray(data) || data.type !== "file" || !data.content)
65
+ return null;
66
+ return Buffer.from(data.content, data.encoding ?? "base64").toString("utf8");
67
+ }
68
+ async function listMarkdownFiles(dir) {
69
+ const data = await getContents(dir);
70
+ if (!data || !Array.isArray(data))
71
+ return [];
72
+ const paths = [];
73
+ const subdirs = [];
74
+ for (const entry of data) {
75
+ if (entry.type === "file" && entry.name.endsWith(".md"))
76
+ paths.push(entry.path);
77
+ else if (entry.type === "dir")
78
+ subdirs.push(entry.path);
79
+ }
80
+ for (const subdir of subdirs) {
81
+ paths.push(...(await listMarkdownFiles(subdir)));
82
+ }
83
+ return paths;
84
+ }
85
+ const deliveryLog = await getFile(DELIVERY_LOG_PATH);
86
+ const docPaths = (await listMarkdownFiles("docs")).filter((path) => path !== DELIVERY_LOG_PATH);
87
+ const docs = [];
88
+ for (let i = 0; i < docPaths.length; i += FETCH_CONCURRENCY) {
89
+ const chunk = await Promise.all(docPaths.slice(i, i + FETCH_CONCURRENCY).map(async (path) => {
90
+ const content = await getFile(path);
91
+ return content !== null ? { path, content } : undefined;
92
+ }));
93
+ for (const doc of chunk) {
94
+ if (doc)
95
+ docs.push(doc);
96
+ }
97
+ }
98
+ const query = options.query?.trim();
99
+ if (!query) {
100
+ return {
101
+ slug,
102
+ repo: fullRepo,
103
+ deliveryLog,
104
+ docs: docs
105
+ .map((doc) => ({ path: doc.path, title: titleOf(doc), snippet: "" }))
106
+ .sort((a, b) => a.path.localeCompare(b.path)),
107
+ };
108
+ }
109
+ const limit = options.limit ?? DEFAULT_QUERY_LIMIT;
110
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
111
+ const matches = docs
112
+ .map((doc) => {
113
+ const text = doc.content.toLowerCase();
114
+ const title = titleOf(doc).toLowerCase();
115
+ let score = 0;
116
+ for (const term of terms) {
117
+ score += countOccurrences(text, term) + countOccurrences(title, term) * 5;
118
+ }
119
+ return { doc, score };
120
+ })
121
+ .filter((entry) => entry.score > 0)
122
+ .sort((a, b) => b.score - a.score)
123
+ .slice(0, limit);
124
+ return {
125
+ slug,
126
+ repo: fullRepo,
127
+ query,
128
+ deliveryLog,
129
+ docs: matches.map(({ doc }) => ({
130
+ path: doc.path,
131
+ title: titleOf(doc),
132
+ snippet: makeSnippet(doc.content, terms),
133
+ })),
134
+ };
135
+ }
136
+ function titleOf(doc) {
137
+ return doc.content.match(/^#\s+(.+)$/m)?.[1].trim() ?? doc.path;
138
+ }
139
+ function countOccurrences(text, term) {
140
+ return term ? text.split(term).length - 1 : 0;
141
+ }
142
+ function makeSnippet(text, terms) {
143
+ const lower = text.toLowerCase();
144
+ let first = -1;
145
+ for (const term of terms) {
146
+ const idx = lower.indexOf(term);
147
+ if (idx !== -1 && (first === -1 || idx < first))
148
+ first = idx;
149
+ }
150
+ if (first === -1)
151
+ return text.slice(0, 160).trim();
152
+ const start = Math.max(0, first - 60);
153
+ const end = Math.min(text.length, first + 100);
154
+ return `${start > 0 ? "…" : ""}${text.slice(start, end).trim()}${end < text.length ? "…" : ""}`;
155
+ }
@@ -0,0 +1,40 @@
1
+ export interface ClientCall {
2
+ /** ISO date parsed from the filename. */
3
+ date: string;
4
+ /** Filename inside calls/. */
5
+ file: string;
6
+ content: string;
7
+ }
8
+ export interface ClientContextOptions {
9
+ /** The installagent/ workspace root (the dir that contains team-clients/). */
10
+ workspaceDir: string;
11
+ /** How many of the most recent call notes to include in full (default 5). */
12
+ maxCalls?: number;
13
+ }
14
+ export interface ClientContextResult {
15
+ slug: string;
16
+ /** Absolute path of the registry folder the brief was read from. */
17
+ registryDir: string;
18
+ /** Full PROFILE.md — the client's synthesized intake identity. */
19
+ profile: string;
20
+ /** Most recent call notes, newest first, capped at maxCalls. */
21
+ calls: ClientCall[];
22
+ /** Total call notes on record (may exceed calls.length). */
23
+ totalCalls: number;
24
+ /**
25
+ * docs/00-delivery-log.md from the local clients/client-<slug>/ build repo,
26
+ * when that repo is checked out — answers "what shipped". Null otherwise.
27
+ */
28
+ deliveryLog: string | null;
29
+ }
30
+ /**
31
+ * Read-only client brief from the team-clients registry: PROFILE.md + the
32
+ * most recent call notes, plus the build repo's delivery log when it's
33
+ * checked out locally. This is the one-call "who is this client and where
34
+ * do things stand" context for humans and agents alike.
35
+ *
36
+ * Strictly read-only — this operation never writes to the registry (PII
37
+ * rules live in team-clients/AGENT.md) and never touches Airtable. The
38
+ * registry data it returns is internal; don't paste it outside team surfaces.
39
+ */
40
+ export declare function clientContext(slug: string, options: ClientContextOptions): Promise<ClientContextResult>;
@@ -0,0 +1,70 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { SLUG_PATTERN } from "./new-client.js";
5
+ /** Call-note files are ISO-dated: YYYY-MM-DD.md or YYYY-MM-DD-<hint>.md. */
6
+ const CALL_FILE = /^(\d{4}-\d{2}-\d{2})[^/]*\.md$/;
7
+ /**
8
+ * Read-only client brief from the team-clients registry: PROFILE.md + the
9
+ * most recent call notes, plus the build repo's delivery log when it's
10
+ * checked out locally. This is the one-call "who is this client and where
11
+ * do things stand" context for humans and agents alike.
12
+ *
13
+ * Strictly read-only — this operation never writes to the registry (PII
14
+ * rules live in team-clients/AGENT.md) and never touches Airtable. The
15
+ * registry data it returns is internal; don't paste it outside team surfaces.
16
+ */
17
+ export async function clientContext(slug, options) {
18
+ if (slug.startsWith("client-")) {
19
+ throw new Error(`pass the bare slug ("${slug.slice("client-".length)}"), not "${slug}" — registry folders are unprefixed`);
20
+ }
21
+ if (!SLUG_PATTERN.test(slug)) {
22
+ throw new Error(`invalid slug "${slug}" — use lowercase letters, digits, and hyphens`);
23
+ }
24
+ const workspaceDir = resolve(options.workspaceDir);
25
+ const registryRoot = join(workspaceDir, "team-clients", "clients");
26
+ if (!existsSync(registryRoot)) {
27
+ throw new Error(`${registryRoot} not found — clone team-clients first (\`ia init\` sets it up)`);
28
+ }
29
+ const registryDir = join(registryRoot, slug);
30
+ if (!existsSync(registryDir)) {
31
+ const known = (await readdir(registryRoot, { withFileTypes: true }))
32
+ .filter((entry) => entry.isDirectory())
33
+ .map((entry) => entry.name)
34
+ .sort();
35
+ throw new Error(`no registry entry for "${slug}" in team-clients/clients/. Known slugs: ${known.join(", ")}`);
36
+ }
37
+ const profilePath = join(registryDir, "PROFILE.md");
38
+ if (!existsSync(profilePath)) {
39
+ throw new Error(`${profilePath} is missing — registry entry is malformed`);
40
+ }
41
+ const profile = await readFile(profilePath, "utf8");
42
+ const callsDir = join(registryDir, "calls");
43
+ let callFiles = [];
44
+ if (existsSync(callsDir)) {
45
+ callFiles = (await readdir(callsDir))
46
+ .map((file) => {
47
+ const match = file.match(CALL_FILE);
48
+ return match ? { date: match[1], file } : undefined;
49
+ })
50
+ .filter((entry) => entry !== undefined)
51
+ // Filenames are ISO-dated, so lexicographic sort is chronological.
52
+ .sort((a, b) => b.file.localeCompare(a.file));
53
+ }
54
+ const maxCalls = options.maxCalls ?? 5;
55
+ const calls = await Promise.all(callFiles.slice(0, maxCalls).map(async ({ date, file }) => ({
56
+ date,
57
+ file,
58
+ content: await readFile(join(callsDir, file), "utf8"),
59
+ })));
60
+ const deliveryLogPath = join(workspaceDir, "clients", `client-${slug}`, "docs", "00-delivery-log.md");
61
+ const deliveryLog = existsSync(deliveryLogPath) ? await readFile(deliveryLogPath, "utf8") : null;
62
+ return {
63
+ slug,
64
+ registryDir,
65
+ profile,
66
+ calls,
67
+ totalCalls: callFiles.length,
68
+ deliveryLog,
69
+ };
70
+ }
@@ -0,0 +1,67 @@
1
+ export declare const AIRTABLE_API_TOKEN_ENV = "AIRTABLE_API_TOKEN";
2
+ export declare const GOOGLE_SERVICE_ACCOUNT_KEY_ENV = "GOOGLE_SERVICE_ACCOUNT_KEY";
3
+ /** Thrown when the Airtable token or Google service-account key is missing or rejected. */
4
+ export declare class ClientDriveAuthError extends Error {
5
+ }
6
+ export interface ClientDriveDoc {
7
+ /** Slash-joined subfolder names + filename, e.g. "calls/Call — Acme — 2026-07-01.gdoc". */
8
+ path: string;
9
+ title: string;
10
+ mimeType: string;
11
+ /** Empty for the no-query index, or a non-Doc file that can't be text-exported. */
12
+ snippet: string;
13
+ }
14
+ export interface ClientDriveSearchResult {
15
+ slug: string;
16
+ /** The client's Drive folder, as recorded in Airtable. */
17
+ folderUrl: string;
18
+ query?: string;
19
+ /** Query matches (ranked), or the full file index when no query is given. */
20
+ docs: ClientDriveDoc[];
21
+ }
22
+ export interface ClientDriveSearchOptions {
23
+ /** Search term(s); omit for a full index of the folder instead of matches. */
24
+ query?: string;
25
+ /** Max matched files to return when query is set (default 5). */
26
+ limit?: number;
27
+ /** Airtable PAT; defaults to $AIRTABLE_API_TOKEN. */
28
+ airtableToken?: string;
29
+ /** Google service-account key JSON (raw string); defaults to $GOOGLE_SERVICE_ACCOUNT_KEY. */
30
+ serviceAccountKey?: string;
31
+ airtableBaseId?: string;
32
+ airtableTableId?: string;
33
+ /** Injectable for tests; defaults to global fetch. Used for every HTTP call (Airtable, Google token, Drive). */
34
+ fetchImpl?: typeof fetch;
35
+ /** Injectable clock for JWT iat/exp; defaults to Date.now. */
36
+ now?: () => number;
37
+ }
38
+ /**
39
+ * Parse a service-account key JSON blob into the two fields the JWT grant
40
+ * needs. Exported for direct unit testing (mirrors the equivalent helper in
41
+ * team-web/apps/portal/lib/drive/google-auth.ts — same idea, not shared code:
42
+ * different repos never cross-import here).
43
+ */
44
+ export declare function parseServiceAccountKey(raw: string): {
45
+ clientEmail: string;
46
+ privateKey: string;
47
+ };
48
+ /** Exported for direct unit testing of the claim shape. */
49
+ export declare function buildAssertionClaims(clientEmail: string, nowMs: number): {
50
+ iss: string;
51
+ scope: string;
52
+ aud: string;
53
+ iat: number;
54
+ exp: number;
55
+ };
56
+ /**
57
+ * Read-only slice of a client's Google Drive folder (call transcripts,
58
+ * deliverables) — resolved via the client's Airtable "Google Drive" link,
59
+ * never guessed. This is the richest, heaviest of the three client context
60
+ * sources (docs/agent-context-sources-plan.md, track ③); complements
61
+ * client_context's registry brief and client_build's GitHub repo slice.
62
+ *
63
+ * Only Google Docs are text-exported and content-scored (transcripts and
64
+ * deliverables are Docs in practice); other file types are listed by name
65
+ * only. Strictly read-only. Never writes to Airtable or Drive.
66
+ */
67
+ export declare function clientDriveSearch(slug: string, options?: ClientDriveSearchOptions): Promise<ClientDriveSearchResult>;