@aidenhq/sdk 0.3.0 → 0.4.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.
- package/README.md +5 -4
- package/dist/src/agent-paused.d.ts +7 -0
- package/dist/src/agent-paused.js +4 -0
- package/dist/src/attribution.d.ts +16 -0
- package/dist/src/attribution.js +21 -0
- package/dist/src/box-bundle.d.ts +9 -0
- package/dist/src/box-bundle.js +59 -0
- package/dist/src/caller.js +2 -1
- package/dist/src/checks.d.ts +101 -0
- package/dist/src/checks.js +151 -0
- package/dist/src/churn.d.ts +46 -0
- package/dist/src/churn.js +177 -0
- package/dist/src/closed-event.d.ts +36 -0
- package/dist/src/closed-event.js +17 -0
- package/dist/src/engine-io.d.ts +2 -0
- package/dist/src/engine-io.js +13 -8
- package/dist/src/executor.d.ts +46 -3
- package/dist/src/executor.js +23 -13
- package/dist/src/fence.d.ts +12 -0
- package/dist/src/fence.js +24 -1
- package/dist/src/for-others.d.ts +3 -0
- package/dist/src/for-others.js +7 -0
- package/dist/src/instance-details.d.ts +10 -0
- package/dist/src/instance-details.js +63 -0
- package/dist/src/instance-paths.d.ts +3 -0
- package/dist/src/instance-paths.js +7 -0
- package/dist/src/judge.d.ts +54 -20
- package/dist/src/judge.js +57 -75
- package/dist/src/kernel-client.d.ts +45 -0
- package/dist/src/kernel-client.js +103 -0
- package/dist/src/kit.js +19 -4
- package/dist/src/maintained-repos.d.ts +58 -0
- package/dist/src/maintained-repos.js +136 -0
- package/dist/src/model-text.d.ts +29 -0
- package/dist/src/model-text.js +361 -0
- package/dist/src/owner-day.d.ts +12 -0
- package/dist/src/owner-day.js +39 -0
- package/dist/src/paperclip.d.ts +34 -0
- package/dist/src/paperclip.js +64 -0
- package/dist/src/pass-rule.d.ts +10 -0
- package/dist/src/pass-rule.js +24 -0
- package/dist/src/pin-owner.d.ts +2 -0
- package/dist/src/pin-owner.js +1 -0
- package/dist/src/progress.js +7 -2
- package/dist/src/provider.d.ts +83 -0
- package/dist/src/provider.js +31 -0
- package/dist/src/quality.d.ts +74 -0
- package/dist/src/quality.js +131 -0
- package/dist/src/repeat.d.ts +19 -0
- package/dist/src/repeat.js +38 -0
- package/dist/src/responses.d.ts +64 -0
- package/dist/src/responses.js +198 -0
- package/dist/src/reviewer.d.ts +79 -34
- package/dist/src/reviewer.js +198 -22
- package/dist/src/source-store.d.ts +13 -3
- package/dist/src/source-store.js +12 -7
- package/dist/src/task-state-types.d.ts +77 -0
- package/dist/src/task-state-types.js +4 -0
- package/dist/src/tiers.d.ts +88 -0
- package/dist/src/tiers.js +156 -0
- package/dist/src/tools-client.d.ts +60 -0
- package/dist/src/tools-client.js +192 -0
- package/dist/src/types.d.ts +28 -2
- package/dist/src/vendor/needs.d.ts +35 -0
- package/dist/src/vendor/needs.js +43 -0
- package/dist/src/vendor/oauth.d.ts +82 -2
- package/dist/src/vendor/oauth.js +282 -32
- package/dist/src/vendor/proxy.d.ts +31 -6
- package/dist/src/vendor/proxy.js +376 -49
- package/package.json +11 -10
package/dist/src/vendor/proxy.js
CHANGED
|
@@ -7,13 +7,16 @@
|
|
|
7
7
|
// /mcp/read the kernel's calls for runner jobs (the read key): only tools the module's manifest tags read (`reads`, the
|
|
8
8
|
// READ_TOOLS its module.yaml sets from those tags) that the upstream also marks read-only (or the connection's
|
|
9
9
|
// read rule says are reads), so the jobs' token never reaches a write;
|
|
10
|
-
// /auth/* the board's sign-in (state, the scopes the owner may pick, start, finish), with the board's own key
|
|
10
|
+
// /auth/* the board's sign-in (state, the scopes the owner may pick, start, finish, or a device code), with the board's own key,
|
|
11
|
+
// and /auth/check: one live read upstream (a tools list), answering { ok: true } or { ok: false, message, fix? };
|
|
11
12
|
// /healthz whether it is connected.
|
|
12
13
|
// A connection adds only its real logic as hooks (a pinned argument, a site id, a deny rule) and its own routes (a write
|
|
13
14
|
// kind's executor). Not signed in: it still starts, lists the tools it saw last as stand-ins, and every call says how to
|
|
14
|
-
// connect (never a crash loop, never a silently empty tool list).
|
|
15
|
+
// connect (never a crash loop, never a silently empty tool list): a needs_owner answer (needs.ts), which the kernel routes to
|
|
16
|
+
// the owner or the digest.
|
|
15
17
|
//
|
|
16
|
-
//
|
|
18
|
+
// First-party modules hold byte-identical copies (scripts/sync-shared.ts: edit this one and run it); third-party modules import
|
|
19
|
+
// @aidenhq/sdk/vendor/proxy (the MCP SDK, zod and pino are theirs: peer dependencies).
|
|
17
20
|
import { timingSafeEqual } from "node:crypto";
|
|
18
21
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
19
22
|
import { createServer } from "node:http";
|
|
@@ -24,10 +27,20 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
|
24
27
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
25
28
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
26
29
|
import { z } from "zod";
|
|
30
|
+
import { needsOwner, signedIn } from "./needs.js";
|
|
27
31
|
import { AuthError, SignInError } from "./oauth.js";
|
|
28
32
|
// The upstream refused the token: refresh once and retry. A refresh that failed (AuthError) already marked what it meant
|
|
29
33
|
// (refused: expired; the vendor's 5xx: not), so it is never retried here.
|
|
30
|
-
|
|
34
|
+
// HubSpot answers an expired token with a bare 401 (no text), so the transport error's status counts too. An HTTP status
|
|
35
|
+
// decides alone: a 500 whose text mentions 401 may have done its write, which a retry would do again.
|
|
36
|
+
const isAuthFailure = (err) => {
|
|
37
|
+
if (err instanceof AuthError)
|
|
38
|
+
return false;
|
|
39
|
+
const code = err?.code;
|
|
40
|
+
if (typeof code === "number" && code >= 100 && code < 600)
|
|
41
|
+
return code === 401;
|
|
42
|
+
return /401|unauthori[sz]ed|unauthenticated|invalid_token|not_authenticated/i.test(String(err));
|
|
43
|
+
};
|
|
31
44
|
const refusal = (text) => ({ isError: true, content: [{ type: "text", text }] });
|
|
32
45
|
// Reads run unattended in Codex as read-only, closed-world tools. Every other tool is a write the kernel files as a record and
|
|
33
46
|
// its tier decides before anything runs; these hints only keep the harness from stopping to ask a person who isn't there.
|
|
@@ -42,25 +55,73 @@ export function createVendorProxy(o) {
|
|
|
42
55
|
const denied = (name) => Boolean(hooks.deny?.test(name));
|
|
43
56
|
const cacheFile = o.stateDir ? join(o.stateDir, "tools.json") : undefined;
|
|
44
57
|
let upstream;
|
|
58
|
+
// A reset (a new sign-in, the periodic reconnect) invalidates every connect already in flight: such a connect is stale and must
|
|
59
|
+
// not become the cached session, or calls would run under the account the owner just replaced.
|
|
60
|
+
let generation = 0;
|
|
61
|
+
// Concurrent calls in one generation share that generation's connect; a new generation starts its own at once, so a stalled
|
|
62
|
+
// connect can never hold up the calls after it. Which one becomes the session is decided at commit (see `commit`).
|
|
63
|
+
let pending;
|
|
64
|
+
let resetting;
|
|
65
|
+
// A new sign-in (a different account or grant), not a refresh of the same one. A call that started under the previous sign-in is
|
|
66
|
+
// never replayed on the new one: its arguments and its results belong to the owner who sent it, not the account that replaced it.
|
|
67
|
+
let signIn = 0;
|
|
45
68
|
const notConnected = () => (!o.upstream ? `${o.name} isn't connected yet: the owner presses Connect on the board (Settings, Connections).` : auth.status().state === "expired" ? `${o.name}'s sign-in stopped working: the owner reconnects it on the board.` : `${o.name} isn't connected: the owner signs in from the board.`);
|
|
46
|
-
|
|
69
|
+
/** The connect started before a reset, whose session belongs to the account or token that reset replaced. */
|
|
70
|
+
class StaleConnect extends Error {
|
|
71
|
+
}
|
|
72
|
+
/** A different sign-in replaced this call's while it waited: it is not sent (or replayed) under the new account. */
|
|
73
|
+
class StaleSignIn extends Error {
|
|
74
|
+
}
|
|
75
|
+
/** The token endpoint failed (a 5xx, a timeout): the vendor never refused the grant, so nothing is marked expired. */
|
|
76
|
+
class RefreshFailed extends Error {
|
|
77
|
+
reason;
|
|
78
|
+
constructor(reason) {
|
|
79
|
+
super(String(reason));
|
|
80
|
+
this.reason = reason;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async function open(gen) {
|
|
47
84
|
if (!o.upstream)
|
|
48
85
|
throw new AuthError(notConnected());
|
|
49
86
|
const client = new Client({ name: `aidenhq-${o.name.toLowerCase()}-proxy`, version: "0.2.0" });
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
87
|
+
try {
|
|
88
|
+
// No redirect, on every request the transport makes (its POSTs and its event-stream GET): the owner's token (or the
|
|
89
|
+
// connection's key header) goes only to the upstream address it was issued for.
|
|
90
|
+
await client.connect(new StreamableHTTPClientTransport(o.upstream, { requestInit: { headers: await auth.headers() }, fetch: (url, init) => fetch(url, { ...init, redirect: "error" }) }));
|
|
91
|
+
const tools = [];
|
|
92
|
+
let cursor;
|
|
93
|
+
do {
|
|
94
|
+
const page = await client.listTools(cursor ? { cursor } : undefined);
|
|
95
|
+
tools.push(...page.tools);
|
|
96
|
+
cursor = page.nextCursor;
|
|
97
|
+
} while (cursor);
|
|
98
|
+
// A connect a reset superseded never runs the hook: it would do work (and reach the vendor) for an account already replaced.
|
|
99
|
+
if (gen !== generation)
|
|
100
|
+
throw new StaleConnect();
|
|
101
|
+
const commitHook = await hooks.connected?.(client, tools);
|
|
102
|
+
// It may have been superseded while the hook ran: its state must not land over the winner's, and its session is not the one.
|
|
103
|
+
if (gen !== generation)
|
|
104
|
+
throw new StaleConnect();
|
|
105
|
+
commitHook?.();
|
|
106
|
+
// The session this one replaces (a racing reconnect's) is retired, never left open.
|
|
107
|
+
if (upstream)
|
|
108
|
+
retire(upstream);
|
|
109
|
+
upstream = { client, tools, at: Date.now(), active: 0, retired: false };
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
// Whatever stopped this connect (a refused handshake, a failing tools list, a hook, or a reset), its client never becomes
|
|
113
|
+
// the cached session: close it here, or its event stream stays open with nothing able to reach it.
|
|
114
|
+
void client.close().catch(() => undefined);
|
|
115
|
+
// A connect a newer sign-in or reset superseded says nothing about the account saved now: its failure is stale, so the
|
|
116
|
+
// caller takes the current session instead of refreshing (or marking expired) against the grant that replaced it.
|
|
117
|
+
if (gen !== generation)
|
|
118
|
+
throw new StaleConnect();
|
|
119
|
+
throw err;
|
|
120
|
+
}
|
|
60
121
|
auth.mark("ok");
|
|
61
|
-
const names = tools.map((t) => t.name).filter((n) => !denied(n));
|
|
122
|
+
const names = upstream.tools.map((t) => t.name).filter((n) => !denied(n));
|
|
62
123
|
// The kernel lists only what the module tags; a name here it doesn't tag reaches nobody until a module change does.
|
|
63
|
-
log.info({ upstream_tools: tools.length, tools: names }, `connected to ${o.name}`);
|
|
124
|
+
log.info({ upstream_tools: upstream.tools.length, tools: names }, `connected to ${o.name}`);
|
|
64
125
|
if (cacheFile)
|
|
65
126
|
try {
|
|
66
127
|
writeFileSync(cacheFile, JSON.stringify(names));
|
|
@@ -68,32 +129,213 @@ export function createVendorProxy(o) {
|
|
|
68
129
|
catch { /* read-only state: no stand-ins */ }
|
|
69
130
|
return upstream;
|
|
70
131
|
}
|
|
71
|
-
|
|
132
|
+
function connect() {
|
|
133
|
+
// A connect already running for this generation is the one to wait on: starting a second would have the two replace each
|
|
134
|
+
// other, and every caller waiting on them would lose its session in turn. A new generation opens its own at once (nothing
|
|
135
|
+
// queues): a stalled connect on a replaced sign-in must not hold up the calls after it, and `commit` decides the winner.
|
|
136
|
+
if (pending && pending.gen === generation)
|
|
137
|
+
return pending.p;
|
|
138
|
+
const gen = generation;
|
|
139
|
+
const entry = { gen, p: open(gen) };
|
|
140
|
+
pending = entry;
|
|
141
|
+
const done = () => { if (pending === entry)
|
|
142
|
+
pending = undefined; };
|
|
143
|
+
void entry.p.then(done, done);
|
|
144
|
+
return entry.p;
|
|
145
|
+
}
|
|
146
|
+
/** A replaced session closes once its in-flight calls end; until then they keep answering on it. */
|
|
147
|
+
function retire(old) {
|
|
148
|
+
old.retired = true;
|
|
149
|
+
if (old.active === 0)
|
|
150
|
+
void old.client.close().catch(() => undefined);
|
|
151
|
+
}
|
|
152
|
+
/** The session only: invalidated and retired, nothing connecting in its place (the sign-in is gone, or a check just failed). */
|
|
153
|
+
function drop() {
|
|
154
|
+
generation += 1;
|
|
72
155
|
const old = upstream;
|
|
73
156
|
upstream = undefined;
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
157
|
+
if (old)
|
|
158
|
+
retire(old);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Replaces the session. Concurrent callers share one reset rather than each invalidating the other's connect, but only when the
|
|
162
|
+
* pending one already does everything they need: a refresh never joins a session-only reset (it would swallow the grant), and a
|
|
163
|
+
* new sign-in (`force`) never joins at all, since a connect started before it belongs to the account it replaced.
|
|
164
|
+
*/
|
|
165
|
+
function reset(refresh, force = false) {
|
|
166
|
+
if (!force && resetting && (resetting.refresh || !refresh))
|
|
167
|
+
return resetting.p;
|
|
168
|
+
const entry = { refresh, p: Promise.resolve() };
|
|
169
|
+
if (force)
|
|
170
|
+
signIn += 1;
|
|
171
|
+
entry.p = (async () => {
|
|
172
|
+
const old = upstream;
|
|
173
|
+
generation += 1;
|
|
174
|
+
upstream = undefined;
|
|
175
|
+
if (old)
|
|
176
|
+
retire(old);
|
|
177
|
+
// A token endpoint failure is the vendor's, not a refusal of the grant: pass it on as it is, with nothing marked expired.
|
|
178
|
+
if (refresh)
|
|
179
|
+
await auth.refresh().catch((err) => { throw new RefreshFailed(err); });
|
|
180
|
+
// A refresh is the one reset with work between its start and its connect, so a reset that replaced it meanwhile owns the
|
|
181
|
+
// session now: connecting here would replace the newer sign-in's session with one opened from this one's grant.
|
|
182
|
+
if (refresh && resetting !== entry)
|
|
183
|
+
return;
|
|
184
|
+
// A newer reset took over while this one ran: it owns the session now, so there is nothing left to connect here.
|
|
185
|
+
await connect().catch((err) => {
|
|
186
|
+
// A sign-in that still could not connect is a real failure for the board; a stale one is the newer reset's business.
|
|
187
|
+
if (!(err instanceof StaleConnect))
|
|
188
|
+
throw err;
|
|
189
|
+
});
|
|
190
|
+
})().finally(() => { if (resetting === entry)
|
|
191
|
+
resetting = undefined; });
|
|
192
|
+
resetting = entry;
|
|
193
|
+
return entry.p;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Waits on a reset another call started, but never past `resetWaitMs`: a handshake that stalls there (a cold start, a periodic
|
|
197
|
+
* reconnect) must not hold up every call after it. A reset left waiting that long is abandoned, and this call opens a session of
|
|
198
|
+
* its own at once; the stalled connect is superseded, so it can never become the session.
|
|
199
|
+
*/
|
|
200
|
+
async function settled() {
|
|
201
|
+
const entry = resetting;
|
|
202
|
+
if (!entry)
|
|
203
|
+
return;
|
|
204
|
+
let timer;
|
|
205
|
+
const stalled = await Promise.race([
|
|
206
|
+
entry.p.then(() => false, () => false),
|
|
207
|
+
new Promise((r) => { timer = setTimeout(() => r(true), o.resetWaitMs ?? 20_000); timer.unref?.(); }),
|
|
208
|
+
]);
|
|
209
|
+
if (timer)
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
if (!stalled)
|
|
212
|
+
return;
|
|
213
|
+
// Only the caller that finds this reset still current invalidates it: a later caller waiting on the same stalled entry must not
|
|
214
|
+
// bump the generation again, or it would invalidate the session the first one opened.
|
|
215
|
+
if (resetting !== entry)
|
|
216
|
+
return;
|
|
217
|
+
log.warn(`${o.name}: a ${entry.refresh ? "token refresh" : "reconnect"} stalled; opening a session of its own`);
|
|
218
|
+
resetting = undefined;
|
|
219
|
+
generation += 1;
|
|
220
|
+
}
|
|
221
|
+
/** The current session, or a fresh one; a connect a reset invalidated is retried on the session that reset opened. */
|
|
222
|
+
async function acquire() {
|
|
223
|
+
// A reset in flight is replacing the token (a refresh) or the account (a sign-in): a handshake started now would go out with
|
|
224
|
+
// the old one and come back 401 after the refresh succeeded, so wait for it and use the session it opened. A connect a reset
|
|
225
|
+
// superseded while it ran is the same case, so it waits for that reset too rather than opening another handshake at once.
|
|
226
|
+
await settled();
|
|
227
|
+
if (upstream)
|
|
228
|
+
return upstream;
|
|
229
|
+
try {
|
|
230
|
+
return await connect();
|
|
231
|
+
}
|
|
232
|
+
catch (err) {
|
|
233
|
+
if (!(err instanceof StaleConnect))
|
|
234
|
+
throw err;
|
|
235
|
+
// A reset started while this connect ran, so the connect is stale. That reset may still be replacing the token (a refresh), so
|
|
236
|
+
// wait for it again before deciding: opening a handshake here could send the token the refresh is replacing.
|
|
237
|
+
await settled();
|
|
238
|
+
return upstream ?? (await connect());
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** Runs one call on a session, counted so a retired session isn't closed under it. */
|
|
242
|
+
async function on(u, fn) {
|
|
243
|
+
u.active += 1;
|
|
244
|
+
try {
|
|
245
|
+
return await fn(u);
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
u.active -= 1;
|
|
249
|
+
if (u.retired && u.active === 0)
|
|
250
|
+
void u.client.close().catch(() => undefined);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* One dispatch on the current session, bound to the sign-in the call started under: the check runs after every wait (a reset, a
|
|
255
|
+
* refresh, a connect), immediately before the tool call, so a sign-in that lands meanwhile fails the call instead of sending it —
|
|
256
|
+
* and its results — through the account that replaced the owner who asked.
|
|
257
|
+
*/
|
|
258
|
+
async function dispatch(under, fn) {
|
|
259
|
+
const u = await acquire();
|
|
260
|
+
if (signIn !== under)
|
|
261
|
+
throw new StaleSignIn();
|
|
262
|
+
return await on(u, fn);
|
|
263
|
+
}
|
|
264
|
+
/** One attempt on the current session; a 401 from a session another call already replaced is retried on the current one. */
|
|
265
|
+
async function run(fn) {
|
|
266
|
+
const under = signIn;
|
|
267
|
+
const u = await acquire();
|
|
268
|
+
if (signIn !== under)
|
|
269
|
+
throw new StaleSignIn();
|
|
270
|
+
try {
|
|
271
|
+
return await on(u, fn);
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
if (!auth.signedIn() || !isAuthFailure(err) || u === upstream)
|
|
275
|
+
throw err;
|
|
276
|
+
// A different account signed in while this call ran: its arguments and results belong to the owner who sent it, so it fails
|
|
277
|
+
// here rather than being replayed (and answered, private data included) under the account that replaced the sign-in.
|
|
278
|
+
if (signIn !== under)
|
|
279
|
+
throw err;
|
|
280
|
+
// The session that failed is no longer the current one (another call replaced it, or the token was refreshed): its 401
|
|
281
|
+
// belongs to the token it was opened with, so retry on the current session and decide nothing about this one.
|
|
282
|
+
return await dispatch(under, fn);
|
|
283
|
+
}
|
|
78
284
|
}
|
|
79
285
|
async function withUpstream(fn) {
|
|
286
|
+
const under = signIn;
|
|
80
287
|
// Reconnect every 30 minutes or after an auth failure (inside the try: a token revoked early fails connect() too).
|
|
81
288
|
try {
|
|
82
|
-
|
|
289
|
+
// A periodic reconnect: only a session that exists can be too old. Without one, `acquire` opens it (bounded by `settled`), so
|
|
290
|
+
// a call never joins a reset another call started and waits on it for as long as that connect hangs.
|
|
291
|
+
if (upstream && Date.now() - upstream.at > 30 * 60_000) {
|
|
83
292
|
await reset(false);
|
|
84
|
-
|
|
293
|
+
// The reconnect may have waited on a refresh or a sign-in: dispatch bound to the sign-in this call started under, as every
|
|
294
|
+
// other retry path does, so one that landed meanwhile never receives it.
|
|
295
|
+
return await dispatch(under, fn);
|
|
296
|
+
}
|
|
297
|
+
return await run(fn);
|
|
85
298
|
}
|
|
86
299
|
catch (err) {
|
|
87
300
|
if (!auth.signedIn() || !isAuthFailure(err))
|
|
88
301
|
throw err;
|
|
302
|
+
// A different account signed in while this call ran: never refresh or replay it under the new sign-in (see `run`).
|
|
303
|
+
if (signIn !== under)
|
|
304
|
+
throw err;
|
|
305
|
+
// The vendor's REST side still answers this token: its MCP endpoint's 401 is that endpoint's own error, not a sign-in to refresh or reconnect.
|
|
306
|
+
// A new session with the current token (the cached one's headers are fixed at connect time); no refresh grant is used.
|
|
307
|
+
if (auth.refused && !(await auth.refused())) {
|
|
308
|
+
await reset(false);
|
|
309
|
+
return await dispatch(under, fn);
|
|
310
|
+
}
|
|
89
311
|
log.warn(`${o.name} rejected the token; refreshing and retrying once`);
|
|
90
312
|
try {
|
|
91
313
|
await reset(true);
|
|
92
|
-
|
|
314
|
+
}
|
|
315
|
+
catch (err) {
|
|
316
|
+
// The token endpoint failed (a 5xx, a timeout): the vendor never refused the grant, so this is a transient error, never an
|
|
317
|
+
// expiry. Only a handshake that still 401s with the fresh token is a refused sign-in.
|
|
318
|
+
if (err instanceof RefreshFailed)
|
|
319
|
+
throw err.reason;
|
|
320
|
+
// A sign-in that replaced this one meanwhile owns the decision, so only the current sign-in is marked — and only after the
|
|
321
|
+
// refusal probe, which may itself have taken long enough for a new sign-in to land.
|
|
322
|
+
const refused = isAuthFailure(err) && (await auth.refused?.() ?? true);
|
|
323
|
+
if (refused && signIn === under)
|
|
324
|
+
auth.mark("expired", `${o.name} rejected a freshly refreshed token`);
|
|
325
|
+
throw err;
|
|
326
|
+
}
|
|
327
|
+
const r = await acquire();
|
|
328
|
+
if (signIn !== under)
|
|
329
|
+
throw new StaleSignIn();
|
|
330
|
+
try {
|
|
331
|
+
return await on(r, fn);
|
|
93
332
|
}
|
|
94
333
|
catch (again) {
|
|
95
|
-
|
|
334
|
+
// A late 401 from a session another call replaced while this retry ran decides nothing about the sign-in saved now: both are
|
|
335
|
+
// rechecked after the refusal probe, which may itself have taken long enough for a new session or sign-in to land.
|
|
336
|
+
if (r === upstream && isAuthFailure(again) && (await auth.refused?.() ?? true) && r === upstream && signIn === under) {
|
|
96
337
|
auth.mark("expired", `${o.name} rejected a freshly refreshed token`);
|
|
338
|
+
}
|
|
97
339
|
throw again;
|
|
98
340
|
}
|
|
99
341
|
}
|
|
@@ -108,17 +350,25 @@ export function createVendorProxy(o) {
|
|
|
108
350
|
const names = cacheFile && existsSync(cacheFile) ? JSON.parse(readFileSync(cacheFile, "utf8")) : [];
|
|
109
351
|
return names.map((name) => ({ name, description: notConnected(), inputSchema: { type: "object" } }));
|
|
110
352
|
}
|
|
111
|
-
async function call(name, args) {
|
|
353
|
+
async function call(name, args, readOnly = false) {
|
|
112
354
|
if (denied(name))
|
|
113
355
|
throw new Error(`${name} is not available through AidenHQ`);
|
|
356
|
+
if (hooks.call)
|
|
357
|
+
return hooks.call(name, args, readOnly);
|
|
114
358
|
return withUpstream(async (u) => {
|
|
115
359
|
const tool = u.tools.find((t) => t.name === name);
|
|
116
360
|
// Only what the upstream lists: its schema is what the hooks pin arguments against.
|
|
117
361
|
if (!tool)
|
|
118
362
|
throw new Error(`${o.name} doesn't offer ${name}`);
|
|
363
|
+
// Checked on the session that dispatches this attempt: a retry after a reconnect must not reach a tool the new session
|
|
364
|
+
// no longer marks read-only.
|
|
365
|
+
if (readOnly && !servesRead(tool)) {
|
|
366
|
+
log.warn({ tool: name }, "refused a write on the read endpoint");
|
|
367
|
+
return refusal(`Tool ${name} is not a read: the read endpoint serves reads only.`);
|
|
368
|
+
}
|
|
119
369
|
const sent = hooks.args ? hooks.args(name, args, tool) : args;
|
|
120
370
|
const result = (await u.client.callTool({ name, arguments: sent }, undefined, o.callTimeoutMs ? { timeout: o.callTimeoutMs } : undefined));
|
|
121
|
-
return hooks.result ? hooks.result(result) : result;
|
|
371
|
+
return hooks.result ? hooks.result(result, name) : result;
|
|
122
372
|
});
|
|
123
373
|
}
|
|
124
374
|
function buildServer(readOnly) {
|
|
@@ -140,22 +390,22 @@ export function createVendorProxy(o) {
|
|
|
140
390
|
log.warn({ tool: name }, "refused a denied tool");
|
|
141
391
|
return refusal(`Tool ${name} is not available through AidenHQ.`);
|
|
142
392
|
}
|
|
393
|
+
// Only the owner can fix these: the kernel routes the need (needs.ts), never this text, to whoever should hear it.
|
|
394
|
+
const need = () => needsOwner({ cause: auth.status().state === "expired" ? "expired" : "not_connected", detail: notConnected() });
|
|
143
395
|
if (!o.upstream || !auth.signedIn())
|
|
144
|
-
return
|
|
396
|
+
return need();
|
|
145
397
|
try {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
return refusal(`Tool ${name} is not a read: the read endpoint serves reads only.`);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
return await call(name, req.params.arguments ?? {});
|
|
398
|
+
// Upstream answered through the owner's sign-in: a success says so, and clears a down state in the kernel (needs.ts).
|
|
399
|
+
const result = await call(name, req.params.arguments ?? {}, readOnly);
|
|
400
|
+
// A connection that serves its calls itself (`hooks.call`) marks what its sign-ins served, and what they didn't.
|
|
401
|
+
return result.isError || hooks.call ? result : signedIn(result);
|
|
154
402
|
}
|
|
155
403
|
catch (err) {
|
|
156
|
-
const signIn = err instanceof AuthError || isAuthFailure(err) || auth.status().state === "expired";
|
|
157
404
|
log.warn({ tool: name, err: String(err).slice(0, 300) }, `${o.name} tool failed`);
|
|
158
|
-
|
|
405
|
+
// A refused sign-in (marked expired) needs the owner; a vendor 5xx on refresh leaves it unknown and stays a plain error.
|
|
406
|
+
if (auth.status().state === "expired")
|
|
407
|
+
return need();
|
|
408
|
+
return refusal(`${o.name} error: ${String(err.message).slice(0, 300)}`);
|
|
159
409
|
}
|
|
160
410
|
});
|
|
161
411
|
return server;
|
|
@@ -179,30 +429,88 @@ export function createVendorProxy(o) {
|
|
|
179
429
|
return chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : undefined;
|
|
180
430
|
}
|
|
181
431
|
const sendJson = (res, status, body) => void res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
|
|
432
|
+
/** One live, read-only call upstream (its tool list): works, or what is wrong and the one thing to do about it. */
|
|
433
|
+
async function checkConnection() {
|
|
434
|
+
if (!o.upstream || !auth.signedIn())
|
|
435
|
+
return { ok: false, message: notConnected(), fix: "Connect" };
|
|
436
|
+
try {
|
|
437
|
+
await withUpstream((u) => u.client.listTools());
|
|
438
|
+
// Signed in and answering, and still unusable: Jira's account can't reach the configured site. The hook names it.
|
|
439
|
+
const problem = hooks.health?.();
|
|
440
|
+
return problem ? { ok: false, message: `${o.name} is signed in but can't be used: ${problem}`, fix: "Reconnect" } : { ok: true };
|
|
441
|
+
}
|
|
442
|
+
catch (err) {
|
|
443
|
+
// A sign-in the vendor refused is marked expired by the refresh path; a 401 it still refuses is the same answer. An AuthError
|
|
444
|
+
// from the token endpoint (a 5xx, a timeout) leaves the grant untouched, so it is the vendor's outage, not the owner's sign-in.
|
|
445
|
+
const expired = auth.status().state === "expired";
|
|
446
|
+
const authFailure = !expired && !(err instanceof AuthError) && isAuthFailure(err);
|
|
447
|
+
const refused = authFailure && (await auth.refused?.() ?? true);
|
|
448
|
+
// A session this proxy itself had, that the upstream no longer accepts, is not moved to the next sign-in: retired here, so
|
|
449
|
+
// the next check (when a bind changes the primary) opens one from the sign-in that is there now.
|
|
450
|
+
if (authFailure && upstream)
|
|
451
|
+
drop();
|
|
452
|
+
return expired || refused ? { ok: false, message: `${o.name} no longer accepts the sign-in.`, fix: "Reconnect" } : { ok: false, message: `${o.name} didn't answer: ${String(err.message).slice(0, 200)}` };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
182
455
|
/** The board's sign-in endpoints: state, the scopes on offer, and starting or finishing a sign-in (never a token). */
|
|
183
456
|
async function handleAuth(req, res, path) {
|
|
184
457
|
if (!bearer(req, o.authKey))
|
|
185
458
|
return sendJson(res, 401, { error: "unauthorized" });
|
|
186
|
-
if (path === "/auth/status" && req.method === "GET")
|
|
187
|
-
|
|
459
|
+
if (path === "/auth/status" && req.method === "GET") {
|
|
460
|
+
await auth.check?.().catch(() => { });
|
|
461
|
+
return sendJson(res, 200, { configured: Boolean(o.upstream), ...auth.status(), ...(hooks.status?.() ?? {}) });
|
|
462
|
+
}
|
|
463
|
+
if (path === "/auth/check" && req.method === "GET")
|
|
464
|
+
return sendJson(res, 200, await checkConnection());
|
|
188
465
|
const flow = auth.signIn;
|
|
189
466
|
if (!flow)
|
|
190
467
|
return sendJson(res, 400, { error: `${o.name} needs no sign-in` });
|
|
191
468
|
if (!o.upstream)
|
|
192
469
|
return sendJson(res, 400, { error: notConnected() });
|
|
193
470
|
try {
|
|
194
|
-
|
|
195
|
-
|
|
471
|
+
// A device sign-in: start (the code for the board to show), its state while this service polls, cancel.
|
|
472
|
+
if (path === "/auth/device" || path === "/auth/device/cancel") {
|
|
473
|
+
const d = auth.device;
|
|
474
|
+
if (!d)
|
|
475
|
+
return sendJson(res, 404, { error: `${o.name} signs in by redirect` });
|
|
476
|
+
if (req.method === "GET" && path === "/auth/device")
|
|
477
|
+
return sendJson(res, 200, d.state());
|
|
478
|
+
if (req.method !== "POST")
|
|
479
|
+
return sendJson(res, 405, { error: "method not allowed" });
|
|
480
|
+
if (path === "/auth/device/cancel")
|
|
481
|
+
return (d.cancel(), sendJson(res, 200, { ok: true }));
|
|
482
|
+
const started = await d.start(() => {
|
|
483
|
+
log.info({ scope: auth.status().scope }, `signed in to ${o.name}`);
|
|
484
|
+
void reset(false, true).catch((err) => log.warn({ err: String(err).slice(0, 300) }, "connecting after sign-in failed"));
|
|
485
|
+
});
|
|
486
|
+
return sendJson(res, 200, started);
|
|
487
|
+
}
|
|
488
|
+
if (path === "/auth/scopes" && req.method === "GET") {
|
|
489
|
+
const q = new URL(req.url ?? "/", "http://x").searchParams;
|
|
490
|
+
const target = { account: q.get("account")?.slice(0, 200) || undefined, client_id: q.get("client_id")?.slice(0, 200) || undefined };
|
|
491
|
+
return sendJson(res, 200, await flow.scopes(target.account || target.client_id ? target : undefined));
|
|
492
|
+
}
|
|
196
493
|
if (req.method !== "POST")
|
|
197
494
|
return sendJson(res, 405, { error: "method not allowed" });
|
|
198
495
|
if (path === "/auth/start") {
|
|
199
|
-
const { redirect_uri, scopes } = z.object({ redirect_uri: z.string().max(200), scopes: z.array(z.string().max(200)).max(200).optional() }).parse(await readJson(req));
|
|
200
|
-
return sendJson(res, 200, await flow.start(redirect_uri, scopes));
|
|
496
|
+
const { redirect_uri, scopes, account, client_id } = z.object({ redirect_uri: z.string().max(200), scopes: z.array(z.string().max(200)).max(200).optional(), account: z.string().max(200).optional(), client_id: z.string().max(200).optional() }).parse(await readJson(req));
|
|
497
|
+
return sendJson(res, 200, await flow.start(redirect_uri, scopes, account || client_id ? { account, client_id } : undefined));
|
|
498
|
+
}
|
|
499
|
+
// One account signed out, on a connection with several (the board's per-account Disconnect).
|
|
500
|
+
if (path === "/auth/disconnect" && auth.disconnect) {
|
|
501
|
+
const { account } = z.object({ account: z.string().max(200).optional() }).parse((await readJson(req)) ?? {});
|
|
502
|
+
await auth.disconnect(account);
|
|
503
|
+
// Its session is retired with the sign-in gone (nothing can reconnect it), and the answer never waits on the primary:
|
|
504
|
+
// a disconnect of one workspace must not outlast the board's 20 s on an unrelated workspace's handshake.
|
|
505
|
+
drop();
|
|
506
|
+
return sendJson(res, 200, { ok: true });
|
|
201
507
|
}
|
|
202
508
|
if (path === "/auth/finish") {
|
|
203
509
|
const { state, code } = z.object({ state: z.string().max(200), code: z.string().max(4096) }).parse(await readJson(req));
|
|
204
510
|
await flow.finish(state, code);
|
|
205
|
-
|
|
511
|
+
// The old session is retired at once; the new one connects after the answer, as a device sign-in's does, so a slow
|
|
512
|
+
// vendor handshake never fails a sign-in whose token is already saved.
|
|
513
|
+
void reset(false, true).catch((err) => log.warn({ err: String(err).slice(0, 300) }, "connecting after sign-in failed"));
|
|
206
514
|
log.info({ scope: auth.status().scope }, `signed in to ${o.name}`);
|
|
207
515
|
return sendJson(res, 200, { ok: true });
|
|
208
516
|
}
|
|
@@ -215,13 +523,20 @@ export function createVendorProxy(o) {
|
|
|
215
523
|
return sendJson(res, 404, { error: "not found" });
|
|
216
524
|
}
|
|
217
525
|
const http = createServer(async (req, res) => {
|
|
218
|
-
|
|
526
|
+
let url;
|
|
527
|
+
try {
|
|
528
|
+
url = new URL(req.url ?? "/", "http://localhost");
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
return void res.writeHead(400).end();
|
|
532
|
+
}
|
|
219
533
|
try {
|
|
220
534
|
if (url.pathname === "/healthz") {
|
|
221
535
|
const s = auth.status();
|
|
222
536
|
// Without a sign-in (a local server) the only question is whether it answers; a failed ping drops the client.
|
|
223
537
|
if (s.state === "none" && o.upstream) {
|
|
224
|
-
const down = await withUpstream((u) => u.client.ping({ timeout: 3000 })).then(() => undefined, (err) => {
|
|
538
|
+
const down = await withUpstream((u) => u.client.ping({ timeout: 3000 })).then(() => undefined, (err) => { const old = upstream; upstream = undefined; if (old)
|
|
539
|
+
retire(old); return `${o.name} didn't answer: ${String(err.message).slice(0, 150)}`; });
|
|
225
540
|
return sendJson(res, down ? 503 : 200, { ok: !down, state: s.state, ...(down ? { detail: down } : {}) });
|
|
226
541
|
}
|
|
227
542
|
const why = !o.upstream ? `${o.name} isn't set up` : s.state === "missing" ? `${o.name} not connected (Connect on the board)` : s.state === "expired" ? `${o.name} sign-in expired: ${s.detail ?? ""} (Reconnect on the board)` : hooks.health?.();
|
|
@@ -266,5 +581,17 @@ export function createVendorProxy(o) {
|
|
|
266
581
|
res.writeHead(500).end();
|
|
267
582
|
}
|
|
268
583
|
});
|
|
269
|
-
|
|
584
|
+
// The current session's tools as agents see them, opened (or refreshed) like any call; undefined when it couldn't list them.
|
|
585
|
+
async function listTools() {
|
|
586
|
+
if (!o.upstream || !auth.signedIn())
|
|
587
|
+
return [];
|
|
588
|
+
try {
|
|
589
|
+
return await withUpstream(async (u) => shown(u.tools, false));
|
|
590
|
+
}
|
|
591
|
+
catch (err) {
|
|
592
|
+
log.warn({ err: String(err).slice(0, 300) }, `listing ${o.name} tools failed`);
|
|
593
|
+
return undefined;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return Object.assign(http, { call, signedIn: () => reset(false, true).catch((err) => log.warn({ err: String(err).slice(0, 300) }, "connecting after sign-in failed")), forget: drop, list: listTools });
|
|
270
597
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aidenhq/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "The shared code of AidenHQ modules: contract types, engine IO, the caller check and fence, write executors, the reviewer side, the judges' models and call, the source writer and the vendor MCP pass-through.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -24,15 +24,16 @@
|
|
|
24
24
|
"./fence": "./dist/src/fence.js",
|
|
25
25
|
"./reviewer": "./dist/src/reviewer.js",
|
|
26
26
|
"./judge": "./dist/src/judge.js",
|
|
27
|
+
"./responses": "./dist/src/responses.js",
|
|
28
|
+
"./provider": "./dist/src/provider.js",
|
|
27
29
|
"./progress": "./dist/src/progress.js",
|
|
30
|
+
"./paperclip": "./dist/src/paperclip.js",
|
|
28
31
|
"./source-store": "./dist/src/source-store.js",
|
|
29
32
|
"./vendor/proxy": "./dist/src/vendor/proxy.js",
|
|
30
|
-
"./vendor/oauth": "./dist/src/vendor/oauth.js"
|
|
33
|
+
"./vendor/oauth": "./dist/src/vendor/oauth.js",
|
|
34
|
+
"./vendor/needs": "./dist/src/vendor/needs.js"
|
|
31
35
|
},
|
|
32
|
-
"files": [
|
|
33
|
-
"dist",
|
|
34
|
-
"LICENSE"
|
|
35
|
-
],
|
|
36
|
+
"files": ["dist", "LICENSE"],
|
|
36
37
|
"peerDependencies": {
|
|
37
38
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
38
39
|
"pg": "^8.23.1",
|
|
@@ -59,13 +60,13 @@
|
|
|
59
60
|
"@types/pg": "8.23.1",
|
|
60
61
|
"pg": "8.23.1",
|
|
61
62
|
"pino": "10.4.0",
|
|
62
|
-
"typescript": "
|
|
63
|
-
"vitest": "5.1.0",
|
|
63
|
+
"typescript": "7.0.2",
|
|
64
64
|
"zod": "4.6.7"
|
|
65
65
|
},
|
|
66
66
|
"scripts": {
|
|
67
|
-
"test": "NODE_PATH
|
|
67
|
+
"test": "NODE_PATH=../node_modules bun test --parallel --timeout=30000 --path-ignore-patterns='**/*.e2e.test.ts' ./test/ ../../modules/engine-codex/test/ ../../modules/engine-opencode/test/",
|
|
68
|
+
"test:e2e": "NODE_PATH=../node_modules bun test --timeout=150000 ../../modules/engine-opencode/test/fresh-session.e2e.test.ts",
|
|
68
69
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
69
|
-
"prepack": "node ../../scripts/sdk-pack.
|
|
70
|
+
"prepack": "node ../../scripts/sdk-pack.ts"
|
|
70
71
|
}
|
|
71
72
|
}
|