@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
@@ -0,0 +1,207 @@
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 } from "./oauth-session.js";
6
+ const nativeCommand = (executable, args, input) => {
7
+ const result = spawnSync(executable, args, { input, encoding: "utf8", timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true, shell: false });
8
+ return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "", ...(result.error ? { error: result.error } : {}) };
9
+ };
10
+ function unavailable(name, environmentName) {
11
+ 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.");
12
+ }
13
+ function parseKey(value) {
14
+ const encoded = value.trim();
15
+ if (!/^[A-Za-z0-9+/]{43}=$/.test(encoded))
16
+ throw new CredentialStorageError("The OS credential key is invalid. Restore access to the original key before using the saved session.");
17
+ const key = Buffer.from(encoded, "base64");
18
+ if (key.length !== 32)
19
+ throw new CredentialStorageError("The OS credential key is invalid.");
20
+ return key;
21
+ }
22
+ /** A small wrapping key avoids OS item-size limits; session files are encrypted
23
+ * separately so refresh rotation can retain the atomic file/lock transaction. */
24
+ export function nativeCredentialKeyStore(path, platform = process.platform, run = nativeCommand, environmentName = "CREDENTIAL_STORE") {
25
+ const failed = (name) => unavailable(name, environmentName);
26
+ const identity = createHash("sha256").update(resolve(path)).digest("hex");
27
+ const service = "typeship.credentials." + identity;
28
+ const account = "session-key";
29
+ if (platform === "darwin") {
30
+ const name = "macOS Keychain";
31
+ const lookup = () => run("/usr/bin/security", ["find-generic-password", "-s", service, "-a", account, "-w"]);
32
+ return {
33
+ name,
34
+ read() {
35
+ const result = lookup();
36
+ if (!result.error && result.status === 44)
37
+ return null; // errSecItemNotFound
38
+ if (result.error || result.status !== 0)
39
+ return failed(name);
40
+ return parseKey(result.stdout);
41
+ },
42
+ write(key) {
43
+ // security's interactive command stream keeps the key off argv. All
44
+ // tokens below have a fixed safe alphabet; no shell or user text is run.
45
+ const input = "add-generic-password -U -s " + service + " -a " + account + " -w " + key.toString("base64") + "\n";
46
+ const result = run("/usr/bin/security", ["-i"], input);
47
+ if (result.error || result.status !== 0)
48
+ return failed(name);
49
+ // Verify the write: an interactive tool's process status alone is not
50
+ // sufficient evidence that its command stored the requested item.
51
+ const saved = this.read();
52
+ if (!saved || !timingSafeEqual(saved, key))
53
+ return failed(name);
54
+ },
55
+ remove() {
56
+ const result = run("/usr/bin/security", ["delete-generic-password", "-s", service, "-a", account]);
57
+ if (result.error || (result.status !== 0 && result.status !== 44))
58
+ failed(name);
59
+ },
60
+ };
61
+ }
62
+ if (platform === "linux") {
63
+ const name = "Linux Secret Service (secret-tool)";
64
+ const attributes = ["service", service, "account", account];
65
+ return {
66
+ name,
67
+ read() {
68
+ const result = run("/usr/bin/secret-tool", ["lookup", ...attributes]);
69
+ if (!result.error && result.status === 1 && !result.stderr.trim())
70
+ return null;
71
+ if (result.error || result.status !== 0)
72
+ return failed(name);
73
+ return parseKey(result.stdout);
74
+ },
75
+ write(key) {
76
+ const result = run("/usr/bin/secret-tool", ["store", "--label=CLI session encryption key", ...attributes], key.toString("base64"));
77
+ if (result.error || result.status !== 0)
78
+ return failed(name);
79
+ const saved = this.read();
80
+ if (!saved || !timingSafeEqual(saved, key))
81
+ return failed(name);
82
+ },
83
+ remove() {
84
+ const result = run("/usr/bin/secret-tool", ["clear", ...attributes]);
85
+ if (result.error || result.status !== 0)
86
+ failed(name);
87
+ },
88
+ };
89
+ }
90
+ if (platform === "win32") {
91
+ const name = "Windows DPAPI (current user)";
92
+ const keyPath = path + ".key";
93
+ const executable = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
94
+ const script = `
95
+ $ErrorActionPreference = 'Stop'
96
+ try {
97
+ Add-Type -AssemblyName System.Security
98
+ $payload = [Console]::In.ReadToEnd() | ConvertFrom-Json
99
+ $bytes = [Convert]::FromBase64String([string]$payload.data)
100
+ $entropy = [Text.Encoding]::UTF8.GetBytes([string]$payload.service)
101
+ $scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
102
+ if ($payload.action -eq 'protect') { $result = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $entropy, $scope) }
103
+ elseif ($payload.action -eq 'unprotect') { $result = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $entropy, $scope) }
104
+ else { exit 1 }
105
+ [Console]::Out.Write([Convert]::ToBase64String($result))
106
+ exit 0
107
+ } catch { exit 1 }
108
+ `;
109
+ const crypt = (action, data) => {
110
+ // EncodedCommand contains fixed code only. Sensitive data goes over stdin.
111
+ const result = run(executable, ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], JSON.stringify({ action, data, service }));
112
+ if (result.error || result.status !== 0 || !result.stdout.trim())
113
+ return failed(name);
114
+ return result.stdout.trim();
115
+ };
116
+ return {
117
+ name,
118
+ read() {
119
+ let wrapped;
120
+ try {
121
+ wrapped = readFileSync(keyPath, "utf8");
122
+ }
123
+ catch (error) {
124
+ if (error.code === "ENOENT")
125
+ return null;
126
+ return failed(name);
127
+ }
128
+ return parseKey(crypt("unprotect", wrapped));
129
+ },
130
+ write(key) {
131
+ const wrapped = crypt("protect", key.toString("base64"));
132
+ const temporary = keyPath + "." + randomBytes(16).toString("hex") + ".tmp";
133
+ try {
134
+ writeFileSync(temporary, wrapped, { mode: 0o600, flag: "wx", flush: true });
135
+ renameSync(temporary, keyPath);
136
+ }
137
+ finally {
138
+ rmSync(temporary, { force: true });
139
+ }
140
+ const saved = this.read();
141
+ if (!saved || !timingSafeEqual(saved, key))
142
+ return failed(name);
143
+ },
144
+ remove() { rmSync(keyPath, { force: true }); },
145
+ };
146
+ }
147
+ 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") };
148
+ }
149
+ export function encryptedCredentialCodec(path, keyStore) {
150
+ const associatedData = Buffer.from("cli-credentials-v1:" + resolve(path));
151
+ const key = (create) => {
152
+ const saved = keyStore.read();
153
+ if (saved)
154
+ return saved;
155
+ if (!create || existsSync(path))
156
+ 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.");
157
+ const generated = randomBytes(32);
158
+ keyStore.write(generated);
159
+ return generated;
160
+ };
161
+ return {
162
+ name: keyStore.name,
163
+ prepare() { key(true); },
164
+ encode(plaintext) {
165
+ const nonce = randomBytes(12);
166
+ const cipher = createCipheriv("aes-256-gcm", key(true), nonce);
167
+ cipher.setAAD(associatedData);
168
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
169
+ return JSON.stringify({ version: 1, algorithm: "aes-256-gcm", nonce: nonce.toString("base64"), tag: cipher.getAuthTag().toString("base64"), ciphertext: ciphertext.toString("base64") });
170
+ },
171
+ decode(encoded) {
172
+ let envelope;
173
+ try {
174
+ envelope = JSON.parse(encoded);
175
+ }
176
+ catch {
177
+ throw new CredentialStorageError("Saved encrypted credentials are damaged. Restore the credential file before logging in again.");
178
+ }
179
+ if (!envelope || envelope.version !== 1 || envelope.algorithm !== "aes-256-gcm" || typeof envelope.nonce !== "string" || typeof envelope.tag !== "string" || typeof envelope.ciphertext !== "string")
180
+ throw new CredentialStorageError("Saved encrypted credentials use an invalid format.");
181
+ const secret = key(false);
182
+ try {
183
+ const nonce = Buffer.from(envelope.nonce, "base64"), tag = Buffer.from(envelope.tag, "base64");
184
+ if (nonce.length !== 12 || tag.length !== 16)
185
+ throw new Error();
186
+ const decipher = createDecipheriv("aes-256-gcm", secret, nonce);
187
+ decipher.setAAD(associatedData);
188
+ decipher.setAuthTag(tag);
189
+ return Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64")), decipher.final()]).toString("utf8");
190
+ }
191
+ catch {
192
+ throw new CredentialStorageError("Saved credentials could not be authenticated. Restore the original credential file and OS key; do not reuse this session.");
193
+ }
194
+ },
195
+ };
196
+ }
197
+ /** OS protection is the default. Plaintext storage is an explicit, separate
198
+ * store for environments where the owner accepts that tradeoff. Never migrate
199
+ * or fall back silently when an OS service is unavailable. */
200
+ export function createCredentialStore(directory, mode = "os", environmentName = "CREDENTIAL_STORE") {
201
+ if (mode === "file")
202
+ return new FileCredentialStore(join(directory, "credentials.json"));
203
+ if (mode !== "os")
204
+ throw new CredentialStorageError(environmentName + " must be os or file.");
205
+ const path = join(directory, "credentials.enc");
206
+ return new FileCredentialStore(path, 40_000, encryptedCredentialCodec(path, nativeCredentialKeyStore(path, process.platform, nativeCommand, environmentName)));
207
+ }
package/dist/dates.d.ts CHANGED
@@ -15,8 +15,6 @@
15
15
  * validates absolute values. Zero dependencies.
16
16
  */
17
17
  export type DateKind = "date" | "date-time";
18
- /** The forms a date-shaped argument accepts, for descriptions and help. */
19
- export declare const RELATIVE_DATE_HINT = "Accepts ISO 8601 or a relative form: -P7D, -7d, 7 days ago, today, now.";
20
18
  /**
21
19
  * Resolve a relative date expression. `null` means "not a relative form,
22
20
  * pass the value through"; `{ error }` means it looked relative but is
@@ -1 +1 @@
1
- {"version":3,"file":"dates.d.ts","sourceRoot":"","sources":["../src/dates.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;AAa5C,2EAA2E;AAC3E,eAAO,MAAM,kBAAkB,4EAA4E,CAAC;AAoC5G;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,GAAE,IAAiB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAmC/H;AAcD,2DAA2D;AAC3D,wBAAgB,UAAU,CAAC,MAAM,EAAE,OAAO,GAAG,QAAQ,GAAG,IAAI,CAE3D"}
1
+ {"version":3,"file":"dates.d.ts","sourceRoot":"","sources":["../src/dates.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;AAiD5C;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,GAAE,IAAiB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAmC/H;AAcD,2DAA2D;AAC3D,wBAAgB,UAAU,CAAC,MAAM,EAAE,OAAO,GAAG,QAAQ,GAAG,IAAI,CAE3D"}
package/dist/dates.js CHANGED
@@ -24,7 +24,6 @@ const UNIT_MS = {
24
24
  const CALENDAR_UNITS = new Set(["mo", "month", "y", "yr", "year"]);
25
25
  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.";
26
26
  /** The forms a date-shaped argument accepts, for descriptions and help. */
27
- export const RELATIVE_DATE_HINT = "Accepts ISO 8601 or a relative form: -P7D, -7d, 7 days ago, today, now.";
28
27
  function shift(base, amount, unit) {
29
28
  const d = new Date(base.getTime());
30
29
  if (CALENDAR_UNITS.has(unit)) {
package/dist/docs.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ /** Shared documentation-fetch boundary for generated CLI and MCP surfaces. */
2
+ export declare const MAX_DOCS_TEXT_BYTES = 2000000;
3
+ export declare function resolveDocsPageUrl(base: string | null, pathOrFile: string): string | null;
4
+ /** Resolve conventional docs files while honoring an explicitly configured
5
+ * llms.txt location. Guide links may live on either the docs-site origin or
6
+ * the index origin; no other origin is accepted. */
7
+ export declare function resolveDocsContentUrl(base: string | null, indexUrl: string | null, pathOrFile: string): string | null;
8
+ export interface GuideMatch {
9
+ title: string;
10
+ section: string | null;
11
+ /** Kept for callers that displayed the original heading-only results. */
12
+ heading: string;
13
+ excerpt: string;
14
+ url: string;
15
+ }
16
+ interface GuidePage {
17
+ title: string;
18
+ url: string;
19
+ description: string;
20
+ }
21
+ export declare function docsIndexPages(index: string | null, base: string | null, indexUrl: string | null): GuidePage[];
22
+ /** Rank sections, then keep the strongest section of each real page. A heading
23
+ * match must have content: blank lines, fences, and source markers are not hits. */
24
+ export declare function searchGuidePages(prose: string | null, index: string | null, base: string | null, indexUrl: string | null, query: string): GuideMatch[];
25
+ export declare function searchConnectedGuides(base: string | null, indexUrl: string | null, fetchText: (path: string) => Promise<string | null>, query: string): Promise<{
26
+ guides: GuideMatch[];
27
+ status: "not_configured" | "unavailable" | "ok";
28
+ }>;
29
+ export declare function docsReadTarget(index: string | null, base: string | null, indexUrl: string | null, page: string): string;
30
+ /** One shell argument, including URLs with quotes, query strings, or fragments. */
31
+ export declare function docsReadCommand(bin: string, url: string): string;
32
+ /** Markdown-preferred fetch with same-origin redirects, one deadline, and a
33
+ * streaming byte cap. Returns null for every invalid or failed read. */
34
+ export declare function fetchDocsText(url: string): Promise<string | null>;
35
+ export {};
36
+ //# sourceMappingURL=docs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs.d.ts","sourceRoot":"","sources":["../src/docs.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAE9E,eAAO,MAAM,mBAAmB,UAAY,CAAC;AAE7C,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAYzF;AAED;;oDAEoD;AACpD,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,QAAQ,EAAE,MAAM,GAAG,IAAI,EACvB,UAAU,EAAE,MAAM,GACjB,MAAM,GAAG,IAAI,CAkBf;AAcD,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb;AAED,UAAU,SAAS;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE;AAUvE,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,CAW9G;AAUD;oFACoF;AACpF,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,MAAM,GACtG,UAAU,EAAE,CAqEd;AAED,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,GAC/G,OAAO,CAAC;IAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAAC,MAAM,EAAE,gBAAgB,GAAG,aAAa,GAAG,IAAI,CAAA;CAAE,CAAC,CAIpF;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAQvH;AAED,mFAAmF;AACnF,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAEhE;AAED;wEACwE;AACxE,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAyCvE"}
package/dist/docs.js ADDED
@@ -0,0 +1,258 @@
1
+ /** Shared documentation-fetch boundary for generated CLI and MCP surfaces. */
2
+ export const MAX_DOCS_TEXT_BYTES = 2_000_000;
3
+ export function resolveDocsPageUrl(base, pathOrFile) {
4
+ if (base === null)
5
+ return null;
6
+ try {
7
+ const baseUrl = new URL(base);
8
+ if ((baseUrl.protocol !== "https:" && baseUrl.protocol !== "http:") || baseUrl.username || baseUrl.password)
9
+ 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
+ }
15
+ catch {
16
+ return null;
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(base, indexUrl, pathOrFile) {
23
+ const exactIndex = safeHttpUrl(indexUrl);
24
+ if (pathOrFile === "llms.txt" && exactIndex)
25
+ return exactIndex;
26
+ if (pathOrFile === "llms-full.txt" && exactIndex) {
27
+ try {
28
+ return new URL("llms-full.txt", exactIndex).toString();
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ const primary = resolveDocsPageUrl(base, pathOrFile);
35
+ if (primary)
36
+ return primary;
37
+ if (!exactIndex)
38
+ return null;
39
+ try {
40
+ const target = /^https?:\/\//.test(pathOrFile)
41
+ ? new URL(pathOrFile)
42
+ : new URL(pathOrFile.replace(/^\/+/, ""), exactIndex);
43
+ const allowed = new URL(exactIndex);
44
+ return target.origin === allowed.origin && !target.username && !target.password ? target.toString() : null;
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ function safeHttpUrl(value) {
51
+ if (!value)
52
+ return null;
53
+ try {
54
+ const parsed = new URL(value);
55
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && !parsed.username && !parsed.password
56
+ ? parsed.toString()
57
+ : null;
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ /** Links in an index follow URL semantics, including site-root relative links. */
64
+ function docsLink(base, indexUrl, value) {
65
+ const index = resolveDocsContentUrl(base, indexUrl, "llms.txt");
66
+ if (!index)
67
+ return null;
68
+ try {
69
+ return resolveDocsContentUrl(base, indexUrl, new URL(value, index).toString());
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ export function docsIndexPages(index, base, indexUrl) {
76
+ const pages = new Map();
77
+ for (const line of (index ?? "").split("\n")) {
78
+ for (const match of line.matchAll(/\[([^\]]+)\]\(([^\s)]+)\)/g)) {
79
+ const url = docsLink(base, indexUrl, match[2]);
80
+ if (!url || /\/llms(?:-full)?\.txt(?:[?#]|$)/.test(url))
81
+ continue;
82
+ const description = line.slice(match.index + match[0].length).replace(/^\s*:\s*/, "").trim();
83
+ if (!pages.has(url))
84
+ pages.set(url, { title: match[1], url, description: cleanDocsText(description) });
85
+ }
86
+ }
87
+ return [...pages.values()];
88
+ }
89
+ function cleanDocsText(text) {
90
+ return text.replace(/^\s*(?:>\s*)+/, "").replace(/!?\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/<[^>]*>/g, "").replace(/[*`]/g, "").replace(/^\s*[-*>]\s*/, "").replace(/\s+/g, " ").trim();
91
+ }
92
+ function docsTerms(query) {
93
+ return [...new Set(query.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((term) => term.length >= 2))];
94
+ }
95
+ /** Rank sections, then keep the strongest section of each real page. A heading
96
+ * match must have content: blank lines, fences, and source markers are not hits. */
97
+ export function searchGuidePages(prose, index, base, indexUrl, query) {
98
+ const pages = docsIndexPages(index, base, indexUrl);
99
+ const terms = docsTerms(query);
100
+ if (terms.length === 0)
101
+ return [];
102
+ const phrase = query.trim().toLowerCase();
103
+ const candidates = [];
104
+ const add = (title, section, url, lines) => {
105
+ if (!url)
106
+ return;
107
+ const content = lines.map(cleanDocsText).filter((line) => line.length > 0);
108
+ if (content.length === 0)
109
+ return;
110
+ const heading = (title + " " + (section ?? "")).toLowerCase();
111
+ const body = content.join(" ").toLowerCase();
112
+ const matched = terms.filter((term) => heading.includes(term) || body.includes(term));
113
+ if (matched.length === 0)
114
+ return;
115
+ const score = matched.length * 10 + (matched.length === terms.length ? 50 : 0)
116
+ + (heading.includes(phrase) ? 35 : body.includes(phrase) ? 25 : 0)
117
+ + (title.toLowerCase().includes(phrase) ? 25 : 0)
118
+ + terms.filter((term) => title.toLowerCase().includes(term)).length * 5
119
+ + terms.filter((term) => heading.includes(term)).length * 5
120
+ + terms.filter((term) => section?.toLowerCase().includes(term)).length * 3;
121
+ const excerpt = [...content].sort((a, b) => {
122
+ const rank = (line) => terms.filter((term) => line.toLowerCase().includes(term)).length;
123
+ return rank(b) - rank(a);
124
+ })[0].slice(0, 240);
125
+ candidates.push({ match: { title, section, heading: section ?? title, excerpt, url }, score });
126
+ };
127
+ let title = "";
128
+ let section = null;
129
+ let url = null;
130
+ let lines = [];
131
+ let fence = null;
132
+ const flush = () => { add(title, section, url, lines); lines = []; };
133
+ for (const line of (prose ?? "").split("\n")) {
134
+ const fenced = line.trim().match(/^(`{3,}|~{3,})/);
135
+ if (fenced) {
136
+ if (fence === null)
137
+ fence = fenced[1][0];
138
+ else if (fenced[1][0] === fence)
139
+ fence = null;
140
+ continue;
141
+ }
142
+ if (fence !== null) {
143
+ if (line.trim())
144
+ lines.push(line);
145
+ continue;
146
+ }
147
+ const heading = line.match(/^(#{1,6})\s+(.+?)\s*#*$/);
148
+ if (heading) {
149
+ flush();
150
+ if (heading[1] === "#") {
151
+ title = cleanDocsText(heading[2]);
152
+ section = null;
153
+ const link = heading[2].match(/\[[^\]]+\]\(([^\s)]+)\)/);
154
+ url = link ? docsLink(base, indexUrl, link[1]) : pages.find((page) => page.title.toLowerCase() === title.toLowerCase())?.url ?? null;
155
+ }
156
+ else
157
+ section = cleanDocsText(heading[2]);
158
+ continue;
159
+ }
160
+ const source = line.match(/^Source:\s*(?:\[[^\]]*\]\()?<?(https?:\/\/[^\s)>]+)>?\)?\s*$/i);
161
+ if (source) {
162
+ url = docsLink(base, indexUrl, source[1]);
163
+ continue;
164
+ }
165
+ // Markdown callouts are blockquotes; keep their text for search and excerpts.
166
+ if (!line.trim() || /^\s*(?:---+|\|[\s:|-]+\|)\s*$/.test(line) || /^\s*</.test(line))
167
+ continue;
168
+ lines.push(line);
169
+ }
170
+ flush();
171
+ // An index is useful without llms-full.txt, and may include additional pages.
172
+ const described = new Set(candidates.map(({ match }) => match.url.replace(/\.md(?=[?#]|$)/, "")));
173
+ for (const page of pages) {
174
+ if (!described.has(page.url.replace(/\.md(?=[?#]|$)/, "")))
175
+ add(page.title, null, page.url, [page.description || page.title]);
176
+ }
177
+ candidates.sort((a, b) => b.score - a.score || a.match.title.localeCompare(b.match.title) || a.match.url.localeCompare(b.match.url));
178
+ const distinct = new Map();
179
+ for (const { match } of candidates) {
180
+ const key = match.url.replace(/\.md(?=[?#]|$)/, "");
181
+ if (!distinct.has(key))
182
+ distinct.set(key, match);
183
+ }
184
+ return [...distinct.values()];
185
+ }
186
+ export async function searchConnectedGuides(base, indexUrl, fetchText, query) {
187
+ if (!base && !indexUrl)
188
+ return { guides: [], status: "not_configured" };
189
+ const [index, prose] = await Promise.all([fetchText("llms.txt"), fetchText("llms-full.txt")]);
190
+ return { guides: searchGuidePages(prose, index, base, indexUrl, query), status: index === null && prose === null ? "unavailable" : "ok" };
191
+ }
192
+ export function docsReadTarget(index, base, indexUrl, page) {
193
+ if (/^https?:\/\//.test(page))
194
+ return page;
195
+ const pages = docsIndexPages(index, base, indexUrl);
196
+ const term = page.toLowerCase();
197
+ const exact = pages.find((item) => item.title.toLowerCase() === term || new URL(item.url).pathname.toLowerCase() === term);
198
+ if (exact)
199
+ return exact.url;
200
+ const matches = pages.filter((item) => item.url.toLowerCase().includes(term));
201
+ return matches.length === 1 ? matches[0].url : page;
202
+ }
203
+ /** One shell argument, including URLs with quotes, query strings, or fragments. */
204
+ export function docsReadCommand(bin, url) {
205
+ return bin + " docs read '" + url.replace(/'/g, "'\\''") + "'";
206
+ }
207
+ /** Markdown-preferred fetch with same-origin redirects, one deadline, and a
208
+ * streaming byte cap. Returns null for every invalid or failed read. */
209
+ export async function fetchDocsText(url) {
210
+ try {
211
+ const initial = new URL(url);
212
+ if ((initial.protocol !== "https:" && initial.protocol !== "http:") || initial.username || initial.password)
213
+ return null;
214
+ const allowedOrigin = initial.origin;
215
+ let current = initial.toString();
216
+ const signal = AbortSignal.timeout(10_000);
217
+ for (let redirects = 0; redirects <= 3; redirects += 1) {
218
+ const response = await fetch(current, { headers: { Accept: "text/markdown, text/plain, */*" }, redirect: "manual", signal });
219
+ if (response.status >= 300 && response.status < 400) {
220
+ const location = response.headers.get("location");
221
+ if (!location || redirects === 3)
222
+ return null;
223
+ const next = new URL(location, current);
224
+ if (next.origin !== allowedOrigin || next.username || next.password)
225
+ return null;
226
+ current = next.toString();
227
+ continue;
228
+ }
229
+ if (!response.ok)
230
+ return null;
231
+ const declared = Number(response.headers.get("content-length"));
232
+ if (Number.isFinite(declared) && declared > MAX_DOCS_TEXT_BYTES)
233
+ return null;
234
+ if (!response.body)
235
+ return "";
236
+ const reader = response.body.getReader();
237
+ const decoder = new TextDecoder();
238
+ let bytes = 0;
239
+ let text = "";
240
+ for (;;) {
241
+ const chunk = await reader.read();
242
+ if (chunk.done)
243
+ break;
244
+ bytes += chunk.value.byteLength;
245
+ if (bytes > MAX_DOCS_TEXT_BYTES) {
246
+ await reader.cancel();
247
+ return null;
248
+ }
249
+ text += decoder.decode(chunk.value, { stream: true });
250
+ }
251
+ return text + decoder.decode();
252
+ }
253
+ return null;
254
+ }
255
+ catch {
256
+ return null;
257
+ }
258
+ }
package/dist/errors.d.ts CHANGED
@@ -1,81 +1,89 @@
1
1
  import { ApiError, type ResponseMeta } from "./core/http.js";
2
- import type { ErrorModel } from "./types.js";
3
- export { ApiError, GraphQLRequestError, TransportError, UnexpectedApiError, ValidationError, type Violation, unwrap } from "./core/http.js";
2
+ import type { ErrorModelRead } from "./types.js";
3
+ export { ApiError, ResponseParseError, TransportError, UnexpectedApiError, ValidationError, type Violation, unwrap } from "./core/http.js";
4
4
  /**
5
- * The request body, specification source, output selection, or package name is invalid.
5
+ * The request body, Definition source, target selection, or package name is invalid.
6
6
  * Raised for HTTP 400 responses.
7
7
  */
8
- export declare class BadRequestError extends ApiError<400, ErrorModel> {
9
- constructor(body: ErrorModel, response: ResponseMeta);
8
+ export declare class BadRequestError extends ApiError<400, ErrorModelRead> {
9
+ constructor(body: ErrorModelRead, response: ResponseMeta);
10
10
  }
11
11
  /**
12
12
  * Missing, invalid, expired, or revoked credentials.
13
13
  * Raised for HTTP 401 responses.
14
14
  */
15
- export declare class UnauthorizedError extends ApiError<401, ErrorModel> {
16
- constructor(body: ErrorModel, response: ResponseMeta);
15
+ export declare class UnauthorizedError extends ApiError<401, ErrorModelRead> {
16
+ constructor(body: ErrorModelRead, response: ResponseMeta);
17
17
  }
18
18
  /**
19
19
  * The credentials are valid but cannot act on the requested organization.
20
20
  * Raised for HTTP 403 responses.
21
21
  */
22
- export declare class ForbiddenError extends ApiError<403, ErrorModel> {
23
- constructor(body: ErrorModel, response: ResponseMeta);
22
+ export declare class ForbiddenError extends ApiError<403, ErrorModelRead> {
23
+ constructor(body: ErrorModelRead, response: ResponseMeta);
24
+ }
25
+ /**
26
+ * The key identifies changed intent.
27
+ * Raised for HTTP 409 responses.
28
+ */
29
+ export declare class ConflictError extends ApiError<409, ErrorModelRead> {
30
+ constructor(body: ErrorModelRead, response: ResponseMeta);
24
31
  }
25
32
  /**
26
33
  * Spec exceeds the 10MB limit.
27
34
  * Raised for HTTP 413 responses.
28
35
  */
29
- export declare class PayloadTooLargeError extends ApiError<413, ErrorModel> {
30
- constructor(body: ErrorModel, response: ResponseMeta);
36
+ export declare class PayloadTooLargeError extends ApiError<413, ErrorModelRead> {
37
+ constructor(body: ErrorModelRead, response: ResponseMeta);
31
38
  }
32
39
  /**
33
- * The spec could not be understood.
40
+ * The Definition could not be resolved or understood.
34
41
  * Raised for HTTP 422 responses.
35
42
  */
36
- export declare class UnprocessableEntityError extends ApiError<422, ErrorModel> {
37
- constructor(body: ErrorModel, response: ResponseMeta);
43
+ export declare class UnprocessableEntityError extends ApiError<422, ErrorModelRead> {
44
+ constructor(body: ErrorModelRead, response: ResponseMeta);
38
45
  }
39
46
  /**
40
- * Too many requests. Wait for Retry-After before retrying.
47
+ * Too many requests, or an identical write is still in progress. Wait for Retry-After before
48
+ * retrying.
41
49
  * Raised for HTTP 429 responses.
42
50
  */
43
- export declare class RateLimitedError extends ApiError<429, ErrorModel> {
44
- constructor(body: ErrorModel, response: ResponseMeta);
51
+ export declare class RateLimitedError extends ApiError<429, ErrorModelRead> {
52
+ constructor(body: ErrorModelRead, response: ResponseMeta);
45
53
  }
46
54
  /**
47
55
  * Unexpected error.
48
56
  * Raised for "default" responses.
49
57
  */
50
- export declare class ApiResponseError extends ApiError<number, ErrorModel> {
51
- constructor(body: ErrorModel, response: ResponseMeta);
58
+ export declare class ApiResponseError extends ApiError<number, ErrorModelRead> {
59
+ constructor(body: ErrorModelRead, response: ResponseMeta);
52
60
  }
53
61
  /**
54
- * The plan does not include another project or the requested output configuration.
62
+ * The plan does not include another project or the requested target configuration.
55
63
  * Raised for HTTP 402 responses.
56
64
  */
57
- export declare class PaymentRequiredError extends ApiError<402, ErrorModel> {
58
- constructor(body: ErrorModel, response: ResponseMeta);
65
+ export declare class PaymentRequiredError extends ApiError<402, ErrorModelRead> {
66
+ constructor(body: ErrorModelRead, response: ResponseMeta);
59
67
  }
60
68
  /**
61
- * The Idempotency-Key was already used with different request parameters.
62
- * Raised for HTTP 409 responses.
63
- */
64
- export declare class ConflictError extends ApiError<409, ErrorModel> {
65
- constructor(body: ErrorModel, response: ResponseMeta);
66
- }
67
- /**
68
- * The original idempotent request is temporarily unavailable.
69
+ * Project setup failed unexpectedly; the key reservation is released.
69
70
  * Raised for HTTP 500 responses.
70
71
  */
71
- export declare class InternalServerError extends ApiError<500, ErrorModel> {
72
- constructor(body: ErrorModel, response: ResponseMeta);
72
+ export declare class InternalServerError extends ApiError<500, ErrorModelRead> {
73
+ constructor(body: ErrorModelRead, response: ResponseMeta);
73
74
  }
74
75
  /**
75
76
  * No such resource in this account.
76
77
  * Raised for HTTP 404 responses.
77
78
  */
78
- export declare class NotFoundError extends ApiError<404, ErrorModel> {
79
- constructor(body: ErrorModel, response: ResponseMeta);
79
+ export declare class NotFoundError extends ApiError<404, ErrorModelRead> {
80
+ constructor(body: ErrorModelRead, response: ResponseMeta);
81
+ }
82
+ /**
83
+ * The Project was saved, but an obsolete release pull request could not be retired.
84
+ * Raised for HTTP 502 responses.
85
+ */
86
+ export declare class BadGatewayError extends ApiError<502, ErrorModelRead> {
87
+ constructor(body: ErrorModelRead, response: ResponseMeta);
80
88
  }
81
89
  //# sourceMappingURL=errors.d.ts.map