@llm4ts/flow 3.0.0 → 3.2.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 (61) 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/Pack.d.ts +11 -0
  6. package/dist/Pack.d.ts.map +1 -1
  7. package/dist/Pack.js +2 -0
  8. package/dist/Pack.js.map +1 -1
  9. package/dist/endpoint/Auth.d.ts +194 -0
  10. package/dist/endpoint/Auth.d.ts.map +1 -0
  11. package/dist/endpoint/Auth.js +302 -0
  12. package/dist/endpoint/Auth.js.map +1 -0
  13. package/dist/endpoint/Endpoints.d.ts +21 -0
  14. package/dist/endpoint/Endpoints.d.ts.map +1 -0
  15. package/dist/endpoint/Endpoints.js +40 -0
  16. package/dist/endpoint/Endpoints.js.map +1 -0
  17. package/dist/endpoint/Transport.d.ts +90 -0
  18. package/dist/endpoint/Transport.d.ts.map +1 -0
  19. package/dist/endpoint/Transport.js +306 -0
  20. package/dist/endpoint/Transport.js.map +1 -0
  21. package/dist/tools/Builtin.d.ts +5 -0
  22. package/dist/tools/Builtin.d.ts.map +1 -0
  23. package/dist/tools/Builtin.js +7 -0
  24. package/dist/tools/Builtin.js.map +1 -0
  25. package/dist/tools/Diff.d.ts +8 -0
  26. package/dist/tools/Diff.d.ts.map +1 -0
  27. package/dist/tools/Diff.js +45 -0
  28. package/dist/tools/Diff.js.map +1 -0
  29. package/dist/tools/HttpCall.d.ts +14 -0
  30. package/dist/tools/HttpCall.d.ts.map +1 -0
  31. package/dist/tools/HttpCall.js +134 -0
  32. package/dist/tools/HttpCall.js.map +1 -0
  33. package/dist/tools/JsonSchemaCheck.d.ts +36 -0
  34. package/dist/tools/JsonSchemaCheck.d.ts.map +1 -0
  35. package/dist/tools/JsonSchemaCheck.js +342 -0
  36. package/dist/tools/JsonSchemaCheck.js.map +1 -0
  37. package/dist/tools/JsonValidate.d.ts +11 -0
  38. package/dist/tools/JsonValidate.d.ts.map +1 -0
  39. package/dist/tools/JsonValidate.js +84 -0
  40. package/dist/tools/JsonValidate.js.map +1 -0
  41. package/dist/tools/Tool.d.ts +126 -0
  42. package/dist/tools/Tool.d.ts.map +1 -0
  43. package/dist/tools/Tool.js +218 -0
  44. package/dist/tools/Tool.js.map +1 -0
  45. package/dist/tools/TreeDiff.d.ts +42 -0
  46. package/dist/tools/TreeDiff.d.ts.map +1 -0
  47. package/dist/tools/TreeDiff.js +276 -0
  48. package/dist/tools/TreeDiff.js.map +1 -0
  49. package/package.json +12 -2
  50. package/src/Activity.ts +22 -0
  51. package/src/Pack.ts +16 -0
  52. package/src/endpoint/Auth.ts +446 -0
  53. package/src/endpoint/Endpoints.ts +60 -0
  54. package/src/endpoint/Transport.ts +456 -0
  55. package/src/tools/Builtin.ts +10 -0
  56. package/src/tools/Diff.ts +61 -0
  57. package/src/tools/HttpCall.ts +160 -0
  58. package/src/tools/JsonSchemaCheck.ts +457 -0
  59. package/src/tools/JsonValidate.ts +106 -0
  60. package/src/tools/Tool.ts +351 -0
  61. package/src/tools/TreeDiff.ts +386 -0
package/src/Activity.ts CHANGED
@@ -139,6 +139,7 @@ export type ToolCategory =
139
139
  | "build"
140
140
  | "install"
141
141
  | "git"
142
+ | "script"
142
143
  | "delegate"
143
144
  | "other"
144
145
 
@@ -154,6 +155,24 @@ const exploreTools =
154
155
  const editTools = /^(edit|write|write_file|replace|multiedit|apply_patch|create|str_replace)$/iu
155
156
  const shellTools = /^(bash|shell|run_shell_command|exec|command_execution)$/iu
156
157
 
158
+ /**
159
+ * An ad-hoc script the coder improvised instead of using a tool the pack
160
+ * provides: an interpreter fed inline code, a heredoc, a redirect into a
161
+ * script file, or an interpreter run on a scratch file. Checked before the
162
+ * test/build/install/git/explore sorting so `python3 - <<EOF` and a heredoc
163
+ * into `scratch.test.ts` both count as script.
164
+ */
165
+ const scriptPatterns: ReadonlyArray<RegExp> = [
166
+ // An interpreter run with inline code: `python3 -c …`, `node -e …`, `python3 -`.
167
+ /^(python3?|node|ruby|perl|php|deno|bun|tsx|ts-node)\s+(-c|-e|--eval|-p|-)(\s|$)/u,
168
+ // A heredoc: `<<EOF`, `<<-EOF`, `<<'EOF'`, `<<"EOF"` (not a `<<<` here-string).
169
+ /(?<!<)<<(?!<)-?\s*(?:'[^']+'|"[^"]+"|\w+)/u,
170
+ // A redirect into a script file: `cat > scratch.py`, `tee debug.js`.
171
+ /(?:>>?|\btee(?:\s+-a)?)\s*\S+\.(?:py|js|mjs|cjs|ts|sh|rb)(?=\s|$)/u,
172
+ // An interpreter run on a scratch file: `/tmp/x.py`, `scratch.js`, `tmp/debug.ts`.
173
+ /^(python3?|node|tsx|bun)\s+(\/tmp\/|.*\b(scratch|tmp|debug)[^\s]*\.(py|js|mjs|ts))/u
174
+ ]
175
+
157
176
  /**
158
177
  * What kind of work a coder's tool call is, for "where does the time go":
159
178
  * reading the code, editing it, or a shell command sorted by what it runs.
@@ -171,6 +190,9 @@ export const toolCategory = (tool: string, args: string): ToolCategory => {
171
190
  }
172
191
  // `cd <worktree> && …`: the command is what follows.
173
192
  const command = args.replace(/^\s*cd\s+\S+\s*&&\s*/u, "").trim()
193
+ if (scriptPatterns.some((pattern) => pattern.test(command))) {
194
+ return "script"
195
+ }
174
196
  if (/\b(test|vitest|jest|pytest|mocha|playwright)\b/u.test(command)) {
175
197
  return "test"
176
198
  }
package/src/Pack.ts CHANGED
@@ -20,6 +20,12 @@ export class ComparisonPolicy extends Schema.Class<ComparisonPolicy>("Comparison
20
20
  ignore: Schema.ReadonlySet(Schema.String)
21
21
  }) {}
22
22
 
23
+ export interface ToolPreset {
24
+ readonly name: string
25
+ /** The catalog tool, then its arguments, as written. */
26
+ readonly command: ReadonlyArray<string>
27
+ }
28
+
23
29
  export interface Pack {
24
30
  readonly name: string
25
31
  readonly source: string
@@ -42,6 +48,12 @@ export interface Pack {
42
48
  // worktree) before its gates run; absent, the target needs no setup.
43
49
  // Optional so a hand-built Pack still type-checks.
44
50
  readonly setup?: ReadonlyArray<string>
51
+ /**
52
+ * `## Tools` presets (ADR 0048): `- name: tool --flag value`, a pack-level
53
+ * name over a catalog tool that a story sees as the same command every
54
+ * run (`llm4ts tool <name>`). Optional so a hand-built Pack still type-checks.
55
+ */
56
+ readonly tools?: ReadonlyArray<ToolPreset>
45
57
  readonly equivalence: ComparisonPolicy
46
58
  readonly judgeDimensions: ReadonlyArray<Dimension>
47
59
  readonly coverage: ReadonlyArray<CoverageRule>
@@ -295,6 +307,9 @@ export const loadPack = Effect.fn("@llm4ts/flow/Pack.load")(function* (
295
307
  ? "PerKey"
296
308
  : "Ordered"
297
309
  const gateList = gateEntries.map(([, command]) => command.split(/\s+/))
310
+ const tools = namedEntries(section(manifest.sections, "Tools")).map(
311
+ ([name, command]): ToolPreset => ({ name, command: command.split(/\s+/) })
312
+ )
298
313
  const gates = Object.fromEntries(
299
314
  gateEntries.map(([name, command]) => [name, command.split(/\s+/)])
300
315
  )
@@ -446,6 +461,7 @@ export const loadPack = Effect.fn("@llm4ts/flow/Pack.load")(function* (
446
461
  featuresDir: fields["features-dir"] ?? "features",
447
462
  gates,
448
463
  gateList,
464
+ ...(tools.length === 0 ? {} : { tools }),
449
465
  replay: fields.replay?.split(/\s+/),
450
466
  ...(fields.setup === undefined || fields.setup.trim().length === 0
451
467
  ? {}
@@ -0,0 +1,446 @@
1
+ import { readFile, readdir } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import * as Effect from "effect/Effect"
4
+ import * as Redacted from "effect/Redacted"
5
+ import * as Schema from "effect/Schema"
6
+
7
+ // The auth profile, `.llm4ts/soap/<service>/auth.json` (gitignored). It holds
8
+ // references only — `env:NAME` or `file:path` — never a secret value; a
9
+ // literal where a secret belongs is a decode error. References are resolved
10
+ // at call time into `Redacted` values that live inside the transport; no
11
+ // secret reaches arguments, logs, traces, persisted files, or error
12
+ // messages (errors name the reference, never its value).
13
+
14
+ export const Environment = Schema.Literals(["dev", "test", "uat"])
15
+ export type Environment = typeof Environment.Type
16
+
17
+ /** `env:NAME` or `file:path`. */
18
+ export const SecretRef = Schema.String.check(
19
+ Schema.isPattern(/^(env:[A-Za-z_][A-Za-z0-9_]*|file:.+)$/, {
20
+ message: "must be a reference, env:NAME or file:path — never the secret itself"
21
+ })
22
+ )
23
+
24
+ /** A username may be written literally or referenced. */
25
+ export const Principal = Schema.String
26
+
27
+ export class BasicAuth extends Schema.Class<BasicAuth>("BasicAuth")({
28
+ scheme: Schema.Literal("basic"),
29
+ user: Principal,
30
+ password: SecretRef
31
+ }) {}
32
+
33
+ export class BearerAuth extends Schema.Class<BearerAuth>("BearerAuth")({
34
+ scheme: Schema.Literal("bearer"),
35
+ token: SecretRef
36
+ }) {}
37
+
38
+ export class NoAuth extends Schema.Class<NoAuth>("NoAuth")({
39
+ scheme: Schema.Literal("none")
40
+ }) {}
41
+
42
+ export const HttpAuth = Schema.Union([NoAuth, BasicAuth, BearerAuth])
43
+ export type HttpAuth = typeof HttpAuth.Type
44
+
45
+ /** How the profile's CA material combines with Node's system roots. */
46
+ export const TlsTrust = Schema.Literals(["system+ca", "ca-only"])
47
+ export type TlsTrust = typeof TlsTrust.Type
48
+
49
+ /**
50
+ * Client TLS: PEM cert+key, or a PKCS#12 bundle; CA material as a PEM file
51
+ * (`ca`) and/or a directory of PEMs (`caDir`), added to the system roots
52
+ * unless `trust` is `ca-only`; `servername` for a host behind a front door.
53
+ */
54
+ export class TlsConfig extends Schema.Class<TlsConfig>("TlsConfig")({
55
+ cert: Schema.optionalKey(SecretRef),
56
+ key: Schema.optionalKey(SecretRef),
57
+ pfx: Schema.optionalKey(SecretRef),
58
+ passphrase: Schema.optionalKey(SecretRef),
59
+ ca: Schema.optionalKey(SecretRef),
60
+ caDir: Schema.optionalKey(Schema.String),
61
+ trust: Schema.optionalKey(TlsTrust),
62
+ servername: Schema.optionalKey(Schema.String)
63
+ }) {}
64
+
65
+ const ProxyUrl = Schema.String.check(
66
+ Schema.isPattern(/^https?:\/\/[^/?#@]+\/?$/i, {
67
+ message: "an http(s) proxy origin without credentials or path; credentials go in auth"
68
+ })
69
+ )
70
+
71
+ /**
72
+ * An explicit HTTP CONNECT proxy for one side, with the hosts that bypass
73
+ * it (`*.suffix` wildcards). Environment proxy variables are never read.
74
+ */
75
+ export class ProxyConfig extends Schema.Class<ProxyConfig>("ProxyConfig")({
76
+ url: ProxyUrl,
77
+ noProxy: Schema.optionalKey(Schema.Array(Schema.String)),
78
+ auth: Schema.optionalKey(BasicAuth)
79
+ }) {}
80
+
81
+ export const ProxySetting = Schema.Union([Schema.Literal("none"), ProxyConfig])
82
+ export type ProxySetting = typeof ProxySetting.Type
83
+
84
+ export class HttpSide extends Schema.Class<HttpSide>("HttpSide")({
85
+ auth: Schema.optionalKey(HttpAuth),
86
+ tls: Schema.optionalKey(TlsConfig),
87
+ proxy: Schema.optionalKey(ProxySetting)
88
+ }) {}
89
+
90
+ /** The credential the STS request template is filled with. */
91
+ export class StsCredential extends Schema.Class<StsCredential>("StsCredential")({
92
+ user: Principal,
93
+ password: SecretRef
94
+ }) {}
95
+
96
+ /**
97
+ * A SAML bearer token from an STS: the template under the service folder
98
+ * is filled and posted to `endpoint` with this side's auth, TLS and proxy;
99
+ * the first element named `token.element` in the answer is carried, bytes
100
+ * unchanged, in every call's WS-Security header.
101
+ */
102
+ export class StsConfig extends Schema.Class<StsConfig>("StsConfig")({
103
+ endpoint: Schema.String.check(
104
+ Schema.isPattern(/^https?:\/\/[^/?#@]+(?:[/?#][^@]*)?$/i, {
105
+ message: "an http(s) URL without credentials; secrets go in references"
106
+ })
107
+ ),
108
+ soapVersion: Schema.optionalKey(Schema.Literals(["1.1", "1.2"])),
109
+ /** Relative to the service folder; `sts init` writes the default. */
110
+ template: Schema.optionalKey(Schema.String),
111
+ auth: StsCredential,
112
+ appliesTo: Schema.optionalKey(Schema.String),
113
+ token: Schema.optionalKey(Schema.Struct({ element: Schema.optionalKey(Schema.String) })),
114
+ renewBeforeSeconds: Schema.optionalKey(Schema.Int),
115
+ timestamp: Schema.optionalKey(Schema.Boolean),
116
+ tls: Schema.optionalKey(TlsConfig),
117
+ proxy: Schema.optionalKey(ProxySetting),
118
+ timeoutSeconds: Schema.optionalKey(Schema.Int)
119
+ }) {}
120
+
121
+ export const defaultStsTemplate = "sts.request.xml"
122
+ export const defaultTokenElement = "Assertion"
123
+
124
+ export class UsernameToken extends Schema.Class<UsernameToken>("UsernameToken")({
125
+ user: Principal,
126
+ password: SecretRef,
127
+ passwordType: Schema.Literals(["text", "digest"])
128
+ }) {}
129
+
130
+ export const MutatingPolicy = Schema.Literals(["confirm", "flag", "deny"])
131
+ export type MutatingPolicy = typeof MutatingPolicy.Type
132
+
133
+ export class MutatingPolicies extends Schema.Class<MutatingPolicies>("MutatingPolicies")({
134
+ dev: Schema.optionalKey(MutatingPolicy),
135
+ test: Schema.optionalKey(MutatingPolicy),
136
+ uat: Schema.optionalKey(MutatingPolicy)
137
+ }) {}
138
+
139
+ export class AuthProfile extends Schema.Class<AuthProfile>("AuthProfile")({
140
+ environment: Environment,
141
+ /** Overrides the WSDL's address for calls (the WSDL often names another environment). */
142
+ endpoint: Schema.optionalKey(
143
+ Schema.String.check(
144
+ Schema.isPattern(/^https?:\/\/[^/?#@]+(?:[/?#][^@]*)?$/i, {
145
+ message: "an http(s) URL without credentials; secrets go in references"
146
+ })
147
+ )
148
+ ),
149
+ /** Fetching the WSDL and its schemas. */
150
+ fetch: Schema.optionalKey(HttpSide),
151
+ /** Calling operations. */
152
+ call: Schema.optionalKey(HttpSide),
153
+ wsSecurity: Schema.optionalKey(UsernameToken),
154
+ /** A SAML bearer token from an STS, carried by every call. */
155
+ sts: Schema.optionalKey(StsConfig),
156
+ mutating: Schema.optionalKey(MutatingPolicies),
157
+ timeoutSeconds: Schema.optionalKey(Schema.Int)
158
+ }) {}
159
+
160
+ /** `auth.json`, or `auth.<env>.json` when an environment is selected. */
161
+ export const profileFileName = (env: string | undefined): string =>
162
+ env === undefined || env.trim() === "" ? "auth.json" : `auth.${env.trim()}.json`
163
+
164
+ export const defaultMutatingPolicy = (environment: Environment): MutatingPolicy =>
165
+ environment === "dev" ? "confirm" : "flag"
166
+
167
+ export const mutatingPolicy = (profile: AuthProfile): MutatingPolicy =>
168
+ profile.mutating?.[profile.environment] ?? defaultMutatingPolicy(profile.environment)
169
+
170
+ export class AuthProfileError extends Schema.TaggedError<AuthProfileError>()("AuthProfileError", {
171
+ /** The reference or field involved; never a secret value. */
172
+ subject: Schema.String,
173
+ detail: Schema.String
174
+ }) {
175
+ get message(): string {
176
+ return `auth profile: ${this.subject}: ${this.detail}`
177
+ }
178
+ }
179
+
180
+ export const decodeAuthProfile = (
181
+ text: string,
182
+ file = "auth.json"
183
+ ): Effect.Effect<AuthProfile, AuthProfileError> =>
184
+ Schema.decodeUnknownEffect(Schema.fromJsonString(AuthProfile))(text).pipe(
185
+ Effect.mapError(
186
+ (error) =>
187
+ // Schema issues quote the offending input; a mistyped secret could be
188
+ // in it, so only the paths of the issue are kept.
189
+ new AuthProfileError({
190
+ subject: file,
191
+ detail: `invalid profile (${issuePaths(error.message)})`
192
+ })
193
+ )
194
+ )
195
+
196
+ /** Keep only the `at ["a"]["b"]` locations of a schema message, dropping any quoted value. */
197
+ const issuePaths = (message: string): string => {
198
+ const paths = [...message.matchAll(/at ((?:\[[^\]]*\])+)/g)].map((match) =>
199
+ [...(match[1] ?? "").matchAll(/\["?([^"\]]*)"?\]/g)].map((part) => part[1] ?? "").join(".")
200
+ )
201
+ return paths.length === 0
202
+ ? "see the soap-ace README for the profile shape"
203
+ : `at ${[...new Set(paths)].join(", ")}; secrets must be env:NAME or file:path references`
204
+ }
205
+
206
+ // ---------------------------------------------------------------------------
207
+ // Resolution
208
+
209
+ export interface SecretSource {
210
+ readonly environment: Readonly<Record<string, string | undefined>>
211
+ readonly readFile: (path: string) => Effect.Effect<Uint8Array, AuthProfileError>
212
+ /** The `.pem`/`.crt` files of a directory, concatenated; absent sources cannot use `caDir`. */
213
+ readonly readPemDirectory?: (path: string) => Effect.Effect<Uint8Array, AuthProfileError>
214
+ }
215
+
216
+ export const resolveSecret = (
217
+ source: SecretSource,
218
+ reference: string
219
+ ): Effect.Effect<Redacted.Redacted<Uint8Array>, AuthProfileError> => {
220
+ if (reference.startsWith("env:")) {
221
+ const name = reference.slice(4)
222
+ const value = source.environment[name]
223
+ return value === undefined || value === ""
224
+ ? Effect.fail(new AuthProfileError({ subject: reference, detail: "variable is not set" }))
225
+ : Effect.succeed(Redacted.make(new TextEncoder().encode(value)))
226
+ }
227
+ if (reference.startsWith("file:")) {
228
+ return Effect.map(source.readFile(reference.slice(5)), (bytes) => Redacted.make(bytes))
229
+ }
230
+ return Effect.fail(new AuthProfileError({ subject: "reference", detail: "not env: or file:" }))
231
+ }
232
+
233
+ export const resolveText = (
234
+ source: SecretSource,
235
+ reference: string
236
+ ): Effect.Effect<Redacted.Redacted<string>, AuthProfileError> =>
237
+ Effect.map(resolveSecret(source, reference), (secret) =>
238
+ Redacted.make(new TextDecoder().decode(Redacted.value(secret)).replace(/\r?\n$/, ""))
239
+ )
240
+
241
+ /** A principal: resolved when it is a reference, else the literal. */
242
+ export const resolvePrincipal = (
243
+ source: SecretSource,
244
+ value: string
245
+ ): Effect.Effect<string, AuthProfileError> =>
246
+ value.startsWith("env:") || value.startsWith("file:")
247
+ ? Effect.map(resolveText(source, value), Redacted.value)
248
+ : Effect.succeed(value)
249
+
250
+ export interface ResolvedTls {
251
+ readonly cert?: Redacted.Redacted<Uint8Array>
252
+ readonly key?: Redacted.Redacted<Uint8Array>
253
+ readonly pfx?: Redacted.Redacted<Uint8Array>
254
+ readonly passphrase?: Redacted.Redacted<string>
255
+ /** The profile's CA material, file and directory concatenated. */
256
+ readonly ca?: Redacted.Redacted<Uint8Array>
257
+ readonly trust?: TlsTrust
258
+ readonly servername?: string
259
+ }
260
+
261
+ export interface ResolvedProxy {
262
+ readonly url: string
263
+ readonly noProxy: ReadonlyArray<string>
264
+ /** `proxy-authorization`, when the proxy wants one. */
265
+ readonly authorization?: Redacted.Redacted<string>
266
+ }
267
+
268
+ export interface ResolvedSide {
269
+ /** Header name → value to send; values are secrets. */
270
+ readonly headers: ReadonlyArray<readonly [string, Redacted.Redacted<string>]>
271
+ readonly tls: ResolvedTls | undefined
272
+ readonly proxy: ResolvedProxy | undefined
273
+ }
274
+
275
+ const optionalSecret = <K extends string>(
276
+ source: SecretSource,
277
+ name: K,
278
+ reference: string | undefined
279
+ ) =>
280
+ reference === undefined
281
+ ? Effect.succeed({})
282
+ : Effect.map(resolveSecret(source, reference), (value) => ({ [name]: value }))
283
+
284
+ export const resolveTls = (
285
+ source: SecretSource,
286
+ tls: TlsConfig | undefined
287
+ ): Effect.Effect<ResolvedTls | undefined, AuthProfileError> =>
288
+ tls === undefined
289
+ ? Effect.succeed(undefined)
290
+ : Effect.gen(function* () {
291
+ if (tls.pfx !== undefined && (tls.cert !== undefined || tls.key !== undefined)) {
292
+ return yield* new AuthProfileError({
293
+ subject: "tls",
294
+ detail: "use either pfx or cert+key, not both"
295
+ })
296
+ }
297
+ if ((tls.cert === undefined) !== (tls.key === undefined)) {
298
+ return yield* new AuthProfileError({
299
+ subject: "tls",
300
+ detail: "cert and key go together"
301
+ })
302
+ }
303
+ const cert = yield* optionalSecret(source, "cert", tls.cert)
304
+ const key = yield* optionalSecret(source, "key", tls.key)
305
+ const pfx = yield* optionalSecret(source, "pfx", tls.pfx)
306
+ const caFile =
307
+ tls.ca === undefined ? undefined : Redacted.value(yield* resolveSecret(source, tls.ca))
308
+ let caDir: Uint8Array | undefined
309
+ if (tls.caDir !== undefined) {
310
+ if (source.readPemDirectory === undefined) {
311
+ return yield* new AuthProfileError({
312
+ subject: "tls.caDir",
313
+ detail: "this source cannot read a directory"
314
+ })
315
+ }
316
+ caDir = yield* source.readPemDirectory(tls.caDir)
317
+ }
318
+ const ca =
319
+ caFile === undefined && caDir === undefined
320
+ ? {}
321
+ : { ca: Redacted.make(concatPem(caFile, caDir)) }
322
+ const passphrase =
323
+ tls.passphrase === undefined
324
+ ? {}
325
+ : { passphrase: yield* resolveText(source, tls.passphrase) }
326
+ return {
327
+ ...cert,
328
+ ...key,
329
+ ...pfx,
330
+ ...ca,
331
+ ...passphrase,
332
+ ...(tls.trust === undefined ? {} : { trust: tls.trust }),
333
+ ...(tls.servername === undefined ? {} : { servername: tls.servername })
334
+ }
335
+ })
336
+
337
+ const concatPem = (...parts: ReadonlyArray<Uint8Array | undefined>): Uint8Array => {
338
+ const present = parts.filter((part): part is Uint8Array => part !== undefined)
339
+ const joined = present.map((part) => new TextDecoder().decode(part).trimEnd()).join("\n")
340
+ return new TextEncoder().encode(`${joined}\n`)
341
+ }
342
+
343
+ /** Whether a host bypasses the proxy: exact match, or `*.suffix` / `.suffix`. */
344
+ export const bypassesProxy = (host: string, noProxy: ReadonlyArray<string>): boolean => {
345
+ const lower = host.toLowerCase()
346
+ return noProxy.some((entry) => {
347
+ const pattern = entry.trim().toLowerCase()
348
+ if (pattern === "") return false
349
+ if (pattern === "*") return true
350
+ if (pattern.startsWith("*.") || pattern.startsWith(".")) {
351
+ const suffix = pattern.replace(/^\*/, "")
352
+ return lower.endsWith(suffix) && lower.length > suffix.length
353
+ }
354
+ return lower === pattern
355
+ })
356
+ }
357
+
358
+ export const resolveProxy = (
359
+ source: SecretSource,
360
+ proxy: ProxySetting | undefined
361
+ ): Effect.Effect<ResolvedProxy | undefined, AuthProfileError> =>
362
+ proxy === undefined || proxy === "none"
363
+ ? Effect.succeed(undefined)
364
+ : Effect.gen(function* () {
365
+ const authorization =
366
+ proxy.auth === undefined
367
+ ? {}
368
+ : {
369
+ authorization: basicHeader(
370
+ yield* resolvePrincipal(source, proxy.auth.user),
371
+ yield* resolveText(source, proxy.auth.password)
372
+ )
373
+ }
374
+ return { url: proxy.url, noProxy: proxy.noProxy ?? [], ...authorization }
375
+ })
376
+
377
+ const basicHeader = (
378
+ user: string,
379
+ password: Redacted.Redacted<string>
380
+ ): Redacted.Redacted<string> =>
381
+ Redacted.make(
382
+ `Basic ${Buffer.from(`${user}:${Redacted.value(password)}`, "utf8").toString("base64")}`
383
+ )
384
+
385
+ export const resolveSide = (
386
+ source: SecretSource,
387
+ side: HttpSide | undefined
388
+ ): Effect.Effect<ResolvedSide, AuthProfileError> =>
389
+ Effect.gen(function* () {
390
+ const auth = side?.auth
391
+ const tls = yield* resolveTls(source, side?.tls)
392
+ const proxy = yield* resolveProxy(source, side?.proxy)
393
+ if (auth === undefined || auth.scheme === "none") return { headers: [], tls, proxy }
394
+ if (auth.scheme === "basic") {
395
+ const user = yield* resolvePrincipal(source, auth.user)
396
+ const password = yield* resolveText(source, auth.password)
397
+ return { headers: [["authorization", basicHeader(user, password)]], tls, proxy }
398
+ }
399
+ const token = yield* resolveText(source, auth.token)
400
+ return {
401
+ headers: [["authorization", Redacted.make(`Bearer ${Redacted.value(token)}`)]],
402
+ tls,
403
+ proxy
404
+ }
405
+ })
406
+
407
+ export interface ResolvedUsernameToken {
408
+ readonly user: string
409
+ readonly password: Redacted.Redacted<string>
410
+ readonly passwordType: "text" | "digest"
411
+ }
412
+
413
+ export const resolveUsernameToken = (
414
+ source: SecretSource,
415
+ token: UsernameToken | undefined
416
+ ): Effect.Effect<ResolvedUsernameToken | undefined, AuthProfileError> =>
417
+ token === undefined
418
+ ? Effect.succeed(undefined)
419
+ : Effect.gen(function* () {
420
+ return {
421
+ user: yield* resolvePrincipal(source, token.user),
422
+ password: yield* resolveText(source, token.password),
423
+ passwordType: token.passwordType
424
+ }
425
+ })
426
+
427
+ /** Secrets from the process environment and local files. */
428
+ export const nodeSecretSource = (
429
+ environment: Readonly<Record<string, string | undefined>> = process.env
430
+ ): SecretSource => ({
431
+ environment,
432
+ readFile: (path) =>
433
+ Effect.tryPromise({
434
+ try: async () => new Uint8Array(await readFile(path)),
435
+ catch: () => new AuthProfileError({ subject: `file:${path}`, detail: "not readable" })
436
+ }),
437
+ readPemDirectory: (path) =>
438
+ Effect.tryPromise({
439
+ try: async () => {
440
+ const names = (await readdir(path)).filter((name) => /\.(pem|crt|cer)$/i.test(name)).sort()
441
+ const parts = await Promise.all(names.map((name) => readFile(join(path, name))))
442
+ return concatPem(...parts.map((part) => new Uint8Array(part)))
443
+ },
444
+ catch: () => new AuthProfileError({ subject: `tls.caDir ${path}`, detail: "not readable" })
445
+ })
446
+ })
@@ -0,0 +1,60 @@
1
+ import * as Effect from "effect/Effect"
2
+ import * as Schema from "effect/Schema"
3
+ import type { PlainFileStoreShape } from "../Persistence.ts"
4
+ import type { AuthProfile, AuthProfileError } from "./Auth.ts"
5
+ import { Environment, decodeAuthProfile, profileFileName } from "./Auth.ts"
6
+
7
+ /**
8
+ * Named endpoints (ADR 0048, 3.2): `<project>/.llm4ts/endpoints/<name>/auth.json`,
9
+ * or `auth.<env>.json`, in the same shape as a SOAP service profile — the
10
+ * `endpoint` URL, a `call` side (auth, tls, proxy), optional `fetch`,
11
+ * `mutating`, `timeoutSeconds`. A tool is given a name and an environment,
12
+ * never a token: secrets stay `env:NAME` or `file:path` references.
13
+ */
14
+ export const endpointProfilePath = (
15
+ projectRoot: string,
16
+ name: string,
17
+ env: string | undefined
18
+ ): string => `${projectRoot}/.llm4ts/endpoints/${name}/${profileFileName(env)}`
19
+
20
+ export class EndpointError extends Schema.TaggedError<EndpointError>()("EndpointError", {
21
+ endpoint: Schema.String,
22
+ message: Schema.String
23
+ }) {}
24
+
25
+ const endpointNamePattern = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/iu
26
+
27
+ export const loadEndpointProfile = (
28
+ files: PlainFileStoreShape,
29
+ projectRoot: string,
30
+ name: string,
31
+ env: string | undefined
32
+ ): Effect.Effect<AuthProfile, EndpointError> =>
33
+ Effect.gen(function* () {
34
+ if (!endpointNamePattern.test(name)) {
35
+ return yield* new EndpointError({ endpoint: name, message: "not an endpoint name" })
36
+ }
37
+ if (env !== undefined && !Schema.is(Environment)(env)) {
38
+ return yield* new EndpointError({
39
+ endpoint: name,
40
+ message: `env must be one of ${Environment.literals.join(", ")}, got '${env}'`
41
+ })
42
+ }
43
+ const path = endpointProfilePath(projectRoot, name, env)
44
+ const text = yield* files
45
+ .read(path)
46
+ .pipe(
47
+ Effect.mapError((error) => new EndpointError({ endpoint: name, message: error.message }))
48
+ )
49
+ if (text === undefined) {
50
+ return yield* new EndpointError({
51
+ endpoint: name,
52
+ message: `no profile at ${path}; write it with at least {"environment": "dev", "endpoint": "https://…"}`
53
+ })
54
+ }
55
+ return yield* decodeAuthProfile(text, path).pipe(
56
+ Effect.mapError(
57
+ (error: AuthProfileError) => new EndpointError({ endpoint: name, message: error.message })
58
+ )
59
+ )
60
+ })