@soft-boy/agentschema 0.3.12 → 0.5.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/README.md +13 -9
  2. package/dist/bin/agentschema.d.ts +2 -0
  3. package/dist/bin/agentschema.js +333 -0
  4. package/dist/lib/channels.d.ts +65 -0
  5. package/dist/lib/channels.js +339 -0
  6. package/dist/lib/check.d.ts +10 -0
  7. package/dist/lib/check.js +411 -0
  8. package/dist/lib/files.d.ts +7 -0
  9. package/{lib → dist/lib}/files.js +10 -14
  10. package/dist/lib/index.d.ts +24 -0
  11. package/{lib → dist/lib}/index.js +3 -10
  12. package/dist/lib/instance.d.ts +41 -0
  13. package/dist/lib/instance.js +74 -0
  14. package/dist/lib/markdown.d.ts +11 -0
  15. package/dist/lib/markdown.js +38 -0
  16. package/dist/lib/scaffold.d.ts +15 -0
  17. package/dist/lib/scaffold.js +46 -0
  18. package/dist/lib/scheduled.d.ts +56 -0
  19. package/dist/lib/scheduled.js +185 -0
  20. package/dist/lib/skills.d.ts +28 -0
  21. package/dist/lib/skills.js +55 -0
  22. package/dist/lib/stream.d.ts +30 -0
  23. package/dist/lib/stream.js +56 -0
  24. package/dist/lib/system-prompt.d.ts +16 -0
  25. package/{lib → dist/lib}/system-prompt.js +14 -15
  26. package/dist/lib/tools.d.ts +105 -0
  27. package/dist/lib/tools.js +353 -0
  28. package/dist/lib/vaults.d.ts +55 -0
  29. package/dist/lib/vaults.js +143 -0
  30. package/dist/src/chat.d.ts +15 -0
  31. package/dist/src/chat.js +159 -0
  32. package/dist/src/check.d.ts +2 -0
  33. package/dist/src/check.js +14 -0
  34. package/dist/src/cred-menu.d.ts +17 -0
  35. package/dist/src/cred-menu.js +193 -0
  36. package/dist/src/cred.d.ts +54 -0
  37. package/dist/src/cred.js +252 -0
  38. package/dist/src/custom-tools.d.ts +3 -0
  39. package/dist/src/custom-tools.js +18 -0
  40. package/dist/src/delete.d.ts +9 -0
  41. package/dist/src/delete.js +27 -0
  42. package/dist/src/deploy.d.ts +62 -0
  43. package/dist/src/deploy.js +442 -0
  44. package/dist/src/dotenv.d.ts +7 -0
  45. package/dist/src/dotenv.js +54 -0
  46. package/dist/src/folder.d.ts +5 -0
  47. package/dist/src/folder.js +57 -0
  48. package/dist/src/init.d.ts +11 -0
  49. package/dist/src/init.js +51 -0
  50. package/dist/src/list.d.ts +3 -0
  51. package/dist/src/list.js +46 -0
  52. package/dist/src/lock.d.ts +10 -0
  53. package/dist/src/lock.js +37 -0
  54. package/dist/src/mcp.d.ts +11 -0
  55. package/dist/src/mcp.js +79 -0
  56. package/dist/src/node.d.ts +14 -0
  57. package/dist/src/oauth.d.ts +64 -0
  58. package/dist/src/oauth.js +208 -0
  59. package/dist/src/prompts.d.ts +18 -0
  60. package/dist/src/prompts.js +166 -0
  61. package/dist/src/session.d.ts +58 -0
  62. package/dist/src/session.js +200 -0
  63. package/dist/src/tools-menu.d.ts +8 -0
  64. package/dist/src/tools-menu.js +173 -0
  65. package/package.json +21 -9
  66. package/bin/agentschema.js +0 -326
  67. package/lib/channels.js +0 -338
  68. package/lib/check.js +0 -388
  69. package/lib/instance.js +0 -48
  70. package/lib/markdown.js +0 -42
  71. package/lib/scaffold.js +0 -51
  72. package/lib/scheduled.js +0 -175
  73. package/lib/skills.js +0 -58
  74. package/lib/stream.js +0 -50
  75. package/lib/tools.js +0 -327
  76. package/lib/vaults.js +0 -142
  77. package/src/chat.js +0 -156
  78. package/src/check.js +0 -14
  79. package/src/cred-menu.js +0 -197
  80. package/src/cred.js +0 -263
  81. package/src/custom-tools.js +0 -17
  82. package/src/delete.js +0 -25
  83. package/src/deploy.js +0 -441
  84. package/src/dotenv.js +0 -50
  85. package/src/folder.js +0 -55
  86. package/src/init.js +0 -54
  87. package/src/list.js +0 -49
  88. package/src/lock.js +0 -40
  89. package/src/mcp.js +0 -76
  90. package/src/oauth.js +0 -215
  91. package/src/prompts.js +0 -159
  92. package/src/session.js +0 -194
  93. package/src/tools-menu.js +0 -163
  94. /package/{src → dist/src}/node.js +0 -0
@@ -0,0 +1,46 @@
1
+ // Lists the agents and sessions in the workspace the credentials belong to.
2
+ export async function listAgents(client) {
3
+ const rows = [];
4
+ for await (const agent of client.beta.agents.list()) {
5
+ rows.push({
6
+ name: agent.name,
7
+ id: agent.id,
8
+ version: String(agent.version),
9
+ model: agent.model?.id ?? "",
10
+ updated: formatDate(agent.updated_at),
11
+ });
12
+ }
13
+ return table(rows, { name: "NAME", id: "ID", version: "VERSION", model: "MODEL", updated: "UPDATED" }, "No agents.");
14
+ }
15
+ export async function listSessions(client) {
16
+ const rows = [];
17
+ // Newest first, the API's default order.
18
+ for await (const session of client.beta.sessions.list()) {
19
+ rows.push({
20
+ id: session.id,
21
+ status: session.status,
22
+ agent: session.agent ? `${session.agent.name} v${session.agent.version}` : "",
23
+ title: truncate(session.title ?? "", 40),
24
+ created: formatDate(session.created_at),
25
+ });
26
+ }
27
+ return table(rows, { id: "ID", status: "STATUS", agent: "AGENT", title: "TITLE", created: "CREATED" }, "No sessions.");
28
+ }
29
+ // Lines of a plain-text table, with columns padded to their widest value.
30
+ function table(rows, headers, empty) {
31
+ if (rows.length === 0)
32
+ return [empty];
33
+ const keys = Object.keys(headers);
34
+ const widths = keys.map((k) => Math.max(headers[k].length, ...rows.map((r) => r[k].length)));
35
+ const line = (r) => keys.map((k, i) => (i === keys.length - 1 ? r[k] : r[k].padEnd(widths[i]))).join(" ").trimEnd();
36
+ return [line(headers), ...rows.map(line)];
37
+ }
38
+ // "2026-11-03 14:02" in local time.
39
+ function formatDate(iso) {
40
+ if (!iso)
41
+ return "";
42
+ const d = new Date(iso);
43
+ const pad = (n) => String(n).padStart(2, "0");
44
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
45
+ }
46
+ const truncate = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
@@ -0,0 +1,10 @@
1
+ import type { Lock } from "../lib/instance.ts";
2
+ import type { Skill } from "../lib/skills.ts";
3
+ export declare const LOCK_FILE = "claude-lock.json";
4
+ export declare function readLock(dir: string): Lock | null;
5
+ export declare function writeLock(dir: string, lock: Lock): void;
6
+ export interface SkillFingerprint {
7
+ files: [rel: string, sha256: string][];
8
+ }
9
+ export declare function skillFingerprint(skill: Pick<Skill, "files">): SkillFingerprint;
10
+ export declare function hashBody(body: unknown): string;
@@ -0,0 +1,37 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ export const LOCK_FILE = "claude-lock.json";
5
+ // Same layout as the lock file `ant apply` writes: one entry per file, keyed by "./<file>".
6
+ export function readLock(dir) {
7
+ const path = join(dir, LOCK_FILE);
8
+ if (!existsSync(path))
9
+ return null;
10
+ try {
11
+ return JSON.parse(readFileSync(path, "utf8"));
12
+ }
13
+ catch (err) {
14
+ throw new Error(`${LOCK_FILE}: not valid JSON (${err.message})`);
15
+ }
16
+ }
17
+ export function writeLock(dir, lock) {
18
+ writeFileSync(join(dir, LOCK_FILE), JSON.stringify(lock, null, 2) + "\n");
19
+ }
20
+ // What's hashed into the lock for a skill: each file's path and contents, so any change makes a
21
+ // new version.
22
+ export function skillFingerprint(skill) {
23
+ return { files: skill.files.map((f) => [f.rel, createHash("sha256").update(f.bytes).digest("hex")]) };
24
+ }
25
+ // Hash of a request body with keys sorted, so key order in the YAML doesn't count as a change.
26
+ export function hashBody(body) {
27
+ return createHash("md5").update(canonicalJSON(body)).digest("hex");
28
+ }
29
+ function canonicalJSON(value) {
30
+ if (Array.isArray(value))
31
+ return `[${value.map(canonicalJSON).join(",")}]`;
32
+ if (value && typeof value === "object") {
33
+ const keys = Object.keys(value).sort();
34
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}`).join(",")}}`;
35
+ }
36
+ return JSON.stringify(value);
37
+ }
@@ -0,0 +1,11 @@
1
+ import type { FileMap } from "../lib/files.ts";
2
+ export interface ListMcpToolsOptions {
3
+ fetch?: typeof globalThis.fetch;
4
+ token?: string;
5
+ clientName?: string;
6
+ }
7
+ export declare function listMcpTools(url: string, { fetch, token, clientName }?: ListMcpToolsOptions): Promise<string[] | null>;
8
+ export declare function listedMcpToolset(files: FileMap, url: string, options?: ListMcpToolsOptions): Promise<{
9
+ path: string;
10
+ text: string;
11
+ } | null>;
@@ -0,0 +1,79 @@
1
+ import { readTools, MCP_TOOLSET, mcpToolsetFile } from "../lib/tools.js";
2
+ import { readInstance } from "../lib/instance.js";
3
+ // Just enough of the MCP client protocol (Streamable HTTP) to ask a server for its tools.
4
+ const PROTOCOL_VERSION = "2025-06-18";
5
+ const TIMEOUT_MS = 10_000;
6
+ // The names of the tools an MCP server offers, sorted. Returns null when the server won't say, or
7
+ // can't be reached. Many only say once you've signed in, so `token` is sent if it's given.
8
+ export async function listMcpTools(url, { fetch = globalThis.fetch, token, clientName = "agentschema" } = {}) {
9
+ try {
10
+ let sessionId = null;
11
+ const send = async (message) => {
12
+ const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
13
+ if (sessionId)
14
+ headers["mcp-session-id"] = sessionId;
15
+ if (token)
16
+ headers.authorization = `Bearer ${token}`;
17
+ const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(message), signal: AbortSignal.timeout(TIMEOUT_MS) });
18
+ sessionId = res.headers.get("mcp-session-id") ?? sessionId;
19
+ if (!res.ok)
20
+ throw new Error(`status ${res.status}`);
21
+ return message.id === undefined ? null : parseResponse(await res.text(), message.id);
22
+ };
23
+ await send({
24
+ jsonrpc: "2.0",
25
+ id: 1,
26
+ method: "initialize",
27
+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: clientName, version: "0" } },
28
+ });
29
+ await send({ jsonrpc: "2.0", method: "notifications/initialized" });
30
+ const names = [];
31
+ let cursor;
32
+ let id = 2;
33
+ do {
34
+ // A request with an id always gets its response (or throws), shaped as tools/list says.
35
+ const { result } = (await send({ jsonrpc: "2.0", id: id++, method: "tools/list", params: cursor ? { cursor } : {} }));
36
+ names.push(...result.tools.map((t) => t.name));
37
+ cursor = result.nextCursor;
38
+ } while (cursor);
39
+ return [...new Set(names)].sort();
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ // The tool file for the server at `url`, now listing its tools, once there's a way to ask. Returns
46
+ // { path, text }, or null if there's nothing to change: the file has a table already, so it may hold
47
+ // choices worth keeping, or the agent has no file for that server, or it won't say what it offers.
48
+ export async function listedMcpToolset(files, url, options = {}) {
49
+ const servers = readInstance(files).agent?.data.mcp_servers;
50
+ const server = Array.isArray(servers) ? servers.find((candidate) => candidate?.url === url) : null;
51
+ if (!server)
52
+ return null;
53
+ const tool = readTools(files).tools.find((candidate) => candidate.data.type === MCP_TOOLSET && candidate.data.mcp_server_name === server.name);
54
+ if (!tool || tool.rows?.length)
55
+ return null;
56
+ const names = await listMcpTools(url, options);
57
+ if (!names?.length)
58
+ return null;
59
+ return { path: tool.file, text: mcpToolsetFile({ name: server.name, tools: names, permission: tool.data.default_config?.permission_policy?.type ?? "always_ask" }) };
60
+ }
61
+ // A response is either plain JSON, or a stream of events with the JSON in a `data:` line.
62
+ function parseResponse(text, id) {
63
+ const trimmed = text.trim();
64
+ if (trimmed.startsWith("{"))
65
+ return checked(JSON.parse(trimmed));
66
+ for (const line of trimmed.split("\n")) {
67
+ if (!line.startsWith("data:"))
68
+ continue;
69
+ const message = JSON.parse(line.slice(5));
70
+ if (message.id === id)
71
+ return checked(message);
72
+ }
73
+ throw new Error("no response");
74
+ }
75
+ function checked(message) {
76
+ if (message.error)
77
+ throw new Error(message.error.message);
78
+ return message;
79
+ }
@@ -0,0 +1,14 @@
1
+ export { check } from "./check.ts";
2
+ export { createCredential, deleteCredential } from "./cred.ts";
3
+ export { DeployError, archiveScheduled, deploy, deployFiles, pauseScheduled, prepareLock } from "./deploy.ts";
4
+ export type { DeployAction, DeployFilesOptions, DeployOptions, DeployResult, Log, PlanEntry, PreparedLock, ResourceKind, SaveLock, ScheduledLockOptions, } from "./deploy.ts";
5
+ export { readFolder, updateFrontmatter } from "./folder.ts";
6
+ export { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.ts";
7
+ export type { SkillFingerprint } from "./lock.ts";
8
+ export { listMcpTools, listedMcpToolset } from "./mcp.ts";
9
+ export { OAuthError, authorizationRequest, discover, exchangeCode, registerClient } from "./oauth.ts";
10
+ export { Conversation, SessionError, openSession, startSession } from "./session.ts";
11
+ export type { ConversationUI, CustomToolResult, OpenSessionOptions, Session, SessionEvent, StartSessionOptions, StartedSession, ToolConfirmation, TurnOutcome, } from "./session.ts";
12
+ export type { CreateCredentialOptions, DeleteCredentialOptions } from "./cred.ts";
13
+ export type { ListMcpToolsOptions } from "./mcp.ts";
14
+ export type { AuthorizationRequest, AuthorizationRequestOptions, ExchangeCodeOptions, OAuthServer, RegisterClientOptions, RegisteredClient, Tokens, } from "./oauth.ts";
@@ -0,0 +1,64 @@
1
+ import { DeployError } from "./deploy.ts";
2
+ export declare class OAuthError extends DeployError {
3
+ }
4
+ type Fetch = typeof globalThis.fetch;
5
+ export interface FetchOptions {
6
+ fetch?: Fetch;
7
+ }
8
+ export interface OAuthServer {
9
+ resource: string | null;
10
+ scopesSupported: string[];
11
+ issuer: string;
12
+ authorizationEndpoint: string;
13
+ tokenEndpoint: string;
14
+ registrationEndpoint: string | null;
15
+ codeChallengeMethods: string[] | null;
16
+ }
17
+ export declare function discover(serverUrl: string, { fetch }?: FetchOptions): Promise<OAuthServer>;
18
+ export interface CallbackServer {
19
+ redirectUri: string;
20
+ waitForCode(state: string, timeoutMs?: number): Promise<string>;
21
+ close(): Promise<void>;
22
+ }
23
+ export declare function startCallbackServer(port?: number): Promise<CallbackServer>;
24
+ export interface RegisterClientOptions extends FetchOptions {
25
+ clientName?: string;
26
+ }
27
+ export interface RegisteredClient {
28
+ clientId: string;
29
+ clientSecret: string | null;
30
+ authMethod: string;
31
+ }
32
+ export declare function registerClient(registrationEndpoint: string, redirectUri: string, { fetch, clientName }?: RegisterClientOptions): Promise<RegisteredClient>;
33
+ export interface AuthorizationRequestOptions {
34
+ authorizationEndpoint: string;
35
+ issuer: string;
36
+ clientId: string;
37
+ redirectUri: string;
38
+ scope?: string | null;
39
+ resource?: string | null;
40
+ }
41
+ export interface AuthorizationRequest {
42
+ url: string;
43
+ verifier: string;
44
+ state: string;
45
+ }
46
+ export declare function authorizationRequest({ authorizationEndpoint, issuer, clientId, redirectUri, scope, resource }: AuthorizationRequestOptions): AuthorizationRequest;
47
+ export interface ExchangeCodeOptions {
48
+ tokenEndpoint: string;
49
+ code: string;
50
+ verifier: string;
51
+ redirectUri: string;
52
+ clientId: string;
53
+ clientSecret?: string | null;
54
+ authMethod: string;
55
+ resource?: string | null;
56
+ }
57
+ export interface Tokens {
58
+ accessToken: string;
59
+ refreshToken: string | null;
60
+ expiresAt: string | null;
61
+ scope: string | null;
62
+ }
63
+ export declare function exchangeCode({ tokenEndpoint, code, verifier, redirectUri, clientId, clientSecret, authMethod, resource }: ExchangeCodeOptions, { fetch }?: FetchOptions): Promise<Tokens>;
64
+ export {};
@@ -0,0 +1,208 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { DeployError } from "./deploy.js";
4
+ // OAuth for MCP servers, as the MCP authorization spec describes it: find the server's
5
+ // authorization server from its URL, then sign in through the browser with the authorization
6
+ // code flow and PKCE, receiving the code on a local port.
7
+ // A DeployError, so the CLI reports it like any other failure.
8
+ export class OAuthError extends DeployError {
9
+ }
10
+ const GOOGLE = "accounts.google.com";
11
+ // Finds the OAuth endpoints for an MCP server from its URL alone.
12
+ // Returns { resource, scopesSupported, issuer, authorizationEndpoint, tokenEndpoint,
13
+ // registrationEndpoint, codeChallengeMethods }.
14
+ export async function discover(serverUrl, { fetch = globalThis.fetch } = {}) {
15
+ const url = new URL(serverUrl);
16
+ const path = url.pathname.replace(/\/$/, "");
17
+ // Protected resource metadata (RFC 9728): which authorization server the MCP server trusts. The
18
+ // server can say where that is when it turns away a request with no token, and some put it where
19
+ // the well-known addresses below wouldn't find it, so its word comes first.
20
+ const hinted = await resourceMetadataHint(serverUrl, fetch);
21
+ const resourceMeta = (hinted && (await getJSON(hinted, fetch))) ||
22
+ (path && (await getJSON(`${url.origin}/.well-known/oauth-protected-resource${path}`, fetch))) ||
23
+ (await getJSON(`${url.origin}/.well-known/oauth-protected-resource`, fetch));
24
+ const issuer = resourceMeta?.authorization_servers?.[0] ?? url.origin;
25
+ // Authorization server metadata (RFC 8414), or OpenID Connect discovery, which Google uses.
26
+ const as = new URL(issuer);
27
+ const asPath = as.pathname.replace(/\/$/, "");
28
+ const candidates = [
29
+ `${as.origin}/.well-known/oauth-authorization-server${asPath}`,
30
+ `${as.origin}/.well-known/openid-configuration${asPath}`,
31
+ ...(asPath ? [`${as.origin}${asPath}/.well-known/openid-configuration`] : []),
32
+ ];
33
+ let meta = null;
34
+ for (const candidate of candidates) {
35
+ meta = await getJSON(candidate, fetch);
36
+ if (meta?.authorization_endpoint && meta?.token_endpoint)
37
+ break;
38
+ meta = null;
39
+ }
40
+ if (!meta) {
41
+ throw new OAuthError(`couldn't find the OAuth sign-in for ${serverUrl}: ${issuer} publishes no authorization server metadata`);
42
+ }
43
+ return {
44
+ resource: resourceMeta?.resource ?? null,
45
+ scopesSupported: resourceMeta?.scopes_supported ?? meta.scopes_supported ?? [],
46
+ issuer: meta.issuer ?? issuer,
47
+ // The loop above only keeps metadata that has both.
48
+ authorizationEndpoint: meta.authorization_endpoint,
49
+ tokenEndpoint: meta.token_endpoint,
50
+ registrationEndpoint: meta.registration_endpoint ?? null,
51
+ codeChallengeMethods: meta.code_challenge_methods_supported ?? null,
52
+ };
53
+ }
54
+ // Where the MCP server's 401 says its protected resource metadata is: the resource_metadata
55
+ // parameter of its WWW-Authenticate header. Returns null when it doesn't say.
56
+ async function resourceMetadataHint(serverUrl, fetch) {
57
+ try {
58
+ const res = await fetch(serverUrl, {
59
+ method: "POST",
60
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
61
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "agentschema", version: "0" } } }),
62
+ signal: AbortSignal.timeout(10_000),
63
+ });
64
+ if (res.status !== 401)
65
+ return null;
66
+ const match = /\bresource_metadata\s*=\s*(?:"([^"]*)"|([^\s,]+))/i.exec(res.headers.get("www-authenticate") ?? "");
67
+ const hint = match?.[1] ?? match?.[2];
68
+ return hint && URL.canParse(hint) ? hint : null;
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ // The parsed body as T, unchecked: callers only read optional fields from it.
75
+ async function getJSON(url, fetch) {
76
+ try {
77
+ const res = await fetch(url, { headers: { accept: "application/json" } });
78
+ if (!res.ok)
79
+ return null;
80
+ return (await res.json());
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
86
+ export async function startCallbackServer(port = 0) {
87
+ let deliver;
88
+ const received = new Promise((resolve) => (deliver = resolve));
89
+ const server = createServer((req, res) => {
90
+ const url = new URL(req.url, "http://127.0.0.1"); // always set on a server's requests
91
+ if (url.pathname !== "/callback") {
92
+ res.writeHead(404).end();
93
+ return;
94
+ }
95
+ const error = url.searchParams.get("error");
96
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
97
+ res.end(`<!doctype html><title>agentschema</title><body style="font:16px system-ui;margin:4em auto;max-width:30em">` +
98
+ (error ? `<h1>Sign-in failed</h1><p>${escape(error)}. Check the terminal.</p>` : "<h1>Signed in</h1><p>You can close this tab and go back to the terminal.</p>") +
99
+ "</body>");
100
+ deliver(url.searchParams);
101
+ });
102
+ await new Promise((resolve, reject) => {
103
+ server.once("error", (err) => reject(new OAuthError(`couldn't listen on 127.0.0.1:${port}: ${err.message}`)));
104
+ server.listen(port, "127.0.0.1", resolve);
105
+ });
106
+ // Listening on a TCP host and port, so address() is an AddressInfo.
107
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
108
+ return {
109
+ redirectUri,
110
+ async waitForCode(state, timeoutMs = 5 * 60_000) {
111
+ let timer;
112
+ const timeout = new Promise((_, reject) => {
113
+ timer = setTimeout(() => reject(new OAuthError("timed out waiting for the browser sign-in")), timeoutMs);
114
+ });
115
+ try {
116
+ const params = await Promise.race([received, timeout]);
117
+ const error = params.get("error");
118
+ if (error) {
119
+ const detail = params.get("error_description");
120
+ throw new OAuthError(`sign-in failed: ${error}${detail ? ` (${detail})` : ""}`);
121
+ }
122
+ if (params.get("state") !== state)
123
+ throw new OAuthError("sign-in failed: the response's state didn't match");
124
+ const code = params.get("code");
125
+ if (!code)
126
+ throw new OAuthError("sign-in failed: no authorization code came back");
127
+ return code;
128
+ }
129
+ finally {
130
+ clearTimeout(timer);
131
+ }
132
+ },
133
+ close: () => new Promise((resolve) => server.close(() => resolve())),
134
+ };
135
+ }
136
+ const ENTITIES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
137
+ const escape = (s) => s.replace(/[&<>"]/g, (c) => ENTITIES[c]);
138
+ export async function registerClient(registrationEndpoint, redirectUri, { fetch = globalThis.fetch, clientName = "agentschema" } = {}) {
139
+ const res = await fetch(registrationEndpoint, {
140
+ method: "POST",
141
+ headers: { "content-type": "application/json", accept: "application/json" },
142
+ body: JSON.stringify({
143
+ client_name: clientName,
144
+ redirect_uris: [redirectUri],
145
+ grant_types: ["authorization_code", "refresh_token"],
146
+ response_types: ["code"],
147
+ token_endpoint_auth_method: "none",
148
+ }),
149
+ });
150
+ const body = (await res.json().catch(() => ({})));
151
+ if (!res.ok || !body.client_id) {
152
+ throw new OAuthError(`couldn't register a client at ${registrationEndpoint} (${res.status}): ${body.error_description ?? body.error ?? "no client_id in the response"}`);
153
+ }
154
+ return {
155
+ clientId: body.client_id,
156
+ clientSecret: body.client_secret ?? null,
157
+ authMethod: body.token_endpoint_auth_method ?? (body.client_secret ? "client_secret_post" : "none"),
158
+ };
159
+ }
160
+ export function authorizationRequest({ authorizationEndpoint, issuer, clientId, redirectUri, scope, resource }) {
161
+ const verifier = base64url(randomBytes(32));
162
+ const state = base64url(randomBytes(16));
163
+ const url = new URL(authorizationEndpoint);
164
+ const params = {
165
+ response_type: "code",
166
+ client_id: clientId,
167
+ redirect_uri: redirectUri,
168
+ code_challenge: base64url(createHash("sha256").update(verifier).digest()),
169
+ code_challenge_method: "S256",
170
+ state,
171
+ };
172
+ if (scope)
173
+ params.scope = scope;
174
+ if (resource)
175
+ params.resource = resource;
176
+ // Google only issues a refresh token for offline access, and only on a fresh consent.
177
+ if (new URL(issuer).host === GOOGLE)
178
+ Object.assign(params, { access_type: "offline", prompt: "consent" });
179
+ for (const [k, v] of Object.entries(params))
180
+ url.searchParams.set(k, v);
181
+ return { url: url.toString(), verifier, state };
182
+ }
183
+ export async function exchangeCode({ tokenEndpoint, code, verifier, redirectUri, clientId, clientSecret, authMethod, resource }, { fetch = globalThis.fetch } = {}) {
184
+ const form = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, code_verifier: verifier });
185
+ if (resource)
186
+ form.set("resource", resource);
187
+ const headers = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
188
+ if (authMethod === "client_secret_basic") {
189
+ headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString("base64")}`;
190
+ }
191
+ else {
192
+ form.set("client_id", clientId);
193
+ if (authMethod === "client_secret_post")
194
+ form.set("client_secret", clientSecret);
195
+ }
196
+ const res = await fetch(tokenEndpoint, { method: "POST", headers, body: form });
197
+ const body = (await res.json().catch(() => ({})));
198
+ if (!res.ok || !body.access_token) {
199
+ throw new OAuthError(`the token endpoint refused the sign-in (${res.status}): ${body.error_description ?? body.error ?? "no access token in the response"}`);
200
+ }
201
+ return {
202
+ accessToken: body.access_token,
203
+ refreshToken: body.refresh_token ?? null,
204
+ expiresAt: body.expires_in ? new Date(Date.now() + Number(body.expires_in) * 1000).toISOString() : null,
205
+ scope: body.scope ?? null,
206
+ };
207
+ }
208
+ const base64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -0,0 +1,18 @@
1
+ export type PromptInput = NodeJS.ReadableStream & {
2
+ isTTY?: boolean;
3
+ };
4
+ export interface PromptsOptions {
5
+ cancelled?: () => Error;
6
+ }
7
+ export interface TextOptions {
8
+ validate?: (reply: string) => string | null | undefined | void;
9
+ }
10
+ export interface Prompts {
11
+ text(question: string, fallback?: string, options?: TextOptions): Promise<string>;
12
+ select(question: string, choices: readonly string[], fallback: string): Promise<string>;
13
+ confirm(question: string, fallback?: boolean): Promise<boolean>;
14
+ secret(question: string): Promise<string>;
15
+ close(): void;
16
+ ended?(): boolean;
17
+ }
18
+ export declare function prompts(input: PromptInput, output: NodeJS.WritableStream, { cancelled }?: PromptsOptions): Prompts;
@@ -0,0 +1,166 @@
1
+ import { createInterface, emitKeypressEvents } from "node:readline";
2
+ // Interactive questions, shared by `init` and `cred create`. In a terminal, choices are picked
3
+ // with the arrow keys and secrets aren't echoed; with piped input, each answer is a line.
4
+ //
5
+ // text(question, fallback, { validate }) an empty reply keeps the fallback; validate returns
6
+ // an error message, or nothing when the reply is fine
7
+ // select(question, choices, fallback) one of `choices` (strings)
8
+ // confirm(question, fallback) true or false
9
+ // secret(question) a reply that isn't shown
10
+ // close()
11
+ //
12
+ // Ctrl+C rejects with the error `cancelled()` returns.
13
+ export function prompts(input, output, { cancelled = () => new Error("cancelled") } = {}) {
14
+ // isTTY is only true on a tty.ReadStream, which has setRawMode.
15
+ const base = input.isTTY ? terminalPrompts(input, output, cancelled) : linePrompts(input, output, cancelled);
16
+ const text = async (question, fallback = "", { validate } = {}) => {
17
+ while (true) {
18
+ const reply = await base.text(question, fallback);
19
+ const problem = validate?.(reply);
20
+ if (!problem)
21
+ return reply;
22
+ output.write(`${problem}\n`);
23
+ if (base.ended?.())
24
+ throw cancelled();
25
+ }
26
+ };
27
+ const confirm = async (question, fallback) => {
28
+ while (true) {
29
+ const reply = (await base.text(`${question} [y/n]`, fallback ? "y" : "n")).toLowerCase();
30
+ if (/^(y|yes)$/.test(reply))
31
+ return true;
32
+ if (/^(n|no)$/.test(reply))
33
+ return false;
34
+ output.write("Answer y or n\n");
35
+ }
36
+ };
37
+ return { ...base, text, confirm };
38
+ }
39
+ // Prompts for piped input: one answer per line, and choices picked by name or number.
40
+ function linePrompts(input, output, cancelled) {
41
+ const rl = createInterface({ input, output, terminal: false });
42
+ const lines = rl[Symbol.asyncIterator]();
43
+ let ended = false;
44
+ const line = async () => {
45
+ if (ended)
46
+ return null;
47
+ const { value, done } = await lines.next();
48
+ if (done) {
49
+ ended = true;
50
+ output.write("\n");
51
+ return null;
52
+ }
53
+ return value.trim();
54
+ };
55
+ const text = async (question, fallback) => {
56
+ output.write(fallback ? `${question} (${fallback}) ` : `${question} `);
57
+ return (await line()) || fallback;
58
+ };
59
+ const select = async (question, choices, fallback) => {
60
+ const listed = choices.map((c, i) => `${i + 1}) ${c}`).join(" ");
61
+ while (true) {
62
+ const reply = await text(`${question} ${listed}`, String(choices.indexOf(fallback) + 1 || 1));
63
+ const picked = choices[Number(reply) - 1] ?? choices.find((c) => c === reply);
64
+ if (picked)
65
+ return picked;
66
+ output.write(`Pick one of: ${choices.join(", ")}\n`);
67
+ if (ended)
68
+ throw cancelled();
69
+ }
70
+ };
71
+ const secret = async (question) => {
72
+ output.write(`${question} `);
73
+ const reply = await line();
74
+ if (reply === null)
75
+ throw cancelled();
76
+ return reply;
77
+ };
78
+ return { text, select, secret, ended: () => ended, close: () => rl.close() };
79
+ }
80
+ const ESC = "\x1b[";
81
+ const cyan = (s) => `${ESC}36m${s}${ESC}0m`;
82
+ const dim = (s) => `${ESC}2m${s}${ESC}0m`;
83
+ // Prompts for a terminal: choices are picked with the arrow keys and Enter.
84
+ function terminalPrompts(input, output, cancelled) {
85
+ // A fresh readline per question, so it doesn't fight the raw-mode select for the arrow keys.
86
+ const text = (question, fallback) => new Promise((resolve, reject) => {
87
+ const rl = createInterface({ input, output, terminal: true });
88
+ rl.on("SIGINT", () => {
89
+ rl.close();
90
+ output.write("\n");
91
+ reject(cancelled());
92
+ });
93
+ rl.question(fallback ? `${question} ${dim(`(${fallback})`)} ` : `${question} `, (reply) => {
94
+ rl.close();
95
+ resolve(reply.trim() || fallback);
96
+ });
97
+ });
98
+ const select = (question, choices, fallback) => new Promise((resolve, reject) => {
99
+ let index = Math.max(0, choices.indexOf(fallback));
100
+ const render = (first) => {
101
+ if (!first)
102
+ output.write(`${ESC}${choices.length}A`);
103
+ for (const [i, choice] of choices.entries()) {
104
+ output.write(`${ESC}2K${i === index ? cyan(`❯ ${choice}`) : ` ${choice}`}\n`);
105
+ }
106
+ };
107
+ const finish = (err) => {
108
+ input.off("keypress", onKey);
109
+ input.setRawMode(false);
110
+ input.pause();
111
+ // Collapse the list to one line with the answer.
112
+ output.write(`${ESC}${choices.length + 1}A${ESC}J${ESC}?25h`);
113
+ output.write(`${question} ${err ? dim("cancelled") : cyan(choices[index])}\n`);
114
+ err ? reject(err) : resolve(choices[index]);
115
+ };
116
+ const onKey = (str, key = {}) => {
117
+ if (key.ctrl && key.name === "c")
118
+ return finish(cancelled());
119
+ if (key.name === "return" || key.name === "enter")
120
+ return finish();
121
+ if (key.name === "up" || key.name === "k")
122
+ index = (index - 1 + choices.length) % choices.length;
123
+ else if (key.name === "down" || key.name === "j" || key.name === "tab")
124
+ index = (index + 1) % choices.length;
125
+ else if (/^[1-9]$/.test(str ?? "") && Number(str) <= choices.length)
126
+ index = Number(str) - 1;
127
+ else
128
+ return;
129
+ render(false);
130
+ };
131
+ emitKeypressEvents(input);
132
+ input.setRawMode(true);
133
+ input.resume();
134
+ output.write(`${question} ${dim("(↑/↓, Enter)")}\n${ESC}?25l`);
135
+ render(true);
136
+ input.on("keypress", onKey);
137
+ });
138
+ // Not echoed, so the secret doesn't end up on screen or in the scrollback; pasting works.
139
+ const secret = (question) => new Promise((resolve, reject) => {
140
+ output.write(`${question} ${dim("(hidden)")} `);
141
+ input.setRawMode(true);
142
+ input.resume();
143
+ let answer = "";
144
+ const finish = (err) => {
145
+ input.off("data", onData);
146
+ input.setRawMode(false);
147
+ input.pause();
148
+ output.write("\n");
149
+ err ? reject(err) : resolve(answer.trim());
150
+ };
151
+ const onData = (chunk) => {
152
+ for (const ch of chunk.toString("utf8")) {
153
+ if (ch === "\r" || ch === "\n")
154
+ return finish();
155
+ if (ch === "\u0003")
156
+ return finish(cancelled());
157
+ if (ch === "\u007f" || ch === "\b")
158
+ answer = answer.slice(0, -1);
159
+ else if (ch >= " ")
160
+ answer += ch;
161
+ }
162
+ };
163
+ input.on("data", onData);
164
+ });
165
+ return { text, select, secret, close() { } };
166
+ }