expandai 0.0.0 → 0.0.2

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 (209) hide show
  1. package/README.md +241 -6
  2. package/build/dts/ApiClient.d.ts +231 -0
  3. package/build/dts/ApiClient.d.ts.map +1 -0
  4. package/build/dts/Authentication.d.ts +23 -0
  5. package/build/dts/Authentication.d.ts.map +1 -0
  6. package/build/dts/BrowserOAuth.d.ts +99 -0
  7. package/build/dts/BrowserOAuth.d.ts.map +1 -0
  8. package/build/dts/Commands/Fetch.d.ts +30 -0
  9. package/build/dts/Commands/Fetch.d.ts.map +1 -0
  10. package/build/dts/Commands/Hook.d.ts +17 -0
  11. package/build/dts/Commands/Hook.d.ts.map +1 -0
  12. package/build/dts/Commands/Mcp.d.ts +11 -0
  13. package/build/dts/Commands/Mcp.d.ts.map +1 -0
  14. package/build/dts/Commands/McpRun.d.ts +5 -0
  15. package/build/dts/Commands/McpRun.d.ts.map +1 -0
  16. package/build/dts/Commands/Search.d.ts +21 -0
  17. package/build/dts/Commands/Search.d.ts.map +1 -0
  18. package/build/dts/Commands/Skill.d.ts +12 -0
  19. package/build/dts/Commands/Skill.d.ts.map +1 -0
  20. package/build/dts/Commands/Uninstall.d.ts +9 -0
  21. package/build/dts/Commands/Uninstall.d.ts.map +1 -0
  22. package/build/dts/Config.d.ts +105 -0
  23. package/build/dts/Config.d.ts.map +1 -0
  24. package/build/dts/DeviceAuth.d.ts +87 -0
  25. package/build/dts/DeviceAuth.d.ts.map +1 -0
  26. package/build/dts/Hook/Claude.d.ts +13 -0
  27. package/build/dts/Hook/Claude.d.ts.map +1 -0
  28. package/build/dts/Hook/Errors.d.ts +20 -0
  29. package/build/dts/Hook/Errors.d.ts.map +1 -0
  30. package/build/dts/Hook/Opencode.d.ts +13 -0
  31. package/build/dts/Hook/Opencode.d.ts.map +1 -0
  32. package/build/dts/Hook/SnapshotNote.d.ts +8 -0
  33. package/build/dts/Hook/SnapshotNote.d.ts.map +1 -0
  34. package/build/dts/Install/Claude/Hook.d.ts +60 -0
  35. package/build/dts/Install/Claude/Hook.d.ts.map +1 -0
  36. package/build/dts/Install/Claude/Mcp.d.ts +45 -0
  37. package/build/dts/Install/Claude/Mcp.d.ts.map +1 -0
  38. package/build/dts/Install/Claude/Skill.d.ts +24 -0
  39. package/build/dts/Install/Claude/Skill.d.ts.map +1 -0
  40. package/build/dts/Install/Codex/Mcp.d.ts +39 -0
  41. package/build/dts/Install/Codex/Mcp.d.ts.map +1 -0
  42. package/build/dts/Install/Codex/Skill.d.ts +20 -0
  43. package/build/dts/Install/Codex/Skill.d.ts.map +1 -0
  44. package/build/dts/Install/Cursor/Mcp.d.ts +45 -0
  45. package/build/dts/Install/Cursor/Mcp.d.ts.map +1 -0
  46. package/build/dts/Install/Cursor/Skill.d.ts +27 -0
  47. package/build/dts/Install/Cursor/Skill.d.ts.map +1 -0
  48. package/build/dts/Install/Domain.d.ts +73 -0
  49. package/build/dts/Install/Domain.d.ts.map +1 -0
  50. package/build/dts/Install/Hook.d.ts +30 -0
  51. package/build/dts/Install/Hook.d.ts.map +1 -0
  52. package/build/dts/Install/Mcp.d.ts +28 -0
  53. package/build/dts/Install/Mcp.d.ts.map +1 -0
  54. package/build/dts/Install/Opencode/Hook.d.ts +23 -0
  55. package/build/dts/Install/Opencode/Hook.d.ts.map +1 -0
  56. package/build/dts/Install/Opencode/Mcp.d.ts +47 -0
  57. package/build/dts/Install/Opencode/Mcp.d.ts.map +1 -0
  58. package/build/dts/Install/Opencode/Skill.d.ts +24 -0
  59. package/build/dts/Install/Opencode/Skill.d.ts.map +1 -0
  60. package/build/dts/Install/Skill.d.ts +32 -0
  61. package/build/dts/Install/Skill.d.ts.map +1 -0
  62. package/build/dts/Install/Uninstall.d.ts +32 -0
  63. package/build/dts/Install/Uninstall.d.ts.map +1 -0
  64. package/build/dts/Mcp/ExpandDocs.d.ts +7 -0
  65. package/build/dts/Mcp/ExpandDocs.d.ts.map +1 -0
  66. package/build/dts/Mcp/RequestHeaders.d.ts +15 -0
  67. package/build/dts/Mcp/RequestHeaders.d.ts.map +1 -0
  68. package/build/dts/Mcp/Server.d.ts +10 -0
  69. package/build/dts/Mcp/Server.d.ts.map +1 -0
  70. package/build/dts/Mcp/Toolkit.d.ts +3 -0
  71. package/build/dts/Mcp/Toolkit.d.ts.map +1 -0
  72. package/build/dts/Mcp/tools/Citations.d.ts +237 -0
  73. package/build/dts/Mcp/tools/Citations.d.ts.map +1 -0
  74. package/build/dts/Mcp/tools/Fetch.d.ts +167 -0
  75. package/build/dts/Mcp/tools/Fetch.d.ts.map +1 -0
  76. package/build/dts/Snippets.d.ts +19 -0
  77. package/build/dts/Snippets.d.ts.map +1 -0
  78. package/build/dts/index.d.ts +2 -0
  79. package/build/dts/index.d.ts.map +1 -0
  80. package/build/dts/main.d.ts +3 -0
  81. package/build/dts/main.d.ts.map +1 -0
  82. package/build/esm/ApiClient.js +182 -0
  83. package/build/esm/ApiClient.js.map +1 -0
  84. package/build/esm/Authentication.js +112 -0
  85. package/build/esm/Authentication.js.map +1 -0
  86. package/build/esm/BrowserOAuth.js +254 -0
  87. package/build/esm/BrowserOAuth.js.map +1 -0
  88. package/build/esm/Commands/Fetch.js +95 -0
  89. package/build/esm/Commands/Fetch.js.map +1 -0
  90. package/build/esm/Commands/Hook.js +20 -0
  91. package/build/esm/Commands/Hook.js.map +1 -0
  92. package/build/esm/Commands/Mcp.js +19 -0
  93. package/build/esm/Commands/Mcp.js.map +1 -0
  94. package/build/esm/Commands/McpRun.js +15 -0
  95. package/build/esm/Commands/McpRun.js.map +1 -0
  96. package/build/esm/Commands/Search.js +43 -0
  97. package/build/esm/Commands/Search.js.map +1 -0
  98. package/build/esm/Commands/Skill.js +17 -0
  99. package/build/esm/Commands/Skill.js.map +1 -0
  100. package/build/esm/Commands/Uninstall.js +28 -0
  101. package/build/esm/Commands/Uninstall.js.map +1 -0
  102. package/build/esm/Config.js +145 -0
  103. package/build/esm/Config.js.map +1 -0
  104. package/build/esm/DeviceAuth.js +127 -0
  105. package/build/esm/DeviceAuth.js.map +1 -0
  106. package/build/esm/Hook/Claude.js +74 -0
  107. package/build/esm/Hook/Claude.js.map +1 -0
  108. package/build/esm/Hook/Errors.js +18 -0
  109. package/build/esm/Hook/Errors.js.map +1 -0
  110. package/build/esm/Hook/Opencode.js +50 -0
  111. package/build/esm/Hook/Opencode.js.map +1 -0
  112. package/build/esm/Hook/SnapshotNote.js +18 -0
  113. package/build/esm/Hook/SnapshotNote.js.map +1 -0
  114. package/build/esm/Install/Claude/Hook.js +89 -0
  115. package/build/esm/Install/Claude/Hook.js.map +1 -0
  116. package/build/esm/Install/Claude/Mcp.js +71 -0
  117. package/build/esm/Install/Claude/Mcp.js.map +1 -0
  118. package/build/esm/Install/Claude/Skill.js +34 -0
  119. package/build/esm/Install/Claude/Skill.js.map +1 -0
  120. package/build/esm/Install/Codex/Mcp.js +92 -0
  121. package/build/esm/Install/Codex/Mcp.js.map +1 -0
  122. package/build/esm/Install/Codex/Skill.js +30 -0
  123. package/build/esm/Install/Codex/Skill.js.map +1 -0
  124. package/build/esm/Install/Cursor/Mcp.js +71 -0
  125. package/build/esm/Install/Cursor/Mcp.js.map +1 -0
  126. package/build/esm/Install/Cursor/Skill.js +37 -0
  127. package/build/esm/Install/Cursor/Skill.js.map +1 -0
  128. package/build/esm/Install/Domain.js +105 -0
  129. package/build/esm/Install/Domain.js.map +1 -0
  130. package/build/esm/Install/Hook.js +38 -0
  131. package/build/esm/Install/Hook.js.map +1 -0
  132. package/build/esm/Install/Mcp.js +40 -0
  133. package/build/esm/Install/Mcp.js.map +1 -0
  134. package/build/esm/Install/Opencode/Hook.js +44 -0
  135. package/build/esm/Install/Opencode/Hook.js.map +1 -0
  136. package/build/esm/Install/Opencode/Mcp.js +73 -0
  137. package/build/esm/Install/Opencode/Mcp.js.map +1 -0
  138. package/build/esm/Install/Opencode/Skill.js +34 -0
  139. package/build/esm/Install/Opencode/Skill.js.map +1 -0
  140. package/build/esm/Install/Opencode/expandai-webfetch.js +38 -0
  141. package/build/esm/Install/Skill.js +41 -0
  142. package/build/esm/Install/Skill.js.map +1 -0
  143. package/build/esm/Install/Uninstall.js +49 -0
  144. package/build/esm/Install/Uninstall.js.map +1 -0
  145. package/build/esm/Mcp/ExpandDocs.js +64 -0
  146. package/build/esm/Mcp/ExpandDocs.js.map +1 -0
  147. package/build/esm/Mcp/RequestHeaders.js +13 -0
  148. package/build/esm/Mcp/RequestHeaders.js.map +1 -0
  149. package/build/esm/Mcp/Server.js +11 -0
  150. package/build/esm/Mcp/Server.js.map +1 -0
  151. package/build/esm/Mcp/Toolkit.js +16 -0
  152. package/build/esm/Mcp/Toolkit.js.map +1 -0
  153. package/build/esm/Mcp/tools/Citations.js +92 -0
  154. package/build/esm/Mcp/tools/Citations.js.map +1 -0
  155. package/build/esm/Mcp/tools/Fetch.js +141 -0
  156. package/build/esm/Mcp/tools/Fetch.js.map +1 -0
  157. package/build/esm/Snippets.js +18 -0
  158. package/build/esm/Snippets.js.map +1 -0
  159. package/build/esm/index.js +2 -0
  160. package/build/esm/index.js.map +1 -0
  161. package/build/esm/main.js +97 -0
  162. package/build/esm/main.js.map +1 -0
  163. package/build/skills/expandai/SKILL.md +72 -0
  164. package/package.json +72 -10
  165. package/src/ApiClient.ts +257 -0
  166. package/src/Authentication.ts +164 -0
  167. package/src/BrowserOAuth.ts +361 -0
  168. package/src/Commands/Fetch.ts +157 -0
  169. package/src/Commands/Hook.ts +48 -0
  170. package/src/Commands/Mcp.ts +30 -0
  171. package/src/Commands/McpRun.ts +25 -0
  172. package/src/Commands/Search.ts +92 -0
  173. package/src/Commands/Skill.ts +30 -0
  174. package/src/Commands/Uninstall.ts +38 -0
  175. package/src/Config.ts +195 -0
  176. package/src/DeviceAuth.ts +193 -0
  177. package/src/Hook/Claude.ts +81 -0
  178. package/src/Hook/Errors.ts +19 -0
  179. package/src/Hook/Opencode.ts +58 -0
  180. package/src/Hook/SnapshotNote.ts +18 -0
  181. package/src/Install/Claude/Hook.ts +133 -0
  182. package/src/Install/Claude/Mcp.ts +82 -0
  183. package/src/Install/Claude/Skill.ts +44 -0
  184. package/src/Install/Codex/Mcp.ts +109 -0
  185. package/src/Install/Codex/Skill.ts +40 -0
  186. package/src/Install/Cursor/Mcp.ts +82 -0
  187. package/src/Install/Cursor/Skill.ts +47 -0
  188. package/src/Install/Domain.ts +148 -0
  189. package/src/Install/Hook.ts +50 -0
  190. package/src/Install/Mcp.ts +71 -0
  191. package/src/Install/Opencode/Hook.ts +55 -0
  192. package/src/Install/Opencode/Mcp.ts +84 -0
  193. package/src/Install/Opencode/Skill.ts +44 -0
  194. package/src/Install/Opencode/expandai-webfetch.d.ts +23 -0
  195. package/src/Install/Opencode/expandai-webfetch.js +38 -0
  196. package/src/Install/Skill.ts +57 -0
  197. package/src/Install/Uninstall.ts +82 -0
  198. package/src/Mcp/ExpandDocs.ts +71 -0
  199. package/src/Mcp/RequestHeaders.ts +16 -0
  200. package/src/Mcp/Server.ts +14 -0
  201. package/src/Mcp/Toolkit.ts +21 -0
  202. package/src/Mcp/tools/Citations.ts +110 -0
  203. package/src/Mcp/tools/Fetch.ts +177 -0
  204. package/src/Snippets.ts +32 -0
  205. package/src/index.ts +1 -0
  206. package/src/main.ts +146 -0
  207. package/bun.lockb +0 -0
  208. package/index.ts +0 -1
  209. package/tsconfig.json +0 -27
@@ -0,0 +1,361 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
3
+ import { HttpClient, HttpClientRequest, HttpClientResponse } from '@effect/platform'
4
+ import { NodeHttpClient } from '@effect/platform-node'
5
+ import { DateTime, Duration, Effect, Inspectable, Redacted, Schema } from 'effect'
6
+ import { ConfigManager, OAuthConfig } from './Config.js'
7
+
8
+ const CLIENT_ID = 'expandai-cli'
9
+ const OAUTH_AUTHORIZE_ENDPOINT = '/api/auth/oauth2/authorize'
10
+ const OAUTH_TOKEN_ENDPOINT = '/api/auth/oauth2/token'
11
+ const OAUTH_SCOPE = 'openid profile email offline_access'
12
+ const LOOPBACK_HOST = '127.0.0.1'
13
+ const OAUTH_LOGIN_TIMEOUT = Duration.minutes(5)
14
+
15
+ const DurationFromSeconds = Schema.transform(Schema.Number, Schema.DurationFromSelf, {
16
+ strict: true,
17
+ decode: Duration.seconds,
18
+ encode: Duration.toSeconds,
19
+ })
20
+
21
+ export class TokenResponse extends Schema.Class<TokenResponse>('BrowserOAuthTokenResponse')({
22
+ access_token: Schema.String,
23
+ refresh_token: Schema.optional(Schema.String),
24
+ expires_in: DurationFromSeconds,
25
+ token_type: Schema.String,
26
+ scope: Schema.optional(Schema.String),
27
+ }) {}
28
+
29
+ export class BrowserOAuthRequestFailed extends Schema.TaggedError<BrowserOAuthRequestFailed>()(
30
+ 'BrowserOAuthRequestFailed',
31
+ {
32
+ endpoint: Schema.String,
33
+ error: Schema.Defect,
34
+ status: Schema.optional(Schema.Number),
35
+ },
36
+ ) {
37
+ get message() {
38
+ return `OAuth request to ${this.endpoint} failed${this.status ? ` (${this.status})` : ''}: ${Inspectable.format(this.error)}`
39
+ }
40
+ }
41
+
42
+ export class BrowserOAuthCallbackError extends Schema.TaggedError<BrowserOAuthCallbackError>()(
43
+ 'BrowserOAuthCallbackError',
44
+ {
45
+ error: Schema.String,
46
+ errorDescription: Schema.optional(Schema.String),
47
+ },
48
+ ) {
49
+ get message() {
50
+ return this.errorDescription ? `${this.error}: ${this.errorDescription}` : this.error
51
+ }
52
+ }
53
+
54
+ export class BrowserOAuthMissingCode extends Schema.TaggedError<BrowserOAuthMissingCode>()(
55
+ 'BrowserOAuthMissingCode',
56
+ {},
57
+ ) {
58
+ get message() {
59
+ return 'OAuth callback did not include an authorization code.'
60
+ }
61
+ }
62
+
63
+ export class BrowserOAuthStateMismatch extends Schema.TaggedError<BrowserOAuthStateMismatch>()(
64
+ 'BrowserOAuthStateMismatch',
65
+ {},
66
+ ) {
67
+ get message() {
68
+ return 'OAuth callback state did not match the login request.'
69
+ }
70
+ }
71
+
72
+ export class BrowserOAuthLoopbackFailed extends Schema.TaggedError<BrowserOAuthLoopbackFailed>()(
73
+ 'BrowserOAuthLoopbackFailed',
74
+ {
75
+ error: Schema.Defect,
76
+ },
77
+ ) {
78
+ get message() {
79
+ return `Could not start OAuth loopback server: ${Inspectable.format(this.error)}`
80
+ }
81
+ }
82
+
83
+ export class BrowserOAuthTimedOut extends Schema.TaggedError<BrowserOAuthTimedOut>()('BrowserOAuthTimedOut', {}) {
84
+ get message() {
85
+ return 'OAuth browser login timed out before the local callback completed.'
86
+ }
87
+ }
88
+
89
+ type CallbackFailure = BrowserOAuthCallbackError | BrowserOAuthMissingCode | BrowserOAuthStateMismatch
90
+
91
+ interface AuthorizeUrlInput {
92
+ readonly apiUrl: URL
93
+ readonly redirectUri: URL
94
+ readonly state: string
95
+ readonly codeChallenge: string
96
+ }
97
+
98
+ interface ExchangeCodeInput {
99
+ readonly code: string
100
+ readonly redirectUri: URL
101
+ readonly codeVerifier: string
102
+ }
103
+
104
+ interface LoopbackServer {
105
+ readonly redirectUri: URL
106
+ readonly waitForCode: Effect.Effect<string, CallbackFailure>
107
+ readonly close: Effect.Effect<void>
108
+ }
109
+
110
+ function base64Url(bytes: Uint8Array): string {
111
+ return Buffer.from(bytes).toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
112
+ }
113
+
114
+ function createHighEntropySecret(): string {
115
+ return base64Url(randomBytes(32))
116
+ }
117
+
118
+ export const createCodeChallenge = Effect.fn('BrowserOAuth.createCodeChallenge')(function* (codeVerifier: string) {
119
+ return base64Url(createHash('sha256').update(codeVerifier).digest())
120
+ })
121
+
122
+ export const buildAuthorizeUrl = Effect.fn('BrowserOAuth.buildAuthorizeUrl')(function* ({
123
+ apiUrl,
124
+ redirectUri,
125
+ state,
126
+ codeChallenge,
127
+ }: AuthorizeUrlInput) {
128
+ const authorizeUrl = new URL(OAUTH_AUTHORIZE_ENDPOINT, apiUrl)
129
+ authorizeUrl.searchParams.set('response_type', 'code')
130
+ authorizeUrl.searchParams.set('client_id', CLIENT_ID)
131
+ authorizeUrl.searchParams.set('redirect_uri', redirectUri.toString())
132
+ authorizeUrl.searchParams.set('scope', OAUTH_SCOPE)
133
+ authorizeUrl.searchParams.set('code_challenge', codeChallenge)
134
+ authorizeUrl.searchParams.set('code_challenge_method', 'S256')
135
+ authorizeUrl.searchParams.set('state', state)
136
+ return authorizeUrl
137
+ })
138
+
139
+ function respond(response: ServerResponse, status: number, body: string): void {
140
+ response.writeHead(status, { 'content-type': 'text/html; charset=utf-8' })
141
+ response.end(body)
142
+ }
143
+
144
+ function validateCallback(request: IncomingMessage, expectedState: string): string {
145
+ const callbackUrl = new URL(request.url ?? '/', `http://${LOOPBACK_HOST}`)
146
+ const error = callbackUrl.searchParams.get('error')
147
+ if (error !== null) {
148
+ throw new BrowserOAuthCallbackError({
149
+ error,
150
+ errorDescription: callbackUrl.searchParams.get('error_description') ?? undefined,
151
+ })
152
+ }
153
+
154
+ if (callbackUrl.searchParams.get('state') !== expectedState) {
155
+ throw new BrowserOAuthStateMismatch()
156
+ }
157
+
158
+ const code = callbackUrl.searchParams.get('code')
159
+ if (code === null || code.length === 0) {
160
+ throw new BrowserOAuthMissingCode()
161
+ }
162
+
163
+ return code
164
+ }
165
+
166
+ function toCallbackFailure(error: unknown): CallbackFailure {
167
+ if (
168
+ error instanceof BrowserOAuthCallbackError ||
169
+ error instanceof BrowserOAuthMissingCode ||
170
+ error instanceof BrowserOAuthStateMismatch
171
+ ) {
172
+ return error
173
+ }
174
+ return new BrowserOAuthCallbackError({ error: 'server_error', errorDescription: Inspectable.format(error) })
175
+ }
176
+
177
+ function closeServer(server: Server): Effect.Effect<void> {
178
+ return Effect.async<void>((resume) => {
179
+ server.close((error) => {
180
+ if (error) {
181
+ resume(Effect.void)
182
+ return
183
+ }
184
+ resume(Effect.void)
185
+ })
186
+ })
187
+ }
188
+
189
+ const startLoopbackServer = Effect.fn('BrowserOAuth.startLoopbackServer')(function* (expectedState: string) {
190
+ return yield* Effect.async<LoopbackServer, BrowserOAuthLoopbackFailed>((resume) => {
191
+ let settled = false
192
+ let resolveCode: (code: string) => void = () => undefined
193
+ let rejectCode: (error: CallbackFailure) => void = () => undefined
194
+ const codePromise = new Promise<string>((resolve, reject) => {
195
+ resolveCode = resolve
196
+ rejectCode = (error) => reject(error)
197
+ })
198
+
199
+ const server = createServer((request, response) => {
200
+ const requestUrl = new URL(request.url ?? '/', `http://${LOOPBACK_HOST}`)
201
+ if (requestUrl.pathname !== '/callback') {
202
+ respond(response, 404, 'Not found')
203
+ return
204
+ }
205
+
206
+ if (settled) {
207
+ respond(response, 409, 'OAuth callback already handled.')
208
+ return
209
+ }
210
+ settled = true
211
+
212
+ try {
213
+ const code = validateCallback(request, expectedState)
214
+ respond(response, 200, 'Authentication complete. You can close this tab.')
215
+ resolveCode(code)
216
+ } catch (error) {
217
+ respond(response, 400, 'Authentication failed. Return to the terminal and try again.')
218
+ rejectCode(toCallbackFailure(error))
219
+ }
220
+ })
221
+
222
+ server.once('error', (error) => {
223
+ resume(Effect.fail(new BrowserOAuthLoopbackFailed({ error })))
224
+ })
225
+
226
+ server.listen(0, LOOPBACK_HOST, () => {
227
+ const address = server.address()
228
+ if (address === null || typeof address === 'string') {
229
+ resume(Effect.fail(new BrowserOAuthLoopbackFailed({ error: 'loopback server did not report a port' })))
230
+ return
231
+ }
232
+
233
+ resume(
234
+ Effect.succeed({
235
+ redirectUri: new URL(`http://${LOOPBACK_HOST}:${address.port}/callback`),
236
+ waitForCode: Effect.tryPromise({
237
+ try: () => codePromise,
238
+ catch: toCallbackFailure,
239
+ }),
240
+ close: closeServer(server),
241
+ }),
242
+ )
243
+ })
244
+ })
245
+ })
246
+
247
+ export class BrowserOAuthService extends Effect.Service<BrowserOAuthService>()('@expandai/cli/BrowserOAuthService', {
248
+ dependencies: [NodeHttpClient.layer, ConfigManager.Default],
249
+ effect: Effect.gen(function* () {
250
+ const httpClient = yield* HttpClient.HttpClient
251
+ const configManager = yield* ConfigManager
252
+
253
+ const exchangeToken = Effect.fn('BrowserOAuthService.exchangeToken')(function* (
254
+ form: ReadonlyArray<readonly [string, string]>,
255
+ ) {
256
+ const apiUrl = yield* configManager.getApiUrl()
257
+ const resource = apiUrl.toString()
258
+ const request = HttpClientRequest.post(new URL(OAUTH_TOKEN_ENDPOINT, apiUrl)).pipe(
259
+ HttpClientRequest.bodyUrlParams([...form, ['resource', resource]]),
260
+ )
261
+
262
+ return yield* httpClient.execute(request).pipe(
263
+ Effect.flatMap(
264
+ HttpClientResponse.matchStatus({
265
+ '200': (response) => HttpClientResponse.schemaBodyJson(TokenResponse)(response),
266
+ orElse: (response) =>
267
+ response.text.pipe(
268
+ Effect.flatMap((body) =>
269
+ Effect.fail(
270
+ new BrowserOAuthRequestFailed({
271
+ endpoint: OAUTH_TOKEN_ENDPOINT,
272
+ status: response.status,
273
+ error: body,
274
+ }),
275
+ ),
276
+ ),
277
+ ),
278
+ }),
279
+ ),
280
+ Effect.catchTags({
281
+ RequestError: (error) =>
282
+ Effect.fail(new BrowserOAuthRequestFailed({ endpoint: OAUTH_TOKEN_ENDPOINT, error })),
283
+ ResponseError: (error) =>
284
+ Effect.fail(new BrowserOAuthRequestFailed({ endpoint: OAUTH_TOKEN_ENDPOINT, error })),
285
+ ParseError: (error) => Effect.fail(new BrowserOAuthRequestFailed({ endpoint: OAUTH_TOKEN_ENDPOINT, error })),
286
+ }),
287
+ )
288
+ })
289
+
290
+ const exchangeCode = Effect.fn('BrowserOAuthService.exchangeCode')(function* ({
291
+ code,
292
+ redirectUri,
293
+ codeVerifier,
294
+ }: ExchangeCodeInput) {
295
+ return yield* exchangeToken([
296
+ ['grant_type', 'authorization_code'],
297
+ ['client_id', CLIENT_ID],
298
+ ['code', code],
299
+ ['redirect_uri', redirectUri.toString()],
300
+ ['code_verifier', codeVerifier],
301
+ ])
302
+ })
303
+
304
+ const refreshToken = Effect.fn('BrowserOAuthService.refreshToken')(function* (refreshToken: string) {
305
+ return yield* exchangeToken([
306
+ ['grant_type', 'refresh_token'],
307
+ ['client_id', CLIENT_ID],
308
+ ['refresh_token', refreshToken],
309
+ ])
310
+ })
311
+
312
+ const saveToken = Effect.fn('BrowserOAuthService.saveToken')(function* (tokenResponse: TokenResponse) {
313
+ const now = yield* DateTime.now
314
+ const expiresAt = DateTime.addDuration(now, tokenResponse.expires_in)
315
+
316
+ yield* configManager.updateConfig({
317
+ authMethod: OAuthConfig.make({
318
+ accessToken: Redacted.make(tokenResponse.access_token),
319
+ refreshToken:
320
+ tokenResponse.refresh_token === undefined ? undefined : Redacted.make(tokenResponse.refresh_token),
321
+ expiresAt,
322
+ }),
323
+ })
324
+ })
325
+
326
+ const login = Effect.fn('BrowserOAuthService.login')(function* <R>(
327
+ openAuthorizeUrl: (authorizeUrl: URL) => Effect.Effect<void, unknown, R>,
328
+ ) {
329
+ const codeVerifier = createHighEntropySecret()
330
+ const state = createHighEntropySecret()
331
+ const codeChallenge = yield* createCodeChallenge(codeVerifier)
332
+ const loopback = yield* startLoopbackServer(state)
333
+ const apiUrl = yield* configManager.getApiUrl()
334
+ const authorizeUrl = yield* buildAuthorizeUrl({
335
+ apiUrl,
336
+ redirectUri: loopback.redirectUri,
337
+ state,
338
+ codeChallenge,
339
+ })
340
+
341
+ const code = yield* openAuthorizeUrl(authorizeUrl).pipe(
342
+ Effect.zipRight(loopback.waitForCode),
343
+ Effect.timeoutFail({
344
+ duration: OAUTH_LOGIN_TIMEOUT,
345
+ onTimeout: () => new BrowserOAuthTimedOut(),
346
+ }),
347
+ Effect.ensuring(loopback.close),
348
+ )
349
+ const token = yield* exchangeCode({ code, redirectUri: loopback.redirectUri, codeVerifier })
350
+ if (token === undefined) {
351
+ return yield* new BrowserOAuthRequestFailed({
352
+ endpoint: OAUTH_TOKEN_ENDPOINT,
353
+ error: 'OAuth token endpoint returned an empty response body',
354
+ })
355
+ }
356
+ yield* saveToken(token)
357
+ })
358
+
359
+ return { exchangeCode, refreshToken, saveToken, login } as const
360
+ }),
361
+ }) {}
@@ -0,0 +1,157 @@
1
+ import { Args, Command, HelpDoc, Options } from '@effect/cli'
2
+ import { DEFAULT_PLAYGROUND_HOST, resolvePlaygroundHost } from '@expandai/sdk/Playground'
3
+ import { Console, Effect, Match, Option, Schema, String } from 'effect'
4
+ import { ApiClient } from '../ApiClient.js'
5
+ import { renderSnippets } from '../Snippets.js'
6
+
7
+ export class MarkdownUnavailable extends Schema.TaggedError<MarkdownUnavailable>()('MarkdownUnavailable', {
8
+ url: Schema.String,
9
+ }) {
10
+ get message() {
11
+ return `No markdown content was returned for ${this.url}`
12
+ }
13
+ }
14
+
15
+ export class SnippetsUnavailable extends Schema.TaggedError<SnippetsUnavailable>()('SnippetsUnavailable', {
16
+ url: Schema.String,
17
+ query: Schema.String,
18
+ }) {
19
+ get message() {
20
+ return `No snippets were returned for ${this.url} matching '${this.query}'`
21
+ }
22
+ }
23
+
24
+ // `Options.text('format').pipe(Options.withDefault('text'))` is optional, so
25
+ // when the user types `expandai fetch --format` (no value) the parser falls
26
+ // through to the default and `--format` is fed to the URL positional. WHATWG's
27
+ // URL parser accepts `https://--format` as a host-only URL, so without this
28
+ // guard the bogus value reaches the API. Reject flag-looking input up front,
29
+ // and require a hostname with a dot (or `localhost`) so `fetch help` etc. fail
30
+ // here with a clear message instead of via the API's schema decoder.
31
+ //
32
+ // `Args.mapEffect` is preferred over `Args.withSchema` because the latter
33
+ // renders failures with `ParseResult.TreeFormatter`, which dumps the full
34
+ // schema-decode trace.
35
+ export const parseUrlArg = Effect.fn('Fetch.parseUrlArg')(function* (raw: string) {
36
+ if (raw.startsWith('-')) {
37
+ return yield* Effect.fail(HelpDoc.p(`Missing argument <url> (received '${raw}')`))
38
+ }
39
+ const candidate = raw.startsWith('http://') || raw.startsWith('https://') ? raw : `https://${raw}`
40
+ const parsed = yield* Effect.try({
41
+ try: () => new URL(candidate),
42
+ catch: () => HelpDoc.p(`Invalid URL '${raw}'`),
43
+ })
44
+ if (!parsed.hostname.includes('.') && parsed.hostname !== 'localhost') {
45
+ return yield* Effect.fail(HelpDoc.p(`URL must contain a valid domain (got '${raw}')`))
46
+ }
47
+ return parsed
48
+ })
49
+
50
+ const url = Args.text({ name: 'url' }).pipe(Args.mapEffect(parseUrlArg))
51
+
52
+ const format = Options.text('format').pipe(
53
+ Options.withDefault('text'),
54
+ Options.withDescription('Output format (text or json)'),
55
+ Options.withSchema(Schema.Literal('text', 'json')),
56
+ )
57
+
58
+ const search = Options.text('search').pipe(
59
+ Options.optional,
60
+ Options.withDescription('Semantic search query. Returns relevant snippets instead of markdown.'),
61
+ )
62
+
63
+ const maxResults = Options.integer('max-results').pipe(
64
+ Options.withDefault(5),
65
+ Options.withDescription('Maximum snippets to return when using --search (default: 5)'),
66
+ Options.withSchema(Schema.Int.pipe(Schema.greaterThanOrEqualTo(1), Schema.lessThanOrEqualTo(50))),
67
+ )
68
+
69
+ const minScore = Options.float('min-score').pipe(
70
+ Options.withDefault(0.6),
71
+ Options.withDescription('Minimum snippet relevance score from 0 to 1 when using --search (default: 0.6)'),
72
+ Options.withSchema(Schema.Number.pipe(Schema.greaterThanOrEqualTo(0), Schema.lessThanOrEqualTo(1))),
73
+ )
74
+
75
+ const fetchConfig = {
76
+ url,
77
+ format,
78
+ search,
79
+ maxResults,
80
+ minScore,
81
+ }
82
+
83
+ interface FetchCommandConfig {
84
+ readonly url: URL
85
+ readonly format: 'text' | 'json'
86
+ readonly search: Option.Option<string>
87
+ readonly maxResults: number
88
+ readonly minScore: number
89
+ }
90
+
91
+ export const FetchCommand: Command.Command<'fetch', never, unknown, FetchCommandConfig> = Command.make(
92
+ 'fetch',
93
+ fetchConfig,
94
+ ).pipe(
95
+ Command.withDescription('Fetch content from a URL as markdown or snippets'),
96
+ Command.withHandler(
97
+ Effect.fnUntraced(function* ({ format, maxResults, minScore, search, url }) {
98
+ const client = yield* ApiClient
99
+ const query = Option.getOrUndefined(search)
100
+ const fetchRequest =
101
+ query === undefined
102
+ ? {
103
+ params: {},
104
+ payload: {
105
+ url: url.toString(),
106
+ include: { markdown: true },
107
+ },
108
+ }
109
+ : {
110
+ params: {},
111
+ payload: {
112
+ url: url.toString(),
113
+ include: { markdown: true, json: true },
114
+ search: {
115
+ query,
116
+ maxResults,
117
+ minScore,
118
+ },
119
+ },
120
+ }
121
+
122
+ const output =
123
+ format === 'text' && query === undefined
124
+ ? yield* client
125
+ .fetchFetch(fetchRequest)
126
+ .pipe(
127
+ Effect.flatMap((markdown) =>
128
+ String.isNonEmpty(markdown)
129
+ ? Effect.succeed(markdown)
130
+ : Effect.fail(new MarkdownUnavailable({ url: url.toString() })),
131
+ ),
132
+ )
133
+ : yield* client.fetchFetchResult(fetchRequest).pipe(
134
+ Effect.flatMap((fetched) =>
135
+ Match.value(format).pipe(
136
+ Match.when('text', () => {
137
+ const snippets = fetched.data?.search?.snippets ?? []
138
+ return snippets.length === 0
139
+ ? Effect.fail(new SnippetsUnavailable({ url: url.toString(), query: query ?? '' }))
140
+ : Effect.succeed(
141
+ renderSnippets(
142
+ fetched.meta.snapshotId,
143
+ resolvePlaygroundHost(fetched.meta.playground, DEFAULT_PLAYGROUND_HOST),
144
+ snippets,
145
+ ),
146
+ )
147
+ }),
148
+ Match.when('json', () => Schema.encode(Schema.parseJson(Schema.Unknown, { space: 2 }))(fetched)),
149
+ Match.exhaustive,
150
+ ),
151
+ ),
152
+ )
153
+
154
+ yield* Console.log(output)
155
+ }, Effect.provide(ApiClient.Default)),
156
+ ),
157
+ )
@@ -0,0 +1,48 @@
1
+ import { Args, Command } from '@effect/cli'
2
+ import { Effect } from 'effect'
3
+ import { ClaudeHook } from '../Hook/Claude.js'
4
+ import { OpencodeHook } from '../Hook/Opencode.js'
5
+ import { HookInstaller } from '../Install/Hook.js'
6
+
7
+ const ClaudeRunCommand = Command.make('claude-code').pipe(
8
+ Command.withDescription('Run the Claude Code WebFetch hook protocol over stdio'),
9
+ Command.withHandler(() => Effect.flatMap(ClaudeHook, (hook) => hook.runProtocol())),
10
+ )
11
+
12
+ const OpencodeRunCommand = Command.make('opencode').pipe(
13
+ Command.withDescription('Run the OpenCode webfetch plugin protocol over stdio'),
14
+ Command.withHandler(() => Effect.flatMap(OpencodeHook, (hook) => hook.runProtocol())),
15
+ )
16
+
17
+ const hostArg = Args.choice([
18
+ ['claude-code', 'claude-code' as const],
19
+ ['opencode', 'opencode' as const],
20
+ ])
21
+ const scopeArg = Args.choice([
22
+ ['global', 'global' as const],
23
+ ['project', 'project' as const],
24
+ ])
25
+
26
+ const InstallSubCommand = Command.make('install', { host: hostArg, scope: scopeArg }).pipe(
27
+ Command.withDescription('Install the expandai MCP server + webfetch hook for the chosen host + scope'),
28
+ Command.withHandler(({ host, scope }) =>
29
+ Effect.flatMap(HookInstaller, (installer) => installer.install(host, scope)),
30
+ ),
31
+ )
32
+
33
+ const UninstallSubCommand = Command.make('uninstall', { host: hostArg, scope: scopeArg }).pipe(
34
+ Command.withDescription('Remove the expandai MCP server + webfetch hook for the chosen host + scope'),
35
+ Command.withHandler(({ host, scope }) =>
36
+ Effect.flatMap(HookInstaller, (installer) => installer.uninstall(host, scope)),
37
+ ),
38
+ )
39
+
40
+ export const HumanHookCommand = Command.make('hook').pipe(
41
+ Command.withDescription('expandai hooks for AI coding assistants'),
42
+ Command.withSubcommands([ClaudeRunCommand, OpencodeRunCommand, InstallSubCommand, UninstallSubCommand]),
43
+ )
44
+
45
+ export const AgentHookCommand = Command.make('hook').pipe(
46
+ Command.withDescription('expandai hooks for AI coding assistants'),
47
+ Command.withSubcommands([ClaudeRunCommand, OpencodeRunCommand]),
48
+ )
@@ -0,0 +1,30 @@
1
+ import { Args, Command } from '@effect/cli'
2
+ import { Effect } from 'effect'
3
+ import { Mcp } from '../Install/Mcp.js'
4
+
5
+ const hostArg = Args.choice([
6
+ ['claude-code', 'claude-code' as const],
7
+ ['cursor', 'cursor' as const],
8
+ ['opencode', 'opencode' as const],
9
+ ['codex', 'codex' as const],
10
+ ])
11
+
12
+ const scopeArg = Args.choice([
13
+ ['global', 'global' as const],
14
+ ['project', 'project' as const],
15
+ ])
16
+
17
+ export const InstallSubCommand = Command.make('install', { host: hostArg, scope: scopeArg }).pipe(
18
+ Command.withDescription('Install the expandai MCP server into the chosen host + scope (e.g. `claude-code global`)'),
19
+ Command.withHandler(
20
+ Effect.fnUntraced(function* ({ host, scope }) {
21
+ const mcp = yield* Mcp
22
+ yield* mcp.install(host, scope)
23
+ }),
24
+ ),
25
+ )
26
+
27
+ export const UninstallSubCommand = Command.make('uninstall', { host: hostArg, scope: scopeArg }).pipe(
28
+ Command.withDescription('Remove the expandai MCP server from the chosen host + scope'),
29
+ Command.withHandler(({ host, scope }) => Effect.flatMap(Mcp, (mcp) => mcp.uninstall(host, scope))),
30
+ )
@@ -0,0 +1,25 @@
1
+ import { McpServer } from '@effect/ai'
2
+ import { Command, Options } from '@effect/cli'
3
+ import { NodeSink, NodeStream } from '@effect/platform-node'
4
+ import { Effect, Layer } from 'effect'
5
+ import { makeServerLayer, ServerInfo } from '../Mcp/Server.js'
6
+
7
+ const includeDocsOption = Options.boolean('docs').pipe(
8
+ Options.withDefault(false),
9
+ Options.withDescription('Expose documentation resources alongside tools'),
10
+ )
11
+
12
+ export const McpRunCommand = Command.make('run', { includeDocs: includeDocsOption }).pipe(
13
+ Command.withDescription('Run the expandai MCP server over stdio'),
14
+ Command.withHandler(
15
+ Effect.fnUntraced(function* ({ includeDocs }) {
16
+ const McpLayer = McpServer.layerStdio({
17
+ ...ServerInfo,
18
+ stdin: NodeStream.stdin,
19
+ stdout: NodeSink.stdout,
20
+ }).pipe(Layer.provide(makeServerLayer({ includeDocs })))
21
+
22
+ return yield* Layer.launch(McpLayer)
23
+ }),
24
+ ),
25
+ )