@llm4ts/flow 3.0.0 → 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 (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 +34 -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 +101 -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 +54 -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 +124 -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
@@ -0,0 +1,351 @@
1
+ import * as Context from "effect/Context"
2
+ import * as Effect from "effect/Effect"
3
+ import * as Schema from "effect/Schema"
4
+ import type { SoapTransport } from "../endpoint/Transport.ts"
5
+ import { PlainFileStore } from "../Persistence.ts"
6
+
7
+ /**
8
+ * A tool is one repeatable action a coding agent would otherwise improvise
9
+ * — validate a document, compare two outputs, probe an endpoint — packaged
10
+ * as a module with a typed input, a typed report and an Effect `run`
11
+ * (ADR 0048). The `llm4ts tool` CLI lists, describes and runs them; a pack
12
+ * names presets over them so a story sees the same command every run.
13
+ */
14
+
15
+ export class ToolError extends Schema.TaggedError<ToolError>()("ToolError", {
16
+ tool: Schema.String,
17
+ message: Schema.String
18
+ }) {}
19
+
20
+ export class ToolIssue extends Schema.Class<ToolIssue>("ToolIssue")({
21
+ path: Schema.String,
22
+ detail: Schema.String
23
+ }) {}
24
+
25
+ /** What every tool prints: a verdict, one line, and the issues behind it. */
26
+ export class ToolReport extends Schema.Class<ToolReport>("ToolReport")({
27
+ tool: Schema.String,
28
+ ok: Schema.Boolean,
29
+ summary: Schema.String,
30
+ issues: Schema.Array(ToolIssue),
31
+ /** Issues cut from `issues` by the output cap; `--all` lifts it. */
32
+ truncated: Schema.Int,
33
+ data: Schema.optionalKey(Schema.Json)
34
+ }) {}
35
+
36
+ export const ToolArgKind = Schema.Literals(["string", "path", "integer", "boolean", "json"])
37
+ export type ToolArgKind = typeof ToolArgKind.Type
38
+
39
+ export interface ToolArg {
40
+ readonly description: string
41
+ readonly kind: ToolArgKind
42
+ readonly required?: boolean
43
+ readonly default?: string
44
+ }
45
+
46
+ export interface ToolContextShape {
47
+ /** The project the tool runs for: the main checkout of a worktree (`.llm4ts/` lives here). */
48
+ readonly projectRoot: string
49
+ /** The process environment, for `env:NAME` secret references; never printed. */
50
+ readonly environment: Readonly<Record<string, string | undefined>>
51
+ }
52
+
53
+ /** Where a tool runs: provided by the CLI, or by `runToolMain` from its arguments. */
54
+ export class ToolContext extends Context.Service<ToolContext, ToolContextShape>()(
55
+ "@llm4ts/flow/tools/ToolContext"
56
+ ) {}
57
+
58
+ /**
59
+ * The services a tool may use: file reads, its context, and the endpoint
60
+ * transport (3.2, ADR 0048) — nothing else.
61
+ */
62
+ export type ToolServices = PlainFileStore | ToolContext | SoapTransport
63
+
64
+ /** A tool with its input type erased: what a catalog holds and the CLI runs. */
65
+ export interface ToolShape {
66
+ readonly name: string
67
+ readonly purpose: string
68
+ readonly args: Readonly<Record<string, ToolArg>>
69
+ /** Decodes parsed arguments with the tool's schema, then runs it. */
70
+ readonly execute: (
71
+ values: Record<string, unknown>
72
+ ) => Effect.Effect<ToolReport, ToolError | ToolArgsError, ToolServices>
73
+ }
74
+
75
+ export interface Tool<I> extends ToolShape {
76
+ readonly input: Schema.Codec<I, unknown>
77
+ readonly run: (input: I) => Effect.Effect<ToolReport, ToolError, ToolServices>
78
+ }
79
+
80
+ export interface ToolDefinition<I> {
81
+ readonly name: string
82
+ readonly purpose: string
83
+ readonly args: Readonly<Record<string, ToolArg>>
84
+ readonly input: Schema.Codec<I, unknown>
85
+ readonly run: (input: I) => Effect.Effect<ToolReport, ToolError, ToolServices>
86
+ }
87
+
88
+ export const defineTool = <I>(definition: ToolDefinition<I>): Tool<I> => ({
89
+ ...definition,
90
+ execute: (values) =>
91
+ withArgDefaults(definition, values).pipe(
92
+ Effect.flatMap((complete) => decodeToolInput(definition, complete)),
93
+ Effect.flatMap(definition.run)
94
+ )
95
+ })
96
+
97
+ /** The argument table's defaults, coerced by kind, under every key the caller left out. */
98
+ const withArgDefaults = (
99
+ tool: Pick<ToolShape, "name" | "args">,
100
+ values: Record<string, unknown>
101
+ ): Effect.Effect<Record<string, unknown>, ToolArgsError> =>
102
+ Effect.gen(function* () {
103
+ const complete: Record<string, unknown> = { ...values }
104
+ for (const [name, arg] of Object.entries(tool.args)) {
105
+ if (arg.default !== undefined && !(name in complete)) {
106
+ complete[name] = yield* coerce(tool.name, name, arg.kind, arg.default)
107
+ }
108
+ }
109
+ return complete
110
+ })
111
+
112
+ /** The spec the CLI prints for `describe` and the brief quotes per preset. */
113
+ export class ToolSpec extends Schema.Class<ToolSpec>("ToolSpec")({
114
+ name: Schema.String,
115
+ purpose: Schema.String,
116
+ args: Schema.Record(
117
+ Schema.String,
118
+ Schema.Struct({
119
+ description: Schema.String,
120
+ kind: ToolArgKind,
121
+ required: Schema.optionalKey(Schema.Boolean),
122
+ default: Schema.optionalKey(Schema.String)
123
+ })
124
+ )
125
+ }) {}
126
+
127
+ export const specOf = (tool: Pick<ToolShape, "name" | "purpose" | "args">): ToolSpec =>
128
+ ToolSpec.make({
129
+ name: tool.name,
130
+ purpose: tool.purpose,
131
+ args: Object.fromEntries(
132
+ Object.entries(tool.args).map(([name, arg]) => [
133
+ name,
134
+ {
135
+ description: arg.description,
136
+ kind: arg.kind,
137
+ ...(arg.required === undefined ? {} : { required: arg.required }),
138
+ ...(arg.default === undefined ? {} : { default: arg.default })
139
+ }
140
+ ])
141
+ )
142
+ })
143
+
144
+ const toolNamePattern = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u
145
+
146
+ export const isToolName = (name: string): boolean => toolNamePattern.test(name)
147
+
148
+ /** `describe` text: purpose, then one line per argument. */
149
+ export const renderSpec = (spec: ToolSpec): string =>
150
+ [
151
+ `${spec.name}: ${spec.purpose}`,
152
+ ...Object.entries(spec.args).map(
153
+ ([name, arg]) =>
154
+ ` --${name} <${arg.kind}>${arg.required === true ? " (required)" : ""}${
155
+ arg.default === undefined ? "" : ` [default ${arg.default}]`
156
+ }: ${arg.description}`
157
+ )
158
+ ].join("\n")
159
+
160
+ /** The one-line usage the brief quotes: `name --a <kind> [--b <kind>]`. */
161
+ export const renderUsage = (spec: ToolSpec): string =>
162
+ [
163
+ spec.name,
164
+ ...Object.entries(spec.args).map(([name, arg]) =>
165
+ arg.required === true ? `--${name} <${arg.kind}>` : `[--${name} <${arg.kind}>]`
166
+ )
167
+ ].join(" ")
168
+
169
+ export class ToolArgsError extends Schema.TaggedError<ToolArgsError>()("ToolArgsError", {
170
+ tool: Schema.String,
171
+ message: Schema.String
172
+ }) {}
173
+
174
+ /**
175
+ * `--name value` pairs (a boolean flag stands alone) to the record a tool's
176
+ * input schema decodes: kinds coerce the text, unknown names and a missing
177
+ * required argument are errors that quote the spec.
178
+ */
179
+ export const parseToolArgs = (
180
+ spec: ToolSpec,
181
+ argv: ReadonlyArray<string>
182
+ ): Effect.Effect<Record<string, unknown>, ToolArgsError> =>
183
+ Effect.gen(function* () {
184
+ const fail = (message: string) =>
185
+ new ToolArgsError({ tool: spec.name, message: `${message}\n${renderSpec(spec)}` })
186
+ const values: Record<string, unknown> = {}
187
+ for (const [name, arg] of Object.entries(spec.args)) {
188
+ if (arg.default !== undefined) {
189
+ values[name] = yield* coerce(spec.name, name, arg.kind, arg.default)
190
+ }
191
+ }
192
+ let index = 0
193
+ while (index < argv.length) {
194
+ const token = argv[index] ?? ""
195
+ if (!token.startsWith("--")) {
196
+ return yield* fail(`unexpected argument '${token}'`)
197
+ }
198
+ const equals = token.indexOf("=")
199
+ const name = equals > 0 ? token.slice(2, equals) : token.slice(2)
200
+ const arg = spec.args[name]
201
+ if (arg === undefined) {
202
+ return yield* fail(`unknown argument '--${name}'`)
203
+ }
204
+ let text: string
205
+ if (equals > 0) {
206
+ text = token.slice(equals + 1)
207
+ index += 1
208
+ } else if (
209
+ arg.kind === "boolean" &&
210
+ (index + 1 >= argv.length || argv[index + 1]?.startsWith("--"))
211
+ ) {
212
+ text = "true"
213
+ index += 1
214
+ } else if (index + 1 < argv.length) {
215
+ text = argv[index + 1] ?? ""
216
+ index += 2
217
+ } else {
218
+ return yield* fail(`argument '--${name}' needs a value`)
219
+ }
220
+ values[name] = yield* coerce(spec.name, name, arg.kind, text)
221
+ }
222
+ for (const [name, arg] of Object.entries(spec.args)) {
223
+ if (arg.required === true && !(name in values)) {
224
+ return yield* fail(`missing required argument '--${name}'`)
225
+ }
226
+ }
227
+ return values
228
+ })
229
+
230
+ const coerce = (
231
+ tool: string,
232
+ name: string,
233
+ kind: ToolArgKind,
234
+ text: string
235
+ ): Effect.Effect<unknown, ToolArgsError> => {
236
+ switch (kind) {
237
+ case "string":
238
+ case "path":
239
+ return Effect.succeed(text)
240
+ case "integer": {
241
+ const value = Number.parseInt(text, 10)
242
+ return Number.isInteger(value) && String(value) === text.trim()
243
+ ? Effect.succeed(value)
244
+ : Effect.fail(
245
+ new ToolArgsError({
246
+ tool,
247
+ message: `argument '--${name}' expects an integer, got '${text}'`
248
+ })
249
+ )
250
+ }
251
+ case "boolean":
252
+ return text === "true" || text === "false"
253
+ ? Effect.succeed(text === "true")
254
+ : Effect.fail(
255
+ new ToolArgsError({
256
+ tool,
257
+ message: `argument '--${name}' expects true or false, got '${text}'`
258
+ })
259
+ )
260
+ case "json":
261
+ return Effect.try({
262
+ try: (): unknown => JSON.parse(text),
263
+ catch: () => new ToolArgsError({ tool, message: `argument '--${name}' is not valid JSON` })
264
+ })
265
+ }
266
+ }
267
+
268
+ /** Decodes parsed arguments with the tool's own schema; a failure quotes the spec. */
269
+ export const decodeToolInput = <I>(
270
+ tool: ToolDefinition<I>,
271
+ values: Record<string, unknown>
272
+ ): Effect.Effect<I, ToolArgsError> =>
273
+ Schema.decodeUnknownEffect(tool.input)(values).pipe(
274
+ Effect.mapError(
275
+ (error) =>
276
+ new ToolArgsError({
277
+ tool: tool.name,
278
+ message: `${String(error)}\n${renderSpec(specOf(tool))}`
279
+ })
280
+ )
281
+ )
282
+
283
+ export const defaultIssueCap = 50
284
+
285
+ /** The report the CLI prints: issues capped unless `all`, the rest counted. */
286
+ export const capReport = (report: ToolReport, all: boolean): ToolReport =>
287
+ all || report.issues.length <= defaultIssueCap
288
+ ? report
289
+ : ToolReport.make({
290
+ ...report,
291
+ issues: report.issues.slice(0, defaultIssueCap),
292
+ truncated: report.truncated + report.issues.length - defaultIssueCap
293
+ })
294
+
295
+ /** A plain-text rendering for terminals; the CLI default is JSON. */
296
+ export const renderReport = (report: ToolReport): string =>
297
+ [
298
+ `${report.ok ? "ok" : "FAIL"} ${report.tool}: ${report.summary}`,
299
+ ...report.issues.map((issue) => ` ${issue.path}: ${issue.detail}`),
300
+ ...(report.truncated > 0 ? [` … ${report.truncated} more (run with --all)`] : [])
301
+ ].join("\n")
302
+
303
+ /** Reads a document for a tool; a missing file is a `ToolError` naming it. */
304
+ export const readToolFile = (
305
+ tool: string,
306
+ path: string
307
+ ): Effect.Effect<string, ToolError, PlainFileStore> =>
308
+ Effect.gen(function* () {
309
+ const files = yield* PlainFileStore
310
+ const text = yield* files
311
+ .read(path)
312
+ .pipe(
313
+ Effect.mapError(
314
+ (error) => new ToolError({ tool, message: `cannot read ${path}: ${error.message}` })
315
+ )
316
+ )
317
+ if (text === undefined) {
318
+ return yield* new ToolError({ tool, message: `no such file: ${path}` })
319
+ }
320
+ return text
321
+ })
322
+
323
+ export const parseJsonDocument = (
324
+ tool: string,
325
+ path: string,
326
+ text: string
327
+ ): Effect.Effect<unknown, ToolError> =>
328
+ Effect.try({
329
+ try: (): unknown => JSON.parse(text),
330
+ catch: (error) =>
331
+ new ToolError({
332
+ tool,
333
+ message: `${path} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
334
+ })
335
+ })
336
+
337
+ export const report = (
338
+ tool: string,
339
+ issues: ReadonlyArray<{ readonly path: string; readonly detail: string }>,
340
+ okSummary: string,
341
+ data?: typeof Schema.Json.Type
342
+ ): ToolReport =>
343
+ ToolReport.make({
344
+ tool,
345
+ ok: issues.length === 0,
346
+ summary:
347
+ issues.length === 0 ? okSummary : `${issues.length} issue${issues.length === 1 ? "" : "s"}`,
348
+ issues: issues.map((issue) => ToolIssue.make({ path: issue.path, detail: issue.detail })),
349
+ truncated: 0,
350
+ ...(data === undefined ? {} : { data })
351
+ })