@llm4ts/flow 2.54.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/Activity.d.ts +1 -1
  2. package/dist/Activity.d.ts.map +1 -1
  3. package/dist/Activity.js +20 -0
  4. package/dist/Activity.js.map +1 -1
  5. package/dist/EstimatedUsage.d.ts.map +1 -1
  6. package/dist/EstimatedUsage.js +0 -1
  7. package/dist/EstimatedUsage.js.map +1 -1
  8. package/dist/Pack.d.ts +11 -0
  9. package/dist/Pack.d.ts.map +1 -1
  10. package/dist/Pack.js +2 -0
  11. package/dist/Pack.js.map +1 -1
  12. package/dist/Replay.d.ts.map +1 -1
  13. package/dist/Replay.js +1 -4
  14. package/dist/Replay.js.map +1 -1
  15. package/dist/RosterSeats.d.ts.map +1 -1
  16. package/dist/RosterSeats.js +0 -1
  17. package/dist/RosterSeats.js.map +1 -1
  18. package/dist/Timing.d.ts.map +1 -1
  19. package/dist/Timing.js +0 -1
  20. package/dist/Timing.js.map +1 -1
  21. package/dist/Transcript.d.ts.map +1 -1
  22. package/dist/Transcript.js +0 -1
  23. package/dist/Transcript.js.map +1 -1
  24. package/dist/TransientRetry.d.ts.map +1 -1
  25. package/dist/TransientRetry.js +0 -1
  26. package/dist/TransientRetry.js.map +1 -1
  27. package/dist/endpoint/Auth.d.ts +194 -0
  28. package/dist/endpoint/Auth.d.ts.map +1 -0
  29. package/dist/endpoint/Auth.js +302 -0
  30. package/dist/endpoint/Auth.js.map +1 -0
  31. package/dist/endpoint/Endpoints.d.ts +21 -0
  32. package/dist/endpoint/Endpoints.d.ts.map +1 -0
  33. package/dist/endpoint/Endpoints.js +34 -0
  34. package/dist/endpoint/Endpoints.js.map +1 -0
  35. package/dist/endpoint/Transport.d.ts +90 -0
  36. package/dist/endpoint/Transport.d.ts.map +1 -0
  37. package/dist/endpoint/Transport.js +306 -0
  38. package/dist/endpoint/Transport.js.map +1 -0
  39. package/dist/tools/Builtin.d.ts +5 -0
  40. package/dist/tools/Builtin.d.ts.map +1 -0
  41. package/dist/tools/Builtin.js +7 -0
  42. package/dist/tools/Builtin.js.map +1 -0
  43. package/dist/tools/Diff.d.ts +8 -0
  44. package/dist/tools/Diff.d.ts.map +1 -0
  45. package/dist/tools/Diff.js +45 -0
  46. package/dist/tools/Diff.js.map +1 -0
  47. package/dist/tools/HttpCall.d.ts +14 -0
  48. package/dist/tools/HttpCall.d.ts.map +1 -0
  49. package/dist/tools/HttpCall.js +101 -0
  50. package/dist/tools/HttpCall.js.map +1 -0
  51. package/dist/tools/JsonSchemaCheck.d.ts +36 -0
  52. package/dist/tools/JsonSchemaCheck.d.ts.map +1 -0
  53. package/dist/tools/JsonSchemaCheck.js +342 -0
  54. package/dist/tools/JsonSchemaCheck.js.map +1 -0
  55. package/dist/tools/JsonValidate.d.ts +11 -0
  56. package/dist/tools/JsonValidate.d.ts.map +1 -0
  57. package/dist/tools/JsonValidate.js +84 -0
  58. package/dist/tools/JsonValidate.js.map +1 -0
  59. package/dist/tools/Tool.d.ts +126 -0
  60. package/dist/tools/Tool.d.ts.map +1 -0
  61. package/dist/tools/Tool.js +218 -0
  62. package/dist/tools/Tool.js.map +1 -0
  63. package/dist/tools/TreeDiff.d.ts +42 -0
  64. package/dist/tools/TreeDiff.d.ts.map +1 -0
  65. package/dist/tools/TreeDiff.js +276 -0
  66. package/dist/tools/TreeDiff.js.map +1 -0
  67. package/package.json +12 -4
  68. package/src/Activity.ts +22 -0
  69. package/src/EstimatedUsage.ts +0 -1
  70. package/src/Pack.ts +16 -0
  71. package/src/Replay.ts +1 -7
  72. package/src/RosterSeats.ts +0 -2
  73. package/src/Timing.ts +0 -10
  74. package/src/Transcript.ts +0 -1
  75. package/src/TransientRetry.ts +0 -2
  76. package/src/endpoint/Auth.ts +446 -0
  77. package/src/endpoint/Endpoints.ts +54 -0
  78. package/src/endpoint/Transport.ts +456 -0
  79. package/src/tools/Builtin.ts +10 -0
  80. package/src/tools/Diff.ts +61 -0
  81. package/src/tools/HttpCall.ts +124 -0
  82. package/src/tools/JsonSchemaCheck.ts +457 -0
  83. package/src/tools/JsonValidate.ts +106 -0
  84. package/src/tools/Tool.ts +351 -0
  85. package/src/tools/TreeDiff.ts +386 -0
  86. package/dist/WorkspaceLayout.d.ts +0 -3
  87. package/dist/WorkspaceLayout.d.ts.map +0 -1
  88. package/dist/WorkspaceLayout.js +0 -19
  89. package/dist/WorkspaceLayout.js.map +0 -1
  90. package/dist/WorkspaceTools.d.ts +0 -4
  91. package/dist/WorkspaceTools.d.ts.map +0 -1
  92. package/dist/WorkspaceTools.js +0 -130
  93. package/dist/WorkspaceTools.js.map +0 -1
  94. package/src/WorkspaceLayout.ts +0 -22
  95. package/src/WorkspaceTools.ts +0 -188
@@ -0,0 +1,456 @@
1
+ import * as http from "node:http"
2
+ import * as https from "node:https"
3
+ import * as net from "node:net"
4
+ import * as tls from "node:tls"
5
+ import * as Context from "effect/Context"
6
+ import * as Duration from "effect/Duration"
7
+ import * as Effect from "effect/Effect"
8
+ import * as Redacted from "effect/Redacted"
9
+ import * as Ref from "effect/Ref"
10
+ import * as Schema from "effect/Schema"
11
+ import { bypassesProxy, type ResolvedProxy, type ResolvedTls } from "./Auth.ts"
12
+
13
+ // The HTTP seam for everything that leaves the machine: fetching WSDLs from
14
+ // a URL, calling operations, asking an STS for a token. Secrets travel only
15
+ // as `Redacted` values in `secretHeaders`, the body (an envelope may carry a
16
+ // WS-Security header), `tls` and the proxy's authorization; errors carry
17
+ // the URL and a reason code, never a header or body. The Node implementation
18
+ // uses `node:https` directly because global `fetch` cannot present a client
19
+ // certificate, tunnels through an explicit proxy with HTTP CONNECT (proxy
20
+ // environment variables are never read), and adds the profile's CA
21
+ // material to Node's system roots instead of replacing them.
22
+
23
+ export interface SoapHttpRequest {
24
+ readonly method: "GET" | "POST"
25
+ readonly url: string
26
+ /** Non-secret headers (content type, SOAPAction). */
27
+ readonly headers: Readonly<Record<string, string>>
28
+ /** Secret headers (authorization). */
29
+ readonly secretHeaders: ReadonlyArray<readonly [string, Redacted.Redacted<string>]>
30
+ readonly body?: Redacted.Redacted<string>
31
+ readonly tls?: ResolvedTls
32
+ readonly proxy?: ResolvedProxy
33
+ readonly timeout: Duration.Duration
34
+ }
35
+
36
+ export interface SoapHttpResponse {
37
+ readonly status: number
38
+ readonly headers: Readonly<Record<string, string>>
39
+ readonly body: Uint8Array
40
+ readonly elapsedMs: number
41
+ }
42
+
43
+ export class TransportError extends Schema.TaggedError<TransportError>()("TransportError", {
44
+ url: Schema.String,
45
+ reason: Schema.Literals(["scheme", "network", "tls", "timeout", "aborted", "proxy"]),
46
+ detail: Schema.String
47
+ }) {
48
+ get message(): string {
49
+ return `${this.url}: ${this.reason}: ${this.detail}`
50
+ }
51
+ }
52
+
53
+ /** One certificate of the chain a server presents, as `peerChain` reads it. */
54
+ export interface PeerCertificate {
55
+ readonly subject: string
56
+ readonly issuer: string
57
+ readonly validFrom: string
58
+ readonly validTo: string
59
+ /** SHA-256 over the DER, colon-separated hex. */
60
+ readonly fingerprint256: string
61
+ readonly pem: string
62
+ }
63
+
64
+ export interface PeerChain {
65
+ readonly host: string
66
+ /** Leaf first. */
67
+ readonly certificates: ReadonlyArray<PeerCertificate>
68
+ /** Whether Node's system roots already trust this chain. */
69
+ readonly trustedBySystem: boolean
70
+ readonly authorizationError: string | undefined
71
+ }
72
+
73
+ export interface PeerChainOptions {
74
+ readonly proxy?: ResolvedProxy
75
+ readonly servername?: string
76
+ readonly timeout: Duration.Duration
77
+ }
78
+
79
+ export interface SoapTransportShape {
80
+ readonly send: (request: SoapHttpRequest) => Effect.Effect<SoapHttpResponse, TransportError>
81
+ /**
82
+ * The chain an https endpoint presents, read without verifying it and
83
+ * without sending a request: what `trust` shows before pinning. Nothing
84
+ * else may call this.
85
+ */
86
+ readonly peerChain: (
87
+ url: string,
88
+ options: PeerChainOptions
89
+ ) => Effect.Effect<PeerChain, TransportError>
90
+ }
91
+
92
+ export class SoapTransport extends Context.Service<SoapTransport, SoapTransportShape>()(
93
+ "@llm4ts/flow/endpoint/SoapTransport"
94
+ ) {}
95
+
96
+ /** Strip query string and credentials from a URL before it lands in an error or a file. */
97
+ export const displayUrl = (raw: string): string => {
98
+ try {
99
+ const url = new URL(raw)
100
+ return `${url.protocol}//${url.host}${url.pathname}`
101
+ } catch {
102
+ return "(invalid url)"
103
+ }
104
+ }
105
+
106
+ const errorCode = (cause: unknown): string =>
107
+ typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string"
108
+ ? cause.code
109
+ : "request failed"
110
+
111
+ const tlsCodes = /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO|DEPTH_ZERO|ERR_OSSL/
112
+ const unknownIssuer =
113
+ /SELF_SIGNED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|UNABLE_TO_GET_ISSUER|DEPTH_ZERO|CERT_UNTRUSTED|UNABLE_TO_GET_LOCAL_ISSUER/
114
+
115
+ export const trustHint = 'the chain is not trusted; capture it with soap-sample "trust <side>"'
116
+
117
+ const describeTlsFailure = (code: string): string =>
118
+ unknownIssuer.test(code) ? `${code} (${trustHint})` : code
119
+
120
+ class ProxyRefused extends Error {
121
+ readonly status: number
122
+ constructor(status: number) {
123
+ super(`proxy refused the tunnel: HTTP ${status}`)
124
+ this.status = status
125
+ }
126
+ }
127
+
128
+ const flatHeaders = (headers: http.IncomingHttpHeaders): Record<string, string> =>
129
+ Object.fromEntries(
130
+ Object.entries(headers).flatMap(([name, value]) =>
131
+ value === undefined ? [] : [[name, Array.isArray(value) ? value.join(", ") : value]]
132
+ )
133
+ )
134
+
135
+ const bufferOf = (secret: Redacted.Redacted<Uint8Array> | undefined): Buffer | undefined =>
136
+ secret === undefined ? undefined : Buffer.from(Redacted.value(secret))
137
+
138
+ /** The CA list a connection verifies against: system roots plus the profile's, or the profile's alone. */
139
+ export const caListFor = (resolved: ResolvedTls | undefined): ReadonlyArray<string> | undefined => {
140
+ if (resolved?.ca === undefined) {
141
+ return undefined
142
+ }
143
+ const own = new TextDecoder().decode(Redacted.value(resolved.ca))
144
+ return resolved.trust === "ca-only" ? [own] : [...tls.rootCertificates, own]
145
+ }
146
+
147
+ const tlsOptionsOf = (resolved: ResolvedTls | undefined, host: string): tls.ConnectionOptions => {
148
+ const ca = caListFor(resolved)
149
+ return {
150
+ ...(resolved === undefined
151
+ ? {}
152
+ : {
153
+ cert: bufferOf(resolved.cert),
154
+ key: bufferOf(resolved.key),
155
+ pfx: bufferOf(resolved.pfx),
156
+ passphrase:
157
+ resolved.passphrase === undefined ? undefined : Redacted.value(resolved.passphrase)
158
+ }),
159
+ // A pinned chain may hold only what the server sent (a leaf signed by a
160
+ // CA it never presents): trust it as captured, not only self-signed roots.
161
+ ...(ca === undefined ? {} : { ca: [...ca], allowPartialTrustChain: true }),
162
+ servername: resolved?.servername ?? (net.isIP(host) === 0 ? host : undefined)
163
+ }
164
+ }
165
+
166
+ const portOf = (url: URL): number =>
167
+ url.port !== "" ? Number(url.port) : url.protocol === "https:" ? 443 : 80
168
+
169
+ /** Whether this request goes through the proxy: configured and the host not excluded. */
170
+ export const proxyFor = (url: URL, proxy: ResolvedProxy | undefined): ResolvedProxy | undefined =>
171
+ proxy === undefined || bypassesProxy(url.hostname, proxy.noProxy) ? undefined : proxy
172
+
173
+ /** An HTTP CONNECT tunnel to `target` through `proxy`; the raw socket, not yet TLS. */
174
+ const connectTunnel = (
175
+ proxy: ResolvedProxy,
176
+ target: URL,
177
+ signal: AbortSignal
178
+ ): Promise<net.Socket> =>
179
+ new Promise((resolve, reject) => {
180
+ const proxyUrl = new URL(proxy.url)
181
+ const headers: Record<string, string> = { host: `${target.hostname}:${portOf(target)}` }
182
+ if (proxy.authorization !== undefined) {
183
+ headers["proxy-authorization"] = Redacted.value(proxy.authorization)
184
+ }
185
+ const request = http.request({
186
+ host: proxyUrl.hostname,
187
+ port: portOf(proxyUrl),
188
+ method: "CONNECT",
189
+ path: `${target.hostname}:${portOf(target)}`,
190
+ headers,
191
+ signal
192
+ })
193
+ request.on("connect", (response, socket) => {
194
+ if (response.statusCode === 200) {
195
+ resolve(socket)
196
+ } else {
197
+ socket.destroy()
198
+ reject(new ProxyRefused(response.statusCode ?? 0))
199
+ }
200
+ })
201
+ request.on("error", reject)
202
+ request.end()
203
+ })
204
+
205
+ /** The socket a request runs on: direct, or through the tunnel; TLS-wrapped for https. */
206
+ const openSocket = async (
207
+ url: URL,
208
+ resolved: ResolvedTls | undefined,
209
+ proxy: ResolvedProxy | undefined,
210
+ signal: AbortSignal
211
+ ): Promise<net.Socket | undefined> => {
212
+ const via = proxyFor(url, proxy)
213
+ if (via === undefined) {
214
+ return undefined
215
+ }
216
+ const tunnel = await connectTunnel(via, url, signal)
217
+ if (url.protocol !== "https:") {
218
+ return tunnel
219
+ }
220
+ return new Promise((resolve, reject) => {
221
+ const secure = tls.connect({ ...tlsOptionsOf(resolved, url.hostname), socket: tunnel }, () =>
222
+ resolve(secure)
223
+ )
224
+ secure.on("error", reject)
225
+ })
226
+ }
227
+
228
+ const transportFailure = (shown: string, cause: unknown): TransportError => {
229
+ if (cause instanceof ProxyRefused) {
230
+ return new TransportError({ url: shown, reason: "proxy", detail: `HTTP ${cause.status}` })
231
+ }
232
+ const code = errorCode(cause)
233
+ return new TransportError({
234
+ url: shown,
235
+ reason: code === "ABORT_ERR" ? "aborted" : tlsCodes.test(code) ? "tls" : "network",
236
+ detail: tlsCodes.test(code) ? describeTlsFailure(code) : code
237
+ })
238
+ }
239
+
240
+ const withTimeout =
241
+ (shown: string, timeout: Duration.Duration) =>
242
+ <A>(effect: Effect.Effect<A, TransportError>): Effect.Effect<A, TransportError> =>
243
+ effect.pipe(
244
+ Effect.timeoutOrElse({
245
+ duration: timeout,
246
+ orElse: () =>
247
+ Effect.fail(
248
+ new TransportError({
249
+ url: shown,
250
+ reason: "timeout",
251
+ detail: `no response within ${Duration.format(timeout)}`
252
+ })
253
+ )
254
+ })
255
+ )
256
+
257
+ const parseTarget = (raw: string, needsTls: boolean): URL | TransportError => {
258
+ const shown = displayUrl(raw)
259
+ let url: URL
260
+ try {
261
+ url = new URL(raw)
262
+ } catch {
263
+ return new TransportError({ url: shown, reason: "scheme", detail: "invalid URL" })
264
+ }
265
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
266
+ return new TransportError({
267
+ url: shown,
268
+ reason: "scheme",
269
+ detail: `${url.protocol} is not http(s)`
270
+ })
271
+ }
272
+ if (url.protocol === "http:" && needsTls) {
273
+ return new TransportError({
274
+ url: shown,
275
+ reason: "scheme",
276
+ detail: "client TLS needs an https URL"
277
+ })
278
+ }
279
+ return url
280
+ }
281
+
282
+ const pemOf = (der: Buffer): string =>
283
+ `-----BEGIN CERTIFICATE-----\n${der
284
+ .toString("base64")
285
+ .replace(/(.{64})/g, "$1\n")
286
+ .trimEnd()}\n-----END CERTIFICATE-----\n`
287
+
288
+ const nameOf = (subject: tls.PeerCertificate["subject"]): string =>
289
+ Object.entries(subject ?? {})
290
+ .map(([key, value]) => `${key}=${Array.isArray(value) ? value.join("+") : String(value)}`)
291
+ .join(", ")
292
+
293
+ /** Walk `issuerCertificate` links, leaf first, stopping at the self-signed root. */
294
+ const chainOf = (leaf: tls.DetailedPeerCertificate): ReadonlyArray<PeerCertificate> => {
295
+ const out: Array<PeerCertificate> = []
296
+ const seen = new Set<string>()
297
+ let current: tls.DetailedPeerCertificate | undefined = leaf
298
+ while (current !== undefined && current.raw !== undefined && !seen.has(current.fingerprint256)) {
299
+ seen.add(current.fingerprint256)
300
+ out.push({
301
+ subject: nameOf(current.subject),
302
+ issuer: nameOf(current.issuer),
303
+ validFrom: current.valid_from,
304
+ validTo: current.valid_to,
305
+ fingerprint256: current.fingerprint256,
306
+ pem: pemOf(current.raw)
307
+ })
308
+ current = current.issuerCertificate === current ? undefined : current.issuerCertificate
309
+ }
310
+ return out
311
+ }
312
+
313
+ export const makeNodeSoapTransport = (): SoapTransportShape => ({
314
+ send: (request) => {
315
+ const shown = displayUrl(request.url)
316
+ const target = parseTarget(request.url, request.tls !== undefined)
317
+ if (target instanceof TransportError) {
318
+ return Effect.fail(target)
319
+ }
320
+ const url = target
321
+ const headers: Record<string, string> = { ...request.headers }
322
+ for (const [name, value] of request.secretHeaders) headers[name] = Redacted.value(value)
323
+ const body =
324
+ request.body === undefined ? undefined : Buffer.from(Redacted.value(request.body), "utf8")
325
+ if (body !== undefined) headers["content-length"] = String(body.length)
326
+
327
+ return Effect.tryPromise({
328
+ try: (signal) => {
329
+ const started = performance.now()
330
+ return openSocket(url, request.tls, request.proxy, signal).then(
331
+ (socket) =>
332
+ new Promise<SoapHttpResponse>((resolve, reject) => {
333
+ const options: https.RequestOptions = {
334
+ method: request.method,
335
+ headers,
336
+ signal,
337
+ ...(url.protocol === "https:" ? tlsOptionsOf(request.tls, url.hostname) : {}),
338
+ ...(socket === undefined ? {} : { createConnection: () => socket })
339
+ }
340
+ const handler = (response: http.IncomingMessage) => {
341
+ const chunks: Array<Buffer> = []
342
+ response.on("data", (chunk: Buffer) => chunks.push(chunk))
343
+ response.on("error", reject)
344
+ response.on("end", () =>
345
+ resolve({
346
+ status: response.statusCode ?? 0,
347
+ headers: flatHeaders(response.headers),
348
+ body: new Uint8Array(Buffer.concat(chunks)),
349
+ elapsedMs: Math.round(performance.now() - started)
350
+ })
351
+ )
352
+ }
353
+ const outgoing =
354
+ url.protocol === "https:"
355
+ ? https.request(url, options, handler)
356
+ : http.request(url, options, handler)
357
+ outgoing.on("error", reject)
358
+ if (body !== undefined) outgoing.write(body)
359
+ outgoing.end()
360
+ })
361
+ )
362
+ },
363
+ catch: (cause) => transportFailure(shown, cause)
364
+ }).pipe(withTimeout(shown, request.timeout))
365
+ },
366
+ peerChain: (raw, options) => {
367
+ const shown = displayUrl(raw)
368
+ const target = parseTarget(raw, false)
369
+ if (target instanceof TransportError) {
370
+ return Effect.fail(target)
371
+ }
372
+ const url = target
373
+ if (url.protocol !== "https:") {
374
+ return Effect.fail(
375
+ new TransportError({
376
+ url: shown,
377
+ reason: "scheme",
378
+ detail: "only an https endpoint has a chain"
379
+ })
380
+ )
381
+ }
382
+ return Effect.tryPromise({
383
+ try: (signal) => {
384
+ const via = proxyFor(url, options.proxy)
385
+ const tunnelled: Promise<net.Socket | undefined> =
386
+ via === undefined ? Promise.resolve(undefined) : connectTunnel(via, url, signal)
387
+ return tunnelled.then(
388
+ (tunnel) =>
389
+ new Promise<PeerChain>((resolve, reject) => {
390
+ const socket = tls.connect(
391
+ {
392
+ ...(tunnel === undefined
393
+ ? { host: url.hostname, port: portOf(url) }
394
+ : { socket: tunnel }),
395
+ servername:
396
+ options.servername ?? (net.isIP(url.hostname) === 0 ? url.hostname : undefined),
397
+ rejectUnauthorized: false
398
+ },
399
+ () => {
400
+ const leaf = socket.getPeerCertificate(true)
401
+ const chain = {
402
+ host: url.hostname,
403
+ certificates: chainOf(leaf),
404
+ trustedBySystem: socket.authorized,
405
+ authorizationError:
406
+ socket.authorizationError === undefined || socket.authorizationError === null
407
+ ? undefined
408
+ : String(socket.authorizationError)
409
+ }
410
+ socket.end()
411
+ resolve(chain)
412
+ }
413
+ )
414
+ socket.on("error", reject)
415
+ signal.addEventListener("abort", () => socket.destroy())
416
+ })
417
+ )
418
+ },
419
+ catch: (cause) => transportFailure(shown, cause)
420
+ }).pipe(withTimeout(shown, options.timeout))
421
+ }
422
+ })
423
+
424
+ /**
425
+ * A scripted transport for tests: each request goes to `respond`, and every
426
+ * request is recorded (secrets still redacted) for assertions. `chain`
427
+ * answers `peerChain`; by default an endpoint presents nothing.
428
+ */
429
+ export const makeFakeSoapTransport = (
430
+ respond: (request: SoapHttpRequest) => Effect.Effect<SoapHttpResponse, TransportError>,
431
+ chain: (url: string) => Effect.Effect<PeerChain, TransportError> = (url) =>
432
+ Effect.succeed({
433
+ host: new URL(url).hostname,
434
+ certificates: [],
435
+ trustedBySystem: true,
436
+ authorizationError: undefined
437
+ })
438
+ ) =>
439
+ Effect.map(Ref.make<ReadonlyArray<SoapHttpRequest>>([]), (log) => ({
440
+ transport: {
441
+ send: (request: SoapHttpRequest) =>
442
+ Effect.andThen(
443
+ Ref.update(log, (all) => [...all, request]),
444
+ respond(request)
445
+ ),
446
+ peerChain: (url: string) => chain(url)
447
+ } satisfies SoapTransportShape,
448
+ requests: Ref.get(log)
449
+ }))
450
+
451
+ export const xmlResponse = (xml: string, status = 200): SoapHttpResponse => ({
452
+ status,
453
+ headers: { "content-type": "text/xml; charset=utf-8" },
454
+ body: new TextEncoder().encode(xml),
455
+ elapsedMs: 5
456
+ })
@@ -0,0 +1,10 @@
1
+ import { diff } from "./Diff.ts"
2
+ import { httpCall } from "./HttpCall.ts"
3
+ import { jsonValidate } from "./JsonValidate.ts"
4
+ import type { ToolShape } from "./Tool.ts"
5
+
6
+ /** The tools every install has, before any kit or pack adds its own. */
7
+ export const builtinTools: ReadonlyArray<ToolShape> = [jsonValidate, diff, httpCall]
8
+
9
+ export const builtinTool = (name: string): ToolShape | undefined =>
10
+ builtinTools.find((tool) => tool.name === name)
@@ -0,0 +1,61 @@
1
+ import * as Effect from "effect/Effect"
2
+ import * as Schema from "effect/Schema"
3
+ import { defineTool, parseJsonDocument, readToolFile, report } from "./Tool.ts"
4
+ import { diffJson } from "./TreeDiff.ts"
5
+
6
+ const name = "diff"
7
+
8
+ const Input = Schema.Struct({
9
+ expected: Schema.String,
10
+ actual: Schema.String,
11
+ ordering: Schema.Literals(["ordered", "per-key", "unordered"]),
12
+ ignore: Schema.String
13
+ })
14
+
15
+ /** Structural compare of two JSON documents, with the pack's ordering and ignore rules. */
16
+ export const diff = defineTool({
17
+ name,
18
+ purpose:
19
+ "Compare two JSON documents structurally and list every missing, unexpected or changed value",
20
+ args: {
21
+ expected: { description: "Path of the expected JSON document", kind: "path", required: true },
22
+ actual: { description: "Path of the actual JSON document", kind: "path", required: true },
23
+ ordering: {
24
+ description:
25
+ "How arrays are matched: ordered (by position), per-key (by id/key/name/code), unordered (as a multiset)",
26
+ kind: "string",
27
+ default: "ordered"
28
+ },
29
+ ignore: {
30
+ description:
31
+ "Comma-separated dot paths to skip, * matches one segment (meta.requestId, items.*.updatedAt)",
32
+ kind: "string",
33
+ default: ""
34
+ }
35
+ },
36
+ input: Input,
37
+ run: (input) =>
38
+ Effect.gen(function* () {
39
+ const expected = yield* parseJsonDocument(
40
+ name,
41
+ input.expected,
42
+ yield* readToolFile(name, input.expected)
43
+ )
44
+ const actual = yield* parseJsonDocument(
45
+ name,
46
+ input.actual,
47
+ yield* readToolFile(name, input.actual)
48
+ )
49
+ const ignore = input.ignore
50
+ .split(",")
51
+ .map((item) => item.trim())
52
+ .filter((item) => item.length > 0)
53
+ const issues = diffJson(expected, actual, { ordering: input.ordering, ignore }).map(
54
+ (issue) => ({
55
+ path: issue.path,
56
+ detail: `${issue.kind}: ${issue.detail}`
57
+ })
58
+ )
59
+ return report(name, issues, `${input.actual} matches ${input.expected}`)
60
+ })
61
+ })
@@ -0,0 +1,124 @@
1
+ import * as Duration from "effect/Duration"
2
+ import * as Effect from "effect/Effect"
3
+ import * as Redacted from "effect/Redacted"
4
+ import * as Schema from "effect/Schema"
5
+ import { redactText } from "@llm4ts/core/observability/Redaction"
6
+ import { nodeSecretSource, resolveSide } from "../endpoint/Auth.ts"
7
+ import { loadEndpointProfile } from "../endpoint/Endpoints.ts"
8
+ import { SoapTransport, displayUrl } from "../endpoint/Transport.ts"
9
+ import { PlainFileStore } from "../Persistence.ts"
10
+ import { ToolContext, ToolError, defineTool, report } from "./Tool.ts"
11
+
12
+ const name = "http-call"
13
+
14
+ const Input = Schema.Struct({
15
+ endpoint: Schema.String,
16
+ env: Schema.optionalKey(Schema.String),
17
+ path: Schema.String,
18
+ expect: Schema.Int,
19
+ timeout: Schema.Int
20
+ })
21
+
22
+ const previewChars = 2_000
23
+
24
+ /**
25
+ * A GET against a named endpoint (ADR 0048): the profile supplies the base
26
+ * URL, auth, TLS and proxy; the tool adds a path, checks the status and
27
+ * returns a redacted preview of the body. Read-and-probe only: no other
28
+ * method, no request body.
29
+ */
30
+ export const httpCall = defineTool({
31
+ name,
32
+ purpose:
33
+ "GET a path of a named endpoint (.llm4ts/endpoints/<name>/auth.<env>.json) and report the status and a redacted body preview",
34
+ args: {
35
+ endpoint: {
36
+ description: "Endpoint name under .llm4ts/endpoints/",
37
+ kind: "string",
38
+ required: true
39
+ },
40
+ env: {
41
+ description: "Environment whose profile to use (dev, test, uat); default auth.json",
42
+ kind: "string"
43
+ },
44
+ path: {
45
+ description: "Path and query appended to the endpoint URL",
46
+ kind: "string",
47
+ default: "/"
48
+ },
49
+ expect: {
50
+ description: "The exact status expected; 0 accepts any 2xx",
51
+ kind: "integer",
52
+ default: "0"
53
+ },
54
+ timeout: { description: "Seconds to wait for the response", kind: "integer", default: "30" }
55
+ },
56
+ input: Input,
57
+ run: (input) =>
58
+ Effect.gen(function* () {
59
+ const context = yield* ToolContext
60
+ const files = yield* PlainFileStore
61
+ const transport = yield* SoapTransport
62
+ const fail = (message: string) => new ToolError({ tool: name, message })
63
+ const profile = yield* loadEndpointProfile(
64
+ files,
65
+ context.projectRoot,
66
+ input.endpoint,
67
+ input.env
68
+ ).pipe(Effect.mapError((error) => fail(error.message)))
69
+ if (profile.endpoint === undefined) {
70
+ return yield* fail(`endpoint ${input.endpoint} has no "endpoint" URL in its profile`)
71
+ }
72
+ const url = yield* Effect.try({
73
+ try: () => new URL(input.path, profile.endpoint).toString(),
74
+ catch: () => fail(`cannot resolve path '${input.path}' against ${profile.endpoint}`)
75
+ })
76
+ const side = yield* resolveSide(
77
+ nodeSecretSource(context.environment),
78
+ profile.call ?? profile.fetch
79
+ ).pipe(Effect.mapError((error) => fail(error.message)))
80
+ const timeout = Duration.seconds(
81
+ input.timeout > 0 ? input.timeout : (profile.timeoutSeconds ?? 30)
82
+ )
83
+ const response = yield* transport
84
+ .send({
85
+ method: "GET",
86
+ url,
87
+ headers: { accept: "application/json, text/*, */*" },
88
+ secretHeaders: side.headers,
89
+ ...(side.tls === undefined ? {} : { tls: side.tls }),
90
+ ...(side.proxy === undefined ? {} : { proxy: side.proxy }),
91
+ timeout
92
+ })
93
+ .pipe(
94
+ Effect.mapError((error) => fail(`${displayUrl(url)}: ${error.reason}: ${error.detail}`))
95
+ )
96
+ const secrets = side.headers.map(([, value]) => Redacted.value(value))
97
+ const body = new TextDecoder("utf8", { fatal: false }).decode(response.body)
98
+ const preview = redactText(body.slice(0, previewChars), { secrets })
99
+ const expected =
100
+ input.expect > 0
101
+ ? response.status === input.expect
102
+ : response.status >= 200 && response.status < 300
103
+ const issues = expected
104
+ ? []
105
+ : [
106
+ {
107
+ path: displayUrl(url),
108
+ detail: `expected ${input.expect > 0 ? `status ${input.expect}` : "a 2xx status"}, got ${response.status}`
109
+ }
110
+ ]
111
+ return report(
112
+ name,
113
+ issues,
114
+ `${displayUrl(url)} answered ${response.status} in ${response.elapsedMs} ms`,
115
+ {
116
+ status: response.status,
117
+ elapsedMs: response.elapsedMs,
118
+ contentType: response.headers["content-type"] ?? null,
119
+ bodyChars: body.length,
120
+ bodyPreview: preview
121
+ }
122
+ )
123
+ })
124
+ })