@typeship-ax/mcp 0.6.0 → 0.9.1

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 (114) hide show
  1. package/AGENTS.md +31 -0
  2. package/README.md +67 -10
  3. package/api.json +6735 -3243
  4. package/api.md +8537 -248
  5. package/dist/api-identity.d.ts +40 -0
  6. package/dist/api-identity.d.ts.map +1 -0
  7. package/dist/api-identity.js +128 -0
  8. package/dist/auth-profiles.d.ts +30 -0
  9. package/dist/auth-profiles.d.ts.map +1 -0
  10. package/dist/auth-profiles.js +138 -0
  11. package/dist/core/http.d.ts +21 -92
  12. package/dist/core/http.d.ts.map +1 -1
  13. package/dist/core/http.js +143 -221
  14. package/dist/core/pagination.d.ts.map +1 -1
  15. package/dist/core/pagination.js +6 -34
  16. package/dist/credential-storage.d.ts +24 -0
  17. package/dist/credential-storage.d.ts.map +1 -0
  18. package/dist/credential-storage.js +207 -0
  19. package/dist/dates.d.ts +0 -2
  20. package/dist/dates.d.ts.map +1 -1
  21. package/dist/dates.js +0 -1
  22. package/dist/docs.d.ts +36 -0
  23. package/dist/docs.d.ts.map +1 -0
  24. package/dist/docs.js +258 -0
  25. package/dist/errors.d.ts +42 -34
  26. package/dist/errors.d.ts.map +1 -1
  27. package/dist/errors.js +30 -20
  28. package/dist/index.d.ts +27 -12
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +40 -14
  31. package/dist/mcp-authorization.d.ts +52 -0
  32. package/dist/mcp-authorization.d.ts.map +1 -0
  33. package/dist/mcp-authorization.js +232 -0
  34. package/dist/mcp-protocol.d.ts +69 -25
  35. package/dist/mcp-protocol.d.ts.map +1 -1
  36. package/dist/mcp-protocol.js +386 -138
  37. package/dist/mcp.d.ts +21 -3
  38. package/dist/mcp.d.ts.map +1 -1
  39. package/dist/mcp.js +199 -85
  40. package/dist/named-credentials.d.ts +21 -0
  41. package/dist/named-credentials.d.ts.map +1 -0
  42. package/dist/named-credentials.js +86 -0
  43. package/dist/oauth-request.d.ts +21 -0
  44. package/dist/oauth-request.d.ts.map +1 -0
  45. package/dist/oauth-request.js +119 -0
  46. package/dist/oauth-session.d.ts +106 -0
  47. package/dist/oauth-session.d.ts.map +1 -0
  48. package/dist/oauth-session.js +244 -0
  49. package/dist/ops.d.ts +18 -0
  50. package/dist/ops.d.ts.map +1 -1
  51. package/dist/ops.js +31 -17
  52. package/dist/resources/account.d.ts +4 -4
  53. package/dist/resources/account.d.ts.map +1 -1
  54. package/dist/resources/account.js +1 -0
  55. package/dist/resources/api-keys.d.ts +13 -8
  56. package/dist/resources/api-keys.d.ts.map +1 -1
  57. package/dist/resources/api-keys.js +5 -1
  58. package/dist/resources/definition-revisions.d.ts +58 -0
  59. package/dist/resources/definition-revisions.d.ts.map +1 -0
  60. package/dist/resources/definition-revisions.js +114 -0
  61. package/dist/resources/definitions.d.ts +35 -0
  62. package/dist/resources/definitions.d.ts.map +1 -0
  63. package/dist/resources/definitions.js +60 -0
  64. package/dist/resources/generate.d.ts +18 -7
  65. package/dist/resources/generate.d.ts.map +1 -1
  66. package/dist/resources/generate.js +13 -5
  67. package/dist/resources/generations.d.ts +6 -6
  68. package/dist/resources/generations.d.ts.map +1 -1
  69. package/dist/resources/generations.js +3 -1
  70. package/dist/resources/projects.d.ts +111 -35
  71. package/dist/resources/projects.d.ts.map +1 -1
  72. package/dist/resources/projects.js +125 -15
  73. package/dist/resources/targets.d.ts +97 -0
  74. package/dist/resources/targets.d.ts.map +1 -0
  75. package/dist/resources/targets.js +197 -0
  76. package/dist/schemas.d.ts.map +1 -1
  77. package/dist/schemas.js +135 -62
  78. package/dist/types.d.ts +2072 -267
  79. package/dist/types.d.ts.map +1 -1
  80. package/dist/types.js +20 -3
  81. package/dist/worker.js +4 -4
  82. package/package.json +11 -1
  83. package/server.json +42 -0
  84. package/src/api-identity.ts +98 -0
  85. package/src/auth-profiles.ts +114 -0
  86. package/src/core/http.ts +156 -305
  87. package/src/core/pagination.ts +6 -30
  88. package/src/credential-storage.ts +183 -0
  89. package/src/dates.ts +0 -1
  90. package/src/docs.ts +239 -0
  91. package/src/errors.ts +52 -41
  92. package/src/index.ts +49 -14
  93. package/src/mcp-authorization.ts +211 -0
  94. package/src/mcp-protocol.ts +432 -133
  95. package/src/mcp.ts +204 -90
  96. package/src/named-credentials.ts +74 -0
  97. package/src/oauth-request.ts +90 -0
  98. package/src/oauth-session.ts +258 -0
  99. package/src/ops.ts +56 -17
  100. package/src/resources/account.ts +6 -3
  101. package/src/resources/api-keys.ts +27 -7
  102. package/src/resources/definition-revisions.ts +207 -0
  103. package/src/resources/definitions.ts +122 -0
  104. package/src/resources/generate.ts +29 -6
  105. package/src/resources/generations.ts +9 -4
  106. package/src/resources/projects.ts +274 -41
  107. package/src/resources/targets.ts +378 -0
  108. package/src/schemas.ts +135 -62
  109. package/src/types.ts +2273 -322
  110. package/src/worker.ts +4 -4
  111. package/dist/resources/spec-revisions.d.ts +0 -47
  112. package/dist/resources/spec-revisions.d.ts.map +0 -1
  113. package/dist/resources/spec-revisions.js +0 -90
  114. package/src/resources/spec-revisions.ts +0 -150
@@ -74,26 +74,11 @@ export class Page<Item, E = unknown> {
74
74
  case "cursor": {
75
75
  const next = getPath(this.body, config.nextCursorField!);
76
76
  if (next === undefined || next === null || next === "") return null;
77
+ if (next === params[config.cursorParam!]) return null;
77
78
  return { ...params, [config.cursorParam!]: next };
78
79
  }
79
- case "cursorFromLastId": {
80
- if (items.length === 0) return null;
81
- const last = items[items.length - 1] as Record<string, unknown>;
82
- const id = last?.[config.idField ?? "id"];
83
- if (id === undefined || id === null) return null;
84
- return { ...params, [config.cursorParam!]: id };
85
- }
86
- case "page": {
87
- if (!this.looksLikeMore(items)) return null;
88
- const current = Number(params[config.pageParam!] ?? 1);
89
- return { ...params, [config.pageParam!]: current + 1 };
90
- }
91
- case "offset": {
92
- if (!this.looksLikeMore(items)) return null;
93
- const current = Number(params[config.offsetParam!] ?? 0);
94
- return { ...params, [config.offsetParam!]: current + items.length };
95
- }
96
80
  }
81
+ return null;
97
82
  }
98
83
 
99
84
  /** Fetch the next page, or null when this is the last one. Throws the typed error on failure. */
@@ -159,26 +144,17 @@ export function paginate<Item, E>(
159
144
  req: CoreRequest,
160
145
  config: PageConfig,
161
146
  ): PagePromise<Item, E> {
162
- const isGraphql = req.graphqlField !== undefined;
147
+ const isGraphql = false
148
+ ;
163
149
  const fetchPage: FetchPage<Item, E> = async (params) => {
164
- const nextReq = isGraphql
165
- ? {
166
- ...req,
167
- body: {
168
- ...(req.body as Record<string, unknown>),
169
- variables: { ...((req.body as { variables?: Record<string, unknown> })?.variables ?? {}), ...params },
170
- },
171
- }
172
- : { ...req, query: params };
150
+ let nextReq: CoreRequest = { ...req, query: params };
173
151
  const result = await core.request<unknown, E>(nextReq);
174
152
  if (!result.ok) return result;
175
153
  const page = new Page<Item, E>(fetchPage, config, params, result.data, result.response);
176
154
  return { ok: true, data: page, response: result.response };
177
155
  };
178
156
  const initial: Record<string, unknown> = {};
179
- const seed = isGraphql
180
- ? ((req.body as { variables?: Record<string, unknown> })?.variables ?? {})
181
- : (req.query ?? {});
157
+ let seed = req.query ?? {};
182
158
  for (const [k, v] of Object.entries(seed)) {
183
159
  if (v !== undefined) initial[k] = v;
184
160
  }
@@ -0,0 +1,183 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { FileCredentialStore, CredentialStorageError, type CredentialCodec } from "./oauth-session.js";
6
+
7
+ export interface NativeCommandResult { status: number | null; stdout: string; stderr: string; error?: unknown }
8
+ export type NativeCommand = (executable: string, args: string[], input?: string) => NativeCommandResult;
9
+ export interface CredentialKeyStore {
10
+ readonly name: string;
11
+ read(): Buffer | null;
12
+ write(key: Buffer): void;
13
+ /** Used only when explicitly removing this wrapping key, not ordinary logout. */
14
+ remove(): void;
15
+ }
16
+
17
+ const nativeCommand: NativeCommand = (executable, args, input) => {
18
+ const result = spawnSync(executable, args, { input, encoding: "utf8", timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true, shell: false });
19
+ return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "", ...(result.error ? { error: result.error } : {}) };
20
+ };
21
+
22
+ function unavailable(name: string, environmentName: string): never {
23
+ throw new CredentialStorageError("Cannot access " + name + ". Unlock or enable your OS credential store and retry. For a headless session, supply credentials through environment variables. Plaintext storage requires explicitly setting " + environmentName + "=file.");
24
+ }
25
+ function parseKey(value: string): Buffer {
26
+ const encoded = value.trim();
27
+ if (!/^[A-Za-z0-9+/]{43}=$/.test(encoded)) throw new CredentialStorageError("The OS credential key is invalid. Restore access to the original key before using the saved session.");
28
+ const key = Buffer.from(encoded, "base64");
29
+ if (key.length !== 32) throw new CredentialStorageError("The OS credential key is invalid.");
30
+ return key;
31
+ }
32
+
33
+ /** A small wrapping key avoids OS item-size limits; session files are encrypted
34
+ * separately so refresh rotation can retain the atomic file/lock transaction. */
35
+ export function nativeCredentialKeyStore(path: string, platform: NodeJS.Platform = process.platform, run: NativeCommand = nativeCommand, environmentName = "CREDENTIAL_STORE"): CredentialKeyStore {
36
+ const failed = (name: string): never => unavailable(name, environmentName);
37
+ const identity = createHash("sha256").update(resolve(path)).digest("hex");
38
+ const service = "typeship.credentials." + identity;
39
+ const account = "session-key";
40
+ if (platform === "darwin") {
41
+ const name = "macOS Keychain";
42
+ const lookup = () => run("/usr/bin/security", ["find-generic-password", "-s", service, "-a", account, "-w"]);
43
+ return {
44
+ name,
45
+ read() {
46
+ const result = lookup();
47
+ if (!result.error && result.status === 44) return null; // errSecItemNotFound
48
+ if (result.error || result.status !== 0) return failed(name);
49
+ return parseKey(result.stdout);
50
+ },
51
+ write(key) {
52
+ // security's interactive command stream keeps the key off argv. All
53
+ // tokens below have a fixed safe alphabet; no shell or user text is run.
54
+ const input = "add-generic-password -U -s " + service + " -a " + account + " -w " + key.toString("base64") + "\n";
55
+ const result = run("/usr/bin/security", ["-i"], input);
56
+ if (result.error || result.status !== 0) return failed(name);
57
+ // Verify the write: an interactive tool's process status alone is not
58
+ // sufficient evidence that its command stored the requested item.
59
+ const saved = this.read();
60
+ if (!saved || !timingSafeEqual(saved, key)) return failed(name);
61
+ },
62
+ remove() {
63
+ const result = run("/usr/bin/security", ["delete-generic-password", "-s", service, "-a", account]);
64
+ if (result.error || (result.status !== 0 && result.status !== 44)) failed(name);
65
+ },
66
+ };
67
+ }
68
+ if (platform === "linux") {
69
+ const name = "Linux Secret Service (secret-tool)";
70
+ const attributes = ["service", service, "account", account];
71
+ return {
72
+ name,
73
+ read() {
74
+ const result = run("/usr/bin/secret-tool", ["lookup", ...attributes]);
75
+ if (!result.error && result.status === 1 && !result.stderr.trim()) return null;
76
+ if (result.error || result.status !== 0) return failed(name);
77
+ return parseKey(result.stdout);
78
+ },
79
+ write(key) {
80
+ const result = run("/usr/bin/secret-tool", ["store", "--label=CLI session encryption key", ...attributes], key.toString("base64"));
81
+ if (result.error || result.status !== 0) return failed(name);
82
+ const saved = this.read();
83
+ if (!saved || !timingSafeEqual(saved, key)) return failed(name);
84
+ },
85
+ remove() {
86
+ const result = run("/usr/bin/secret-tool", ["clear", ...attributes]);
87
+ if (result.error || result.status !== 0) failed(name);
88
+ },
89
+ };
90
+ }
91
+ if (platform === "win32") {
92
+ const name = "Windows DPAPI (current user)";
93
+ const keyPath = path + ".key";
94
+ const executable = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
95
+ const script = `
96
+ $ErrorActionPreference = 'Stop'
97
+ try {
98
+ Add-Type -AssemblyName System.Security
99
+ $payload = [Console]::In.ReadToEnd() | ConvertFrom-Json
100
+ $bytes = [Convert]::FromBase64String([string]$payload.data)
101
+ $entropy = [Text.Encoding]::UTF8.GetBytes([string]$payload.service)
102
+ $scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
103
+ if ($payload.action -eq 'protect') { $result = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $entropy, $scope) }
104
+ elseif ($payload.action -eq 'unprotect') { $result = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $entropy, $scope) }
105
+ else { exit 1 }
106
+ [Console]::Out.Write([Convert]::ToBase64String($result))
107
+ exit 0
108
+ } catch { exit 1 }
109
+ `;
110
+ const crypt = (action: "protect" | "unprotect", data: string) => {
111
+ // EncodedCommand contains fixed code only. Sensitive data goes over stdin.
112
+ const result = run(executable, ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], JSON.stringify({ action, data, service }));
113
+ if (result.error || result.status !== 0 || !result.stdout.trim()) return failed(name);
114
+ return result.stdout.trim();
115
+ };
116
+ return {
117
+ name,
118
+ read() {
119
+ let wrapped: string;
120
+ try { wrapped = readFileSync(keyPath, "utf8"); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; return failed(name); }
121
+ return parseKey(crypt("unprotect", wrapped));
122
+ },
123
+ write(key) {
124
+ const wrapped = crypt("protect", key.toString("base64"));
125
+ const temporary = keyPath + "." + randomBytes(16).toString("hex") + ".tmp";
126
+ try {
127
+ writeFileSync(temporary, wrapped, { mode: 0o600, flag: "wx", flush: true });
128
+ renameSync(temporary, keyPath);
129
+ } finally { rmSync(temporary, { force: true }); }
130
+ const saved = this.read();
131
+ if (!saved || !timingSafeEqual(saved, key)) return failed(name);
132
+ },
133
+ remove() { rmSync(keyPath, { force: true }); },
134
+ };
135
+ }
136
+ return { name: "OS credential storage", read: () => failed("OS credential storage on this platform"), write: () => failed("OS credential storage on this platform"), remove: () => failed("OS credential storage on this platform") };
137
+ }
138
+
139
+ export function encryptedCredentialCodec(path: string, keyStore: CredentialKeyStore): CredentialCodec {
140
+ const associatedData = Buffer.from("cli-credentials-v1:" + resolve(path));
141
+ const key = (create: boolean) => {
142
+ const saved = keyStore.read();
143
+ if (saved) return saved;
144
+ if (!create || existsSync(path)) throw new CredentialStorageError("The encryption key for this saved session is missing. Restore the original OS credential store, or run logout --local to remove the saved encrypted session before logging in again.");
145
+ const generated = randomBytes(32);
146
+ keyStore.write(generated);
147
+ return generated;
148
+ };
149
+ return {
150
+ name: keyStore.name,
151
+ prepare() { key(true); },
152
+ encode(plaintext) {
153
+ const nonce = randomBytes(12);
154
+ const cipher = createCipheriv("aes-256-gcm", key(true), nonce);
155
+ cipher.setAAD(associatedData);
156
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
157
+ return JSON.stringify({ version: 1, algorithm: "aes-256-gcm", nonce: nonce.toString("base64"), tag: cipher.getAuthTag().toString("base64"), ciphertext: ciphertext.toString("base64") });
158
+ },
159
+ decode(encoded) {
160
+ let envelope: { version?: unknown; algorithm?: unknown; nonce?: unknown; tag?: unknown; ciphertext?: unknown };
161
+ try { envelope = JSON.parse(encoded); } catch { throw new CredentialStorageError("Saved encrypted credentials are damaged. Restore the credential file before logging in again."); }
162
+ if (!envelope || envelope.version !== 1 || envelope.algorithm !== "aes-256-gcm" || typeof envelope.nonce !== "string" || typeof envelope.tag !== "string" || typeof envelope.ciphertext !== "string") throw new CredentialStorageError("Saved encrypted credentials use an invalid format.");
163
+ const secret = key(false);
164
+ try {
165
+ const nonce = Buffer.from(envelope.nonce, "base64"), tag = Buffer.from(envelope.tag, "base64");
166
+ if (nonce.length !== 12 || tag.length !== 16) throw new Error();
167
+ const decipher = createDecipheriv("aes-256-gcm", secret, nonce);
168
+ decipher.setAAD(associatedData); decipher.setAuthTag(tag);
169
+ return Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64")), decipher.final()]).toString("utf8");
170
+ } catch { throw new CredentialStorageError("Saved credentials could not be authenticated. Restore the original credential file and OS key; do not reuse this session."); }
171
+ },
172
+ };
173
+ }
174
+
175
+ /** OS protection is the default. Plaintext storage is an explicit, separate
176
+ * store for environments where the owner accepts that tradeoff. Never migrate
177
+ * or fall back silently when an OS service is unavailable. */
178
+ export function createCredentialStore(directory: string, mode: string = "os", environmentName = "CREDENTIAL_STORE"): FileCredentialStore {
179
+ if (mode === "file") return new FileCredentialStore(join(directory, "credentials.json"));
180
+ if (mode !== "os") throw new CredentialStorageError(environmentName + " must be os or file.");
181
+ const path = join(directory, "credentials.enc");
182
+ return new FileCredentialStore(path, 40_000, encryptedCredentialCodec(path, nativeCredentialKeyStore(path, process.platform, nativeCommand, environmentName)));
183
+ }
package/src/dates.ts CHANGED
@@ -29,7 +29,6 @@ const CALENDAR_UNITS = new Set(["mo", "month", "y", "yr", "year"]);
29
29
  const HINT = "Use a signed form: -7d or -P7D for seven days ago, +7d or +P7D for seven days ahead; or an absolute ISO 8601 value.";
30
30
 
31
31
  /** The forms a date-shaped argument accepts, for descriptions and help. */
32
- export const RELATIVE_DATE_HINT = "Accepts ISO 8601 or a relative form: -P7D, -7d, 7 days ago, today, now.";
33
32
 
34
33
  function shift(base: Date, amount: number, unit: string): Date {
35
34
  const d = new Date(base.getTime());
package/src/docs.ts ADDED
@@ -0,0 +1,239 @@
1
+ /** Shared documentation-fetch boundary for generated CLI and MCP surfaces. */
2
+
3
+ export const MAX_DOCS_TEXT_BYTES = 2_000_000;
4
+
5
+ export function resolveDocsPageUrl(base: string | null, pathOrFile: string): string | null {
6
+ if (base === null) return null;
7
+ try {
8
+ const baseUrl = new URL(base);
9
+ if ((baseUrl.protocol !== "https:" && baseUrl.protocol !== "http:") || baseUrl.username || baseUrl.password) return null;
10
+ const target = /^https?:\/\//.test(pathOrFile)
11
+ ? new URL(pathOrFile)
12
+ : new URL(pathOrFile.replace(/^\/+/, ""), baseUrl.toString().replace(/\/+$/, "") + "/");
13
+ return target.origin === baseUrl.origin && !target.username && !target.password ? target.toString() : null;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+
19
+ /** Resolve conventional docs files while honoring an explicitly configured
20
+ * llms.txt location. Guide links may live on either the docs-site origin or
21
+ * the index origin; no other origin is accepted. */
22
+ export function resolveDocsContentUrl(
23
+ base: string | null,
24
+ indexUrl: string | null,
25
+ pathOrFile: string,
26
+ ): string | null {
27
+ const exactIndex = safeHttpUrl(indexUrl);
28
+ if (pathOrFile === "llms.txt" && exactIndex) return exactIndex;
29
+ if (pathOrFile === "llms-full.txt" && exactIndex) {
30
+ try { return new URL("llms-full.txt", exactIndex).toString(); } catch { return null; }
31
+ }
32
+ const primary = resolveDocsPageUrl(base, pathOrFile);
33
+ if (primary) return primary;
34
+ if (!exactIndex) return null;
35
+ try {
36
+ const target = /^https?:\/\//.test(pathOrFile)
37
+ ? new URL(pathOrFile)
38
+ : new URL(pathOrFile.replace(/^\/+/, ""), exactIndex);
39
+ const allowed = new URL(exactIndex);
40
+ return target.origin === allowed.origin && !target.username && !target.password ? target.toString() : null;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ function safeHttpUrl(value: string | null): string | null {
47
+ if (!value) return null;
48
+ try {
49
+ const parsed = new URL(value);
50
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && !parsed.username && !parsed.password
51
+ ? parsed.toString()
52
+ : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ export interface GuideMatch {
59
+ title: string;
60
+ section: string | null;
61
+ /** Kept for callers that displayed the original heading-only results. */
62
+ heading: string;
63
+ excerpt: string;
64
+ url: string;
65
+ }
66
+
67
+ interface GuidePage { title: string; url: string; description: string }
68
+
69
+ /** Links in an index follow URL semantics, including site-root relative links. */
70
+ function docsLink(base: string | null, indexUrl: string | null, value: string): string | null {
71
+ const index = resolveDocsContentUrl(base, indexUrl, "llms.txt");
72
+ if (!index) return null;
73
+ try { return resolveDocsContentUrl(base, indexUrl, new URL(value, index).toString()); }
74
+ catch { return null; }
75
+ }
76
+
77
+ export function docsIndexPages(index: string | null, base: string | null, indexUrl: string | null): GuidePage[] {
78
+ const pages = new Map<string, GuidePage>();
79
+ for (const line of (index ?? "").split("\n")) {
80
+ for (const match of line.matchAll(/\[([^\]]+)\]\(([^\s)]+)\)/g)) {
81
+ const url = docsLink(base, indexUrl, match[2]!);
82
+ if (!url || /\/llms(?:-full)?\.txt(?:[?#]|$)/.test(url)) continue;
83
+ const description = line.slice(match.index! + match[0].length).replace(/^\s*:\s*/, "").trim();
84
+ if (!pages.has(url)) pages.set(url, { title: match[1]!, url, description: cleanDocsText(description) });
85
+ }
86
+ }
87
+ return [...pages.values()];
88
+ }
89
+
90
+ function cleanDocsText(text: string): string {
91
+ return text.replace(/^\s*(?:>\s*)+/, "").replace(/!?\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/<[^>]*>/g, "").replace(/[*`]/g, "").replace(/^\s*[-*>]\s*/, "").replace(/\s+/g, " ").trim();
92
+ }
93
+
94
+ function docsTerms(query: string): string[] {
95
+ return [...new Set(query.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length >= 2))];
96
+ }
97
+
98
+ /** Rank sections, then keep the strongest section of each real page. A heading
99
+ * match must have content: blank lines, fences, and source markers are not hits. */
100
+ export function searchGuidePages(
101
+ prose: string | null, index: string | null, base: string | null, indexUrl: string | null, query: string,
102
+ ): GuideMatch[] {
103
+ const pages = docsIndexPages(index, base, indexUrl);
104
+ const terms = docsTerms(query);
105
+ if (terms.length === 0) return [];
106
+ const phrase = query.trim().toLowerCase();
107
+ const candidates: { match: GuideMatch; score: number }[] = [];
108
+ const add = (title: string, section: string | null, url: string | null, lines: string[]) => {
109
+ if (!url) return;
110
+ const content = lines.map(cleanDocsText).filter((line) => line.length > 0);
111
+ if (content.length === 0) return;
112
+ const heading = (title + " " + (section ?? "")).toLowerCase();
113
+ const body = content.join(" ").toLowerCase();
114
+ const matched = terms.filter((term) => heading.includes(term) || body.includes(term));
115
+ if (matched.length === 0) return;
116
+ const score = matched.length * 10 + (matched.length === terms.length ? 50 : 0)
117
+ + (heading.includes(phrase) ? 35 : body.includes(phrase) ? 25 : 0)
118
+ + (title.toLowerCase().includes(phrase) ? 25 : 0)
119
+ + terms.filter((term) => title.toLowerCase().includes(term)).length * 5
120
+ + terms.filter((term) => heading.includes(term)).length * 5
121
+ + terms.filter((term) => section?.toLowerCase().includes(term)).length * 3;
122
+ const excerpt = [...content].sort((a, b) => {
123
+ const rank = (line: string) => terms.filter((term) => line.toLowerCase().includes(term)).length;
124
+ return rank(b) - rank(a);
125
+ })[0]!.slice(0, 240);
126
+ candidates.push({ match: { title, section, heading: section ?? title, excerpt, url }, score });
127
+ };
128
+ let title = "";
129
+ let section: string | null = null;
130
+ let url: string | null = null;
131
+ let lines: string[] = [];
132
+ let fence: string | null = null;
133
+ const flush = () => { add(title, section, url, lines); lines = []; };
134
+ for (const line of (prose ?? "").split("\n")) {
135
+ const fenced = line.trim().match(/^(`{3,}|~{3,})/);
136
+ if (fenced) { if (fence === null) fence = fenced[1]![0]!; else if (fenced[1]![0] === fence) fence = null; continue; }
137
+ if (fence !== null) { if (line.trim()) lines.push(line); continue; }
138
+ const heading = line.match(/^(#{1,6})\s+(.+?)\s*#*$/);
139
+ if (heading) {
140
+ flush();
141
+ if (heading[1] === "#") {
142
+ title = cleanDocsText(heading[2]!);
143
+ section = null;
144
+ const link = heading[2]!.match(/\[[^\]]+\]\(([^\s)]+)\)/);
145
+ url = link ? docsLink(base, indexUrl, link[1]!) : pages.find((page) => page.title.toLowerCase() === title.toLowerCase())?.url ?? null;
146
+ } else section = cleanDocsText(heading[2]!);
147
+ continue;
148
+ }
149
+ const source = line.match(/^Source:\s*(?:\[[^\]]*\]\()?<?(https?:\/\/[^\s)>]+)>?\)?\s*$/i);
150
+ if (source) {
151
+ url = docsLink(base, indexUrl, source[1]!);
152
+ continue;
153
+ }
154
+ // Markdown callouts are blockquotes; keep their text for search and excerpts.
155
+ if (!line.trim() || /^\s*(?:---+|\|[\s:|-]+\|)\s*$/.test(line) || /^\s*</.test(line)) continue;
156
+ lines.push(line);
157
+ }
158
+ flush();
159
+ // An index is useful without llms-full.txt, and may include additional pages.
160
+ const described = new Set(candidates.map(({ match }) => match.url.replace(/\.md(?=[?#]|$)/, "")));
161
+ for (const page of pages) {
162
+ if (!described.has(page.url.replace(/\.md(?=[?#]|$)/, ""))) add(page.title, null, page.url, [page.description || page.title]);
163
+ }
164
+ candidates.sort((a, b) => b.score - a.score || a.match.title.localeCompare(b.match.title) || a.match.url.localeCompare(b.match.url));
165
+ const distinct = new Map<string, GuideMatch>();
166
+ for (const { match } of candidates) {
167
+ const key = match.url.replace(/\.md(?=[?#]|$)/, "");
168
+ if (!distinct.has(key)) distinct.set(key, match);
169
+ }
170
+ return [...distinct.values()];
171
+ }
172
+
173
+ export async function searchConnectedGuides(
174
+ base: string | null, indexUrl: string | null, fetchText: (path: string) => Promise<string | null>, query: string,
175
+ ): Promise<{ guides: GuideMatch[]; status: "not_configured" | "unavailable" | "ok" }> {
176
+ if (!base && !indexUrl) return { guides: [], status: "not_configured" };
177
+ const [index, prose] = await Promise.all([fetchText("llms.txt"), fetchText("llms-full.txt")]);
178
+ return { guides: searchGuidePages(prose, index, base, indexUrl, query), status: index === null && prose === null ? "unavailable" : "ok" };
179
+ }
180
+
181
+ export function docsReadTarget(index: string | null, base: string | null, indexUrl: string | null, page: string): string {
182
+ if (/^https?:\/\//.test(page)) return page;
183
+ const pages = docsIndexPages(index, base, indexUrl);
184
+ const term = page.toLowerCase();
185
+ const exact = pages.find((item) => item.title.toLowerCase() === term || new URL(item.url).pathname.toLowerCase() === term);
186
+ if (exact) return exact.url;
187
+ const matches = pages.filter((item) => item.url.toLowerCase().includes(term));
188
+ return matches.length === 1 ? matches[0]!.url : page;
189
+ }
190
+
191
+ /** One shell argument, including URLs with quotes, query strings, or fragments. */
192
+ export function docsReadCommand(bin: string, url: string): string {
193
+ return bin + " docs read '" + url.replace(/'/g, "'\\''") + "'";
194
+ }
195
+
196
+ /** Markdown-preferred fetch with same-origin redirects, one deadline, and a
197
+ * streaming byte cap. Returns null for every invalid or failed read. */
198
+ export async function fetchDocsText(url: string): Promise<string | null> {
199
+ try {
200
+ const initial = new URL(url);
201
+ if ((initial.protocol !== "https:" && initial.protocol !== "http:") || initial.username || initial.password) return null;
202
+ const allowedOrigin = initial.origin;
203
+ let current = initial.toString();
204
+ const signal = AbortSignal.timeout(10_000);
205
+ for (let redirects = 0; redirects <= 3; redirects += 1) {
206
+ const response = await fetch(current, { headers: { Accept: "text/markdown, text/plain, */*" }, redirect: "manual", signal });
207
+ if (response.status >= 300 && response.status < 400) {
208
+ const location = response.headers.get("location");
209
+ if (!location || redirects === 3) return null;
210
+ const next = new URL(location, current);
211
+ if (next.origin !== allowedOrigin || next.username || next.password) return null;
212
+ current = next.toString();
213
+ continue;
214
+ }
215
+ if (!response.ok) return null;
216
+ const declared = Number(response.headers.get("content-length"));
217
+ if (Number.isFinite(declared) && declared > MAX_DOCS_TEXT_BYTES) return null;
218
+ if (!response.body) return "";
219
+ const reader = response.body.getReader();
220
+ const decoder = new TextDecoder();
221
+ let bytes = 0;
222
+ let text = "";
223
+ for (;;) {
224
+ const chunk = await reader.read();
225
+ if (chunk.done) break;
226
+ bytes += chunk.value.byteLength;
227
+ if (bytes > MAX_DOCS_TEXT_BYTES) {
228
+ await reader.cancel();
229
+ return null;
230
+ }
231
+ text += decoder.decode(chunk.value, { stream: true });
232
+ }
233
+ return text + decoder.decode();
234
+ }
235
+ return null;
236
+ } catch {
237
+ return null;
238
+ }
239
+ }
package/src/errors.ts CHANGED
@@ -2,17 +2,17 @@
2
2
  // Generated by typeship — https://typeship.dev — do not edit by hand.
3
3
 
4
4
  import { ApiError, type ResponseMeta } from "./core/http.js";
5
- import type { ErrorModel } from "./types.js";
5
+ import type { ErrorModel, ErrorModelRead } from "./types.js";
6
6
 
7
- export { ApiError, GraphQLRequestError, TransportError, UnexpectedApiError, ValidationError, type Violation, unwrap } from "./core/http.js";
7
+ export { ApiError, ResponseParseError, TransportError, UnexpectedApiError, ValidationError, type Violation, unwrap } from "./core/http.js";
8
8
 
9
9
  /**
10
- * The request body, specification source, output selection, or package name is invalid.
10
+ * The request body, Definition source, target selection, or package name is invalid.
11
11
  * Raised for HTTP 400 responses.
12
12
  */
13
- export class BadRequestError extends ApiError<400, ErrorModel> {
14
- constructor(body: ErrorModel, response: ResponseMeta) {
15
- super("The request body, specification source, output selection, or package name is invalid.", 400, body, response);
13
+ export class BadRequestError extends ApiError<400, ErrorModelRead> {
14
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
15
+ super("The request body, Definition source, target selection, or package name is invalid.", 400, body, response);
16
16
  }
17
17
  }
18
18
 
@@ -20,8 +20,8 @@ export class BadRequestError extends ApiError<400, ErrorModel> {
20
20
  * Missing, invalid, expired, or revoked credentials.
21
21
  * Raised for HTTP 401 responses.
22
22
  */
23
- export class UnauthorizedError extends ApiError<401, ErrorModel> {
24
- constructor(body: ErrorModel, response: ResponseMeta) {
23
+ export class UnauthorizedError extends ApiError<401, ErrorModelRead> {
24
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
25
25
  super("Missing, invalid, expired, or revoked credentials.", 401, body, response);
26
26
  }
27
27
  }
@@ -30,39 +30,50 @@ export class UnauthorizedError extends ApiError<401, ErrorModel> {
30
30
  * The credentials are valid but cannot act on the requested organization.
31
31
  * Raised for HTTP 403 responses.
32
32
  */
33
- export class ForbiddenError extends ApiError<403, ErrorModel> {
34
- constructor(body: ErrorModel, response: ResponseMeta) {
33
+ export class ForbiddenError extends ApiError<403, ErrorModelRead> {
34
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
35
35
  super("The credentials are valid but cannot act on the requested organization.", 403, body, response);
36
36
  }
37
37
  }
38
38
 
39
+ /**
40
+ * The key identifies changed intent.
41
+ * Raised for HTTP 409 responses.
42
+ */
43
+ export class ConflictError extends ApiError<409, ErrorModelRead> {
44
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
45
+ super("The key identifies changed intent.", 409, body, response);
46
+ }
47
+ }
48
+
39
49
  /**
40
50
  * Spec exceeds the 10MB limit.
41
51
  * Raised for HTTP 413 responses.
42
52
  */
43
- export class PayloadTooLargeError extends ApiError<413, ErrorModel> {
44
- constructor(body: ErrorModel, response: ResponseMeta) {
53
+ export class PayloadTooLargeError extends ApiError<413, ErrorModelRead> {
54
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
45
55
  super("Spec exceeds the 10MB limit.", 413, body, response);
46
56
  }
47
57
  }
48
58
 
49
59
  /**
50
- * The spec could not be understood.
60
+ * The Definition could not be resolved or understood.
51
61
  * Raised for HTTP 422 responses.
52
62
  */
53
- export class UnprocessableEntityError extends ApiError<422, ErrorModel> {
54
- constructor(body: ErrorModel, response: ResponseMeta) {
55
- super("The spec could not be understood.", 422, body, response);
63
+ export class UnprocessableEntityError extends ApiError<422, ErrorModelRead> {
64
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
65
+ super("The Definition could not be resolved or understood.", 422, body, response);
56
66
  }
57
67
  }
58
68
 
59
69
  /**
60
- * Too many requests. Wait for Retry-After before retrying.
70
+ * Too many requests, or an identical write is still in progress. Wait for Retry-After before
71
+ * retrying.
61
72
  * Raised for HTTP 429 responses.
62
73
  */
63
- export class RateLimitedError extends ApiError<429, ErrorModel> {
64
- constructor(body: ErrorModel, response: ResponseMeta) {
65
- super("Too many requests. Wait for Retry-After before retrying.", 429, body, response);
74
+ export class RateLimitedError extends ApiError<429, ErrorModelRead> {
75
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
76
+ super("Too many requests, or an identical write is still in progress. Wait for Retry-After before retrying.", 429, body, response);
66
77
  }
67
78
  }
68
79
 
@@ -70,48 +81,48 @@ export class RateLimitedError extends ApiError<429, ErrorModel> {
70
81
  * Unexpected error.
71
82
  * Raised for "default" responses.
72
83
  */
73
- export class ApiResponseError extends ApiError<number, ErrorModel> {
74
- constructor(body: ErrorModel, response: ResponseMeta) {
84
+ export class ApiResponseError extends ApiError<number, ErrorModelRead> {
85
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
75
86
  super("Unexpected error.", response.status, body, response);
76
87
  }
77
88
  }
78
89
 
79
90
  /**
80
- * The plan does not include another project or the requested output configuration.
91
+ * The plan does not include another project or the requested target configuration.
81
92
  * Raised for HTTP 402 responses.
82
93
  */
83
- export class PaymentRequiredError extends ApiError<402, ErrorModel> {
84
- constructor(body: ErrorModel, response: ResponseMeta) {
85
- super("The plan does not include another project or the requested output configuration.", 402, body, response);
94
+ export class PaymentRequiredError extends ApiError<402, ErrorModelRead> {
95
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
96
+ super("The plan does not include another project or the requested target configuration.", 402, body, response);
86
97
  }
87
98
  }
88
99
 
89
100
  /**
90
- * The Idempotency-Key was already used with different request parameters.
91
- * Raised for HTTP 409 responses.
101
+ * Project setup failed unexpectedly; the key reservation is released.
102
+ * Raised for HTTP 500 responses.
92
103
  */
93
- export class ConflictError extends ApiError<409, ErrorModel> {
94
- constructor(body: ErrorModel, response: ResponseMeta) {
95
- super("The Idempotency-Key was already used with different request parameters.", 409, body, response);
104
+ export class InternalServerError extends ApiError<500, ErrorModelRead> {
105
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
106
+ super("Project setup failed unexpectedly; the key reservation is released.", 500, body, response);
96
107
  }
97
108
  }
98
109
 
99
110
  /**
100
- * The original idempotent request is temporarily unavailable.
101
- * Raised for HTTP 500 responses.
111
+ * No such resource in this account.
112
+ * Raised for HTTP 404 responses.
102
113
  */
103
- export class InternalServerError extends ApiError<500, ErrorModel> {
104
- constructor(body: ErrorModel, response: ResponseMeta) {
105
- super("The original idempotent request is temporarily unavailable.", 500, body, response);
114
+ export class NotFoundError extends ApiError<404, ErrorModelRead> {
115
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
116
+ super("No such resource in this account.", 404, body, response);
106
117
  }
107
118
  }
108
119
 
109
120
  /**
110
- * No such resource in this account.
111
- * Raised for HTTP 404 responses.
121
+ * The Project was saved, but an obsolete release pull request could not be retired.
122
+ * Raised for HTTP 502 responses.
112
123
  */
113
- export class NotFoundError extends ApiError<404, ErrorModel> {
114
- constructor(body: ErrorModel, response: ResponseMeta) {
115
- super("No such resource in this account.", 404, body, response);
124
+ export class BadGatewayError extends ApiError<502, ErrorModelRead> {
125
+ constructor(body: ErrorModelRead, response: ResponseMeta) {
126
+ super("The Project was saved, but an obsolete release pull request could not be retired.", 502, body, response);
116
127
  }
117
128
  }