@aidenhq/sdk 0.1.0 → 0.2.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,226 @@
1
+ // Shared sources (docs/design/sources.md): the writer side. Each source writer (slack-live,
2
+ // github, jira, ops-mcp for meetings, google-workspace for docs) logs in to the warehouse as src_<source>, owns schema src_<source> (ops/warehouse-sources.sh
3
+ // creates both) and writes through this: typed upserts that keep first_seen_at, bump src_meta.seq on any difference and
4
+ // log tracked-field changes, a baseline flag for first syncs, per-scope sync state, and one src_meta.ingest_run per pass.
5
+ // No LLM anywhere: ingest is code.
6
+ //
7
+ // Writers import it as @aidenhq/sdk/source-store (pg is theirs: a peer dependency).
8
+ import { readFileSync } from "node:fs";
9
+ import pg from "pg";
10
+ /** Long text is cut to about 4 KB by default; the row keeps a <field>_truncated flag and its url for the rest. */
11
+ const TEXT_CAP = 4096;
12
+ /** Text cut to `cap` bytes (whole characters), NULs dropped (Postgres text can't hold them). */
13
+ export function capText(s, cap = TEXT_CAP) {
14
+ if (s == null)
15
+ return { text: null, truncated: false };
16
+ const clean = s.replace(/\u0000/g, "");
17
+ const buf = Buffer.from(clean, "utf8");
18
+ if (buf.length <= cap)
19
+ return { text: clean, truncated: false };
20
+ return { text: buf.subarray(0, cap).toString("utf8").replace(/�+$/, ""), truncated: true };
21
+ }
22
+ /** People in a source, keyed by the source's own id: consumers resolve people by id, never by a model-read name. */
23
+ export const USERS = { name: "users", key: ["user_id"], cols: { user_id: "text", handle: "text", display_name: "text", email: "text", is_bot: "boolean" }, tracked: [] };
24
+ const ident = (s) => {
25
+ if (!/^[a-z_][a-z0-9_]*$/.test(s))
26
+ throw new Error(`bad identifier ${s}`);
27
+ return s;
28
+ };
29
+ /** CREATE TABLE for a source table: its columns plus the common ones every source row carries. */
30
+ export function tableDdl(schema, t) {
31
+ const cols = Object.entries(t.cols).map(([c, type]) => ` ${ident(c)} ${type}${t.key.includes(c) ? " NOT NULL" : ""}`);
32
+ // 'simple': no stemming or stop words, so product names, codes and handles match as written.
33
+ const tsv = t.search?.length ? ` tsv tsvector GENERATED ALWAYS AS (to_tsvector('simple', ${t.search.map((c) => `coalesce(${ident(c)}, '')`).join(" || ' ' || ")})) STORED,\n` : "";
34
+ return `CREATE TABLE IF NOT EXISTS ${ident(schema)}.${ident(t.name)} (
35
+ ${cols.join(",\n")},
36
+ ${tsv} baseline boolean NOT NULL DEFAULT false,
37
+ first_seen_at timestamptz NOT NULL DEFAULT now(),
38
+ ingested_at timestamptz NOT NULL DEFAULT now(),
39
+ seq bigint NOT NULL DEFAULT nextval('src_meta.seq'),
40
+ PRIMARY KEY (${t.key.map(ident).join(", ")})
41
+ );
42
+ CREATE INDEX IF NOT EXISTS ${t.name}_seq ON ${schema}.${t.name} (seq);${tsv ? `\nCREATE INDEX IF NOT EXISTS ${t.name}_tsv ON ${schema}.${t.name} USING gin (tsv);` : ""}`;
43
+ }
44
+ /** Per-scope sync state and the change log: in every source schema. */
45
+ function commonDdl(schema) {
46
+ const s = ident(schema);
47
+ return `CREATE TABLE IF NOT EXISTS ${s}.scope (
48
+ scope text PRIMARY KEY,
49
+ baselined_at timestamptz,
50
+ cursor text,
51
+ updated_at timestamptz NOT NULL DEFAULT now()
52
+ );
53
+ CREATE TABLE IF NOT EXISTS ${s}.change (
54
+ seq bigint PRIMARY KEY DEFAULT nextval('src_meta.seq'),
55
+ entity text NOT NULL,
56
+ entity_id text NOT NULL,
57
+ scope text,
58
+ field text NOT NULL,
59
+ old_value text,
60
+ new_value text,
61
+ url text,
62
+ observed_at timestamptz NOT NULL DEFAULT now()
63
+ );
64
+ CREATE INDEX IF NOT EXISTS change_entity ON ${s}.change (entity, entity_id);`;
65
+ }
66
+ const asText = (v) => (v == null ? null : typeof v === "string" ? v : v instanceof Date ? v.toISOString() : JSON.stringify(v));
67
+ const capped = (v) => capText(asText(v)).text;
68
+ export class SourceStore {
69
+ schema;
70
+ pool;
71
+ migrated = false;
72
+ constructor(schema, pool) {
73
+ this.schema = schema;
74
+ this.pool = pool;
75
+ ident(schema);
76
+ }
77
+ /**
78
+ * The writer's store, or undefined while it can't be (no password file: the warehouse module or its secret is missing).
79
+ * WAREHOUSE_HOST defaults to the warehouse app's container, reached on the `sources` network (compose.yaml), which no app joins.
80
+ */
81
+ static fromEnv(source, env = process.env) {
82
+ const file = env.WAREHOUSE_PASSWORD_FILE;
83
+ let password = "";
84
+ try {
85
+ password = file ? readFileSync(file, "utf8").trim() : "";
86
+ }
87
+ catch {
88
+ return undefined;
89
+ }
90
+ if (!password)
91
+ return undefined;
92
+ const role = `src_${source}`;
93
+ const pool = new pg.Pool({ host: env.WAREHOUSE_HOST || "app-warehouse-postgres-1", port: Number(env.WAREHOUSE_PORT || 5432), database: "warehouse", user: role, password, max: 3, connectionTimeoutMillis: 10_000, statement_timeout: 60_000 });
94
+ pool.on("error", () => undefined); // idle-client errors surface on the next query
95
+ return new SourceStore(role, pool);
96
+ }
97
+ /** Runs the writer's DDL once per process, serialised across processes by an advisory lock. */
98
+ async migrate(ddl) {
99
+ if (this.migrated)
100
+ return;
101
+ const c = await this.pool.connect();
102
+ try {
103
+ await c.query("SELECT pg_advisory_lock(hashtext($1))", [this.schema]);
104
+ try {
105
+ await c.query(`${commonDdl(this.schema)}\n${ddl}`);
106
+ }
107
+ finally {
108
+ await c.query("SELECT pg_advisory_unlock(hashtext($1))", [this.schema]);
109
+ }
110
+ this.migrated = true;
111
+ }
112
+ finally {
113
+ c.release();
114
+ }
115
+ }
116
+ async scope(scope) {
117
+ const r = await this.pool.query(`SELECT baselined_at, cursor FROM ${this.schema}.scope WHERE scope = $1`, [scope]);
118
+ return { baselined: !!r.rows[0]?.baselined_at, cursor: r.rows[0]?.cursor ?? null };
119
+ }
120
+ /** Every scope whose name starts with `prefix`, with when it was last saved (epoch ms): lets a pass pick the oldest-synced first. */
121
+ async scopesByPrefix(prefix) {
122
+ const r = await this.pool.query(`SELECT scope, baselined_at, cursor, updated_at FROM ${this.schema}.scope WHERE starts_with(scope, $1)`, [prefix]);
123
+ return new Map(r.rows.map((x) => [x.scope, { baselined: !!x.baselined_at, cursor: x.cursor ?? null, syncedAt: new Date(x.updated_at).getTime() }]));
124
+ }
125
+ /** Saves a scope's cursor; `baselined` marks its first full pass done (only after it completed). */
126
+ async saveScope(scope, cursor, baselined = false) {
127
+ await this.pool.query(`INSERT INTO ${this.schema}.scope (scope, cursor, baselined_at) VALUES ($1, $2, CASE WHEN $3 THEN now() END)
128
+ ON CONFLICT (scope) DO UPDATE SET cursor = COALESCE(EXCLUDED.cursor, ${this.schema}.scope.cursor),
129
+ baselined_at = COALESCE(${this.schema}.scope.baselined_at, EXCLUDED.baselined_at), updated_at = now()`, [scope, cursor, baselined]);
130
+ }
131
+ /**
132
+ * Insert or update one row by its key. New rows carry `baseline`; an existing row is rewritten only when a written
133
+ * column differs (seq and ingested_at bumped), and its tracked differences go to the change log unless `baseline`.
134
+ */
135
+ async upsert(t, row, o) {
136
+ for (let attempt = 0;; attempt++) {
137
+ const c = await this.pool.connect();
138
+ try {
139
+ await c.query("BEGIN");
140
+ const r = await this.upsertIn(c, t, row, o.baseline);
141
+ await c.query("COMMIT");
142
+ return r;
143
+ }
144
+ catch (err) {
145
+ await c.query("ROLLBACK").catch(() => undefined);
146
+ // Two writers inserted the same new row at once: the second retries as an update.
147
+ if (err.code === "23505" && attempt === 0)
148
+ continue;
149
+ throw err;
150
+ }
151
+ finally {
152
+ c.release();
153
+ }
154
+ }
155
+ }
156
+ async upsertIn(c, t, row, baseline) {
157
+ const s = this.schema;
158
+ const cols = Object.keys(t.cols).filter((k) => k in row);
159
+ const vals = cols.map((k) => (t.cols[k] === "jsonb" && row[k] != null ? JSON.stringify(row[k]) : row[k]));
160
+ const typed = cols.map((k, i) => `$${i + 1}::${t.cols[k]} AS ${ident(k)}`).join(", ");
161
+ const on = t.key.map((k) => `o.${ident(k)} = n.${ident(k)}`).join(" AND ");
162
+ const diff = cols.filter((k) => !t.key.includes(k)).map((k) => `(o.${k} IS DISTINCT FROM n.${k}) AS "d_${k}", o.${k} AS "o_${k}"`);
163
+ const q = `WITH n AS (SELECT ${typed}) SELECT true AS found${diff.length ? `, ${diff.join(", ")}` : ""}
164
+ FROM n JOIN ${s}.${t.name} o ON ${on} FOR UPDATE OF o`;
165
+ const cur = (await c.query(q, vals)).rows[0];
166
+ if (!cur) {
167
+ const names = [...cols, "baseline"].map(ident).join(", ");
168
+ await c.query(`INSERT INTO ${s}.${t.name} (${names}) VALUES (${cols.map((k, i) => `$${i + 1}::${t.cols[k]}`).join(", ")}, $${cols.length + 1})`, [...vals, baseline]);
169
+ return "new";
170
+ }
171
+ const changed = cols.filter((k) => cur[`d_${k}`]);
172
+ if (!changed.length)
173
+ return "same";
174
+ const keyVals = t.key.map((k) => row[k]);
175
+ // Only the parameters this statement uses (Postgres can't type an unused one).
176
+ const used = [...changed, ...t.key];
177
+ const sets = changed.map((k, i) => `${ident(k)} = $${i + 1}::${t.cols[k]}`).join(", ");
178
+ const where = t.key.map((k, i) => `${ident(k)} = $${changed.length + i + 1}::${t.cols[k]}`).join(" AND ");
179
+ // A row that changes after its baseline is no longer baseline: it is a recent change.
180
+ await c.query(`UPDATE ${s}.${t.name} SET ${sets},${baseline ? "" : " baseline = false,"} ingested_at = now(), seq = nextval('src_meta.seq') WHERE ${where}`, used.map((k) => vals[cols.indexOf(k)]));
181
+ if (baseline)
182
+ return "changed";
183
+ const entityId = keyVals.map(String).join("/");
184
+ const scope = t.scope ? asText(row[t.scope]) : null;
185
+ const url = t.url ? asText(row[t.url]) : null;
186
+ for (const k of changed.filter((f) => t.tracked.includes(f))) {
187
+ const pairs = t.cols[k] === "jsonb"
188
+ ? jsonDiff(cur[`o_${k}`], row[k]).map(([sub, a, b]) => [`${k}.${sub}`, a, b])
189
+ : [[k, cur[`o_${k}`], row[k]]];
190
+ for (const [field, a, b] of pairs)
191
+ await c.query(`INSERT INTO ${s}.change (entity, entity_id, scope, field, old_value, new_value, url) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [t.name, entityId, scope, field, capped(a), capped(b), url]);
192
+ }
193
+ return "changed";
194
+ }
195
+ /**
196
+ * One ingest pass: records src_meta.ingest_run (rows = rows written with a difference) and rethrows a failure.
197
+ * `commit` is the git HEAD a repo target was read at, when the pass covers a checkout.
198
+ */
199
+ async run(source, scope, fn, meta = {}) {
200
+ const started = new Date();
201
+ let rows = 0;
202
+ let error = null;
203
+ try {
204
+ rows = await fn();
205
+ return rows;
206
+ }
207
+ catch (err) {
208
+ error = String(err.message ?? err).slice(0, 500);
209
+ throw err;
210
+ }
211
+ finally {
212
+ await this.pool
213
+ .query(`INSERT INTO src_meta.ingest_run (source, scope, started_at, rows, error, commit) VALUES ($1, $2, $3, $4, $5, $6)`, [source, scope, started, rows, error, meta.commit || null])
214
+ .catch(() => undefined);
215
+ }
216
+ }
217
+ }
218
+ /** Top-level keys of two JSON objects whose values differ: [key, old, new]. */
219
+ function jsonDiff(a, b) {
220
+ const o = (a && typeof a === "object" ? a : {});
221
+ const n = (b && typeof b === "object" ? b : {});
222
+ const keys = [...new Set([...Object.keys(o), ...Object.keys(n)])].sort();
223
+ return keys.filter((k) => stable(o[k] ?? null) !== stable(n[k] ?? null)).map((k) => [k, o[k] ?? null, n[k] ?? null]);
224
+ }
225
+ /** JSON with object keys sorted (jsonb returns keys in its own order). */
226
+ const stable = (v) => Array.isArray(v) ? `[${v.map(stable).join(",")}]` : v && typeof v === "object" ? `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable(v[k])}`).join(",")}}` : JSON.stringify(v);
@@ -0,0 +1,93 @@
1
+ /** A module's `providers.executor` (spec §3.3.2): its write kinds' executor endpoint and the secret the kernel calls it with. */
2
+ export interface ExecutorDecl {
3
+ contract: "executor@1";
4
+ url: string;
5
+ auth: string;
6
+ }
7
+ /** A module's `providers.reviewer` (spec §3.3.3; reviewer.ts): its review endpoint and the secret the kernel calls it with. */
8
+ export interface ReviewerDecl {
9
+ contract: "reviewer@1";
10
+ url: string;
11
+ auth: string;
12
+ }
13
+ export interface Caller {
14
+ agent: string;
15
+ roles: string[];
16
+ task?: string;
17
+ run?: string;
18
+ job?: string;
19
+ module?: string;
20
+ }
21
+ export interface CardText {
22
+ sentence: string;
23
+ changes: string;
24
+ reads: string;
25
+ cost: string;
26
+ tier: 0 | 1 | 2;
27
+ panel: boolean;
28
+ kind: string;
29
+ digest: string;
30
+ requester: string;
31
+ task: string;
32
+ }
33
+ export interface JobSpec {
34
+ contract: "engine@1";
35
+ job: string;
36
+ agent: string;
37
+ task: string;
38
+ prompt: string;
39
+ session?: string;
40
+ model: {
41
+ base_url: string;
42
+ token_env: string;
43
+ id: string;
44
+ effort: string;
45
+ };
46
+ mcp: {
47
+ name: string;
48
+ url: string;
49
+ token_env: "AIDENHQ_JOB_TOKEN";
50
+ tool_timeout_s?: number;
51
+ }[];
52
+ env: string[];
53
+ limits: {
54
+ timeout_s: number;
55
+ };
56
+ web: boolean;
57
+ state?: string;
58
+ sandbox: {
59
+ kind: "bwrap" | "box";
60
+ writable: string[];
61
+ network: boolean;
62
+ };
63
+ }
64
+ export type EngineEvent = {
65
+ t: "progress";
66
+ text: string;
67
+ plan?: {
68
+ step: string;
69
+ done: boolean;
70
+ doing?: boolean;
71
+ }[];
72
+ steps?: {
73
+ at: string;
74
+ text: string;
75
+ }[];
76
+ } | {
77
+ t: "usage";
78
+ input: number;
79
+ output: number;
80
+ cached?: number;
81
+ model: string;
82
+ } | {
83
+ t: "session";
84
+ id: string;
85
+ } | {
86
+ t: "final";
87
+ text: string;
88
+ };
89
+ export interface InboxLine {
90
+ t: "comment";
91
+ from: string;
92
+ text: string;
93
+ }
package/dist/src/types.js CHANGED
@@ -1,34 +1,4 @@
1
1
  // The public contract types (spec §3.3.1). engine@1 minor additions are marked "minor": optional for engines, always
2
2
  // written by the runner.
3
-
4
- /** A module's `providers.executor` (spec §3.3.2): its write kinds' executor endpoint and the secret the kernel calls it with. */
5
-
6
- /** A module's `providers.reviewer` (spec §3.3.3; reviewer.ts): its review endpoint and the secret the kernel calls it with. */
7
-
8
-
9
-
10
-
11
-
12
-
13
- // job dir (read-write for the engine), the task folder is the engine's working directory
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
- // <job dir>/inbox.jsonl, appended by the runner: { t: "comment"; from: string; text: string } (only if live_input)
33
-
3
+ export {};
34
4
  // exit code: 0 = turn done; non-zero = failed (the runner reports, the requesting module decides retries)
@@ -0,0 +1,85 @@
1
+ /** Sign-in state for the board's banner and the healthcheck; `none`: the connection signs in to nothing. */
2
+ export interface AuthStatus {
3
+ state: "missing" | "ok" | "expired" | "unknown" | "none";
4
+ since: string;
5
+ detail?: string;
6
+ /** The scopes the vendor granted at the last sign-in. */
7
+ scope?: string;
8
+ }
9
+ export declare class AuthError extends Error {
10
+ }
11
+ export declare class SignInError extends Error {
12
+ }
13
+ /** The board's sign-in: which scopes the owner may pick (and the ones pre-selected), then the round trip. */
14
+ export interface SignInFlow {
15
+ scopes(): Promise<{
16
+ supported: string[];
17
+ recommended: string[];
18
+ }>;
19
+ start(redirectUri: string, scopes?: string[]): Promise<{
20
+ url: string;
21
+ }>;
22
+ finish(state: string, code: string): Promise<void>;
23
+ }
24
+ /** What the proxy needs from a sign-in: the headers for an upstream request, a refresh after a refusal, and its state. */
25
+ export interface Auth {
26
+ headers(): Promise<Record<string, string>>;
27
+ refresh(): Promise<void>;
28
+ status(): AuthStatus;
29
+ mark(state: "ok" | "expired", detail?: string): void;
30
+ signedIn(): boolean;
31
+ signIn?: SignInFlow;
32
+ }
33
+ /** A connection that signs in to nothing (a local server), with fixed headers. */
34
+ export declare function staticAuth(headers?: Record<string, string>): Auth;
35
+ export interface OAuthOptions {
36
+ /** The vendor's name in messages ("Glean"). */
37
+ name: string;
38
+ mcpUrl: string;
39
+ /** token.json and client.json live here. */
40
+ stateDir: string;
41
+ /** Sent on every upstream request and on discovery's probe (Grafana Cloud: x-grafana-url). */
42
+ headers?: Record<string, string>;
43
+ /** A client the owner made in the vendor (HubSpot, Slack); without one the client is registered dynamically. */
44
+ client?: () => {
45
+ id: string;
46
+ secret?: string;
47
+ } | undefined;
48
+ /** The board's https address (default: BOARD_URL, from the host's BOARD_LAN_URL): the one redirect besides loopback. */
49
+ boardUrl?: string;
50
+ /** Fixed endpoints (Slack); without them they are discovered (RFC 9728, then RFC 8414). */
51
+ endpoints?: {
52
+ authorize: string;
53
+ token: string;
54
+ };
55
+ /**
56
+ * `supported`: the scopes the owner may pick when the vendor doesn't list them (an empty list: never ask for scopes).
57
+ * `recommended`: the ones pre-selected (default: all of them). `separator`: how they are joined (default a space).
58
+ */
59
+ scopes?: {
60
+ supported?: string[];
61
+ recommended?: string[];
62
+ separator?: string;
63
+ };
64
+ /** false: never send RFC 8707 `resource` (default: the MCP URL without its query). */
65
+ resource?: false;
66
+ /** A vendor's token answer in the standard shape (Slack nests the user token under authed_user). */
67
+ tokenAnswer?: (json: Record<string, unknown>) => Record<string, unknown>;
68
+ fetchImpl?: typeof fetch;
69
+ }
70
+ /** token.json: the pair plus the client it belongs to. Extra fields a vendor answered (Slack's user_id) are kept. */
71
+ export interface StoredToken {
72
+ access_token: string;
73
+ refresh_token?: string;
74
+ expires_at?: number;
75
+ scope?: string;
76
+ client_id?: string;
77
+ client_secret?: string;
78
+ token_endpoint?: string;
79
+ resource?: string;
80
+ [extra: string]: unknown;
81
+ }
82
+ /** A redirect this sign-in may send: a loopback callback (a tunnel), or a callback on the board's https origin. */
83
+ export declare function redirectAllowed(redirectUri: string, boardUrl?: string): boolean;
84
+ /** The owner's OAuth sign-in to a vendor's MCP server. */
85
+ export declare function oauth(o: OAuthOptions): Auth;