@llm4ts/shell 4.8.0 → 4.9.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.
@@ -0,0 +1,204 @@
1
+ // @internal: the Node wiring of `llm4ts chat`, used only by the CLI
2
+ import { basename, resolve } from "node:path"
3
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"
4
+ import * as Cause from "effect/Cause"
5
+ import * as Clock from "effect/Clock"
6
+ import * as Console from "effect/Console"
7
+ import * as Effect from "effect/Effect"
8
+ import * as Exit from "effect/Exit"
9
+ import * as Fiber from "effect/Fiber"
10
+ import * as Option from "effect/Option"
11
+ import * as Ref from "effect/Ref"
12
+ import type * as Scope from "effect/Scope"
13
+ import type { PersistenceError } from "@llm4ts/flow/FlowError"
14
+ import type { FlowEventsShape } from "@llm4ts/flow/FlowEvents"
15
+ import { makeGitTool } from "@llm4ts/flow/GitTool"
16
+ import { makeGoogleChatTool, parseSpaceRef } from "@llm4ts/flow/GoogleChatTool"
17
+ import { settingValue } from "@llm4ts/flow/Settings"
18
+ import { asToolless, readOnlySeatProblem, reasonerFromEnvironment } from "@llm4ts/runner/Connectors"
19
+ import { interruptOnSignal, type SignalSource } from "@llm4ts/runner/FlowRunner"
20
+ import { nodePlainFileStore } from "@llm4ts/runner/NodePlainFileStore"
21
+ import { nodeProcessExecutor } from "@llm4ts/runner/NodeProcessExecutor"
22
+ import {
23
+ decideThroughFlow,
24
+ runChat,
25
+ type ChatLoopDeps,
26
+ type ChatOptions,
27
+ type ChatStopped
28
+ } from "./ChatLoop.ts"
29
+ import { nodeListTraces } from "./Costs.ts"
30
+ import { discoverFlows, type FlowTierPaths } from "./FlowCatalog.ts"
31
+ import { nodeFlowProcess } from "./FlowProcess.ts"
32
+ import { nodeListFiles } from "./OperatorNode.ts"
33
+ import { makeRunSupervisor } from "./RunSupervisor.ts"
34
+ import { ShellUsageError } from "./ShellErrors.ts"
35
+ import { nodeListEpics } from "./Watch.ts"
36
+
37
+ type Environment = Readonly<Record<string, string | undefined>>
38
+
39
+ export interface ChatFlags {
40
+ readonly space: Option.Option<string>
41
+ readonly trigger: Option.Option<string>
42
+ readonly marker: Option.Option<string>
43
+ readonly allow: ReadonlyArray<string>
44
+ /** Comma-separated flow names. */
45
+ readonly flows: Option.Option<string>
46
+ readonly interval: Option.Option<number>
47
+ readonly observe: boolean
48
+ }
49
+
50
+ export const defaultMarker = "🌙 chief:"
51
+ export const defaultIntervalSeconds = 5
52
+ export const defaultFlows: ReadonlyArray<string> = ["implement"]
53
+
54
+ const usage = (message: string): ShellUsageError => new ShellUsageError({ message })
55
+
56
+ /** The `chat` flags over the settings; a flag wins, and every rejection is a usage error. */
57
+ export const chatOptionsFrom = (
58
+ flags: ChatFlags,
59
+ environment: Environment
60
+ ): Effect.Effect<ChatOptions, ShellUsageError> =>
61
+ Effect.gen(function* () {
62
+ const spaceText =
63
+ Option.getOrUndefined(flags.space) ?? settingValue("LLM4TS_CHAT_SPACE", environment)
64
+ if (spaceText === undefined || spaceText.trim() === "") {
65
+ return yield* usage("chat needs a space: --space spaces/AAAA… or LLM4TS_CHAT_SPACE")
66
+ }
67
+ const space = parseSpaceRef(spaceText)
68
+ if (space === undefined) {
69
+ return yield* usage(`"${spaceText}" is not a Chat space; give spaces/AAAA… or its id`)
70
+ }
71
+ const trigger = Option.getOrElse(flags.trigger, () =>
72
+ settingValue("LLM4TS_CHAT_TRIGGER", environment)
73
+ ).trim()
74
+ if (trigger === "") return yield* usage("--trigger must not be empty")
75
+ const marker = Option.getOrElse(flags.marker, () => defaultMarker).trim()
76
+ if (marker === "") return yield* usage("--marker must not be empty")
77
+ const stranger = flags.allow.find((who) => !/^users\/\S+$/u.test(who))
78
+ if (stranger !== undefined) {
79
+ return yield* usage(`--allow takes a user id such as users/1234567890, not "${stranger}"`)
80
+ }
81
+ const flows = Option.match(flags.flows, {
82
+ onNone: () => defaultFlows,
83
+ onSome: (text) =>
84
+ text
85
+ .split(",")
86
+ .map((name) => name.trim())
87
+ .filter((name) => name.length > 0)
88
+ })
89
+ if (flows.length === 0) return yield* usage("--flows names no flow")
90
+ if (flows.includes("chief")) {
91
+ return yield* usage("--flows must not name chief: it is how the Chief decides, not a run")
92
+ }
93
+ const intervalSeconds = Option.getOrElse(flags.interval, () => defaultIntervalSeconds)
94
+ if (!Number.isInteger(intervalSeconds) || intervalSeconds < 1) {
95
+ return yield* usage("--interval must be a whole number of seconds, 1 or more")
96
+ }
97
+ return {
98
+ space,
99
+ trigger,
100
+ marker,
101
+ allow: flags.allow,
102
+ flows: [...new Set(flows)],
103
+ intervalSeconds,
104
+ observe: flags.observe
105
+ }
106
+ })
107
+
108
+ // Tools outside a flow run publish to nobody.
109
+ const noEvents: FlowEventsShape = { publish: () => Effect.void }
110
+
111
+ /**
112
+ * The chat loop's dependencies on Node for the repository at `cwd`, and
113
+ * only that one: the supervisor knows no other, so a run id the Chief names
114
+ * cannot reach elsewhere (other than a repository with the same directory
115
+ * name, which shares the registry, as under `llm4ts mcp`). Flows start with the process environment, as under
116
+ * `llm4ts mcp`; the reasoning seat is checked against `settings`, the
117
+ * environment with the config files applied. The supervisor lives in the
118
+ * scope, so closing it stops every run started from chat.
119
+ */
120
+ export const nodeChatDeps = (
121
+ options: ChatOptions,
122
+ cwd: string,
123
+ tierPaths: FlowTierPaths,
124
+ settings: Environment = process.env
125
+ ): Effect.Effect<ChatLoopDeps, PersistenceError, Scope.Scope> =>
126
+ Effect.gen(function* () {
127
+ const path = resolve(cwd)
128
+ const repo = { id: basename(path), path }
129
+ const environment: Environment = process.env
130
+ const supervisor = yield* makeRunSupervisor({
131
+ repos: [repo],
132
+ environment,
133
+ files: nodePlainFileStore,
134
+ process: nodeFlowProcess,
135
+ parallelRuns: 1
136
+ })
137
+ const deps: Omit<ChatLoopDeps, "decide"> = {
138
+ chat: makeGoogleChatTool(nodeProcessExecutor, path, noEvents),
139
+ files: nodePlainFileStore,
140
+ supervisor,
141
+ git: makeGitTool(nodeProcessExecutor, path, noEvents),
142
+ repo,
143
+ flows: discoverFlows(tierPaths).pipe(
144
+ Effect.provide(NodeFileSystem.layer),
145
+ Effect.map((flows) =>
146
+ flows.map((flow) => ({
147
+ name: flow.name,
148
+ path: flow.path,
149
+ description: flow.description ?? ""
150
+ }))
151
+ )
152
+ ),
153
+ sources: { files: nodePlainFileStore, listFiles: nodeListFiles },
154
+ listTraces: nodeListTraces,
155
+ listEpics: nodeListEpics,
156
+ environment,
157
+ now: Clock.currentTimeMillis,
158
+ say: (line) => Console.log(line),
159
+ strangers: yield* Ref.make<ReadonlySet<string>>(new Set()),
160
+ seatProblem: reasonerFromEnvironment(settings).pipe(
161
+ Effect.map((seat) => readOnlySeatProblem(asToolless(seat))),
162
+ Effect.catch((error) => Effect.succeed(error.message))
163
+ ),
164
+ ignored: nodeProcessExecutor.run(["git", "check-ignore", "-q", ".llm4ts/"], path, {}).pipe(
165
+ Effect.map((result) => result.exitCode === 0),
166
+ Effect.orElseSucceed(() => false)
167
+ ),
168
+ options
169
+ }
170
+ return { ...deps, decide: decideThroughFlow(deps) }
171
+ })
172
+
173
+ /**
174
+ * Runs the chat loop until it stops or a signal arrives. The first SIGINT or
175
+ * SIGTERM interrupts it and ends cleanly; closing the scope then stops the
176
+ * runs started from chat, as `llm4ts mcp` does. A second signal exits at
177
+ * once (130 or 143).
178
+ */
179
+ export const runChatUntilSignal = <E>(
180
+ deps: Effect.Effect<ChatLoopDeps, E, Scope.Scope>,
181
+ signals: SignalSource
182
+ ): Effect.Effect<void, E | ChatStopped | PersistenceError> => {
183
+ const disposers: Array<() => void> = []
184
+ return Effect.scoped(
185
+ Effect.gen(function* () {
186
+ const built = yield* deps
187
+ const fiber = yield* Effect.forkScoped(runChat(built))
188
+ disposers.push(interruptOnSignal(fiber, signals, ["SIGINT", "SIGTERM"]))
189
+ const exit = yield* Fiber.await(fiber)
190
+ if (Exit.isSuccess(exit)) return
191
+ if (Cause.hasInterruptsOnly(exit.cause)) {
192
+ yield* built.say("Stopping; runs started from chat are stopped too.")
193
+ return
194
+ }
195
+ return yield* Effect.failCause(exit.cause)
196
+ })
197
+ ).pipe(
198
+ Effect.ensuring(
199
+ Effect.sync(() => {
200
+ for (const dispose of disposers) dispose()
201
+ })
202
+ )
203
+ )
204
+ }
@@ -0,0 +1,156 @@
1
+ // @internal: the chat loop's persistent state, read and written only by the chat loop
2
+ import { join } from "node:path"
3
+ import * as Effect from "effect/Effect"
4
+ import * as Schema from "effect/Schema"
5
+ import { PersistenceError } from "@llm4ts/flow/FlowError"
6
+ import type { PlainFileStoreShape } from "@llm4ts/flow/Persistence"
7
+
8
+ export const postedLimit = 500
9
+
10
+ export const chatDir = (repoPath: string, spaceId: string): string =>
11
+ join(repoPath, ".llm4ts", "chat", spaceId)
12
+
13
+ export class ChatState extends Schema.Class<ChatState>("ChatState")({
14
+ space: Schema.String,
15
+ trigger: Schema.String,
16
+ marker: Schema.String,
17
+ cursor: Schema.String,
18
+ posted: Schema.Array(Schema.String),
19
+ ownerId: Schema.optional(Schema.String),
20
+ baseBranch: Schema.String
21
+ }) {}
22
+
23
+ export class ChatRequest extends Schema.Class<ChatRequest>("ChatRequest")({
24
+ messageName: Schema.String,
25
+ createTime: Schema.String,
26
+ sender: Schema.String,
27
+ text: Schema.String,
28
+ threadName: Schema.optional(Schema.String),
29
+ status: Schema.Literals(["received", "answered", "started", "refused", "failed", "ended"]),
30
+ action: Schema.optional(Schema.String),
31
+ reply: Schema.optional(Schema.String),
32
+ runId: Schema.optional(Schema.String),
33
+ outcome: Schema.optional(Schema.String)
34
+ }) {}
35
+
36
+ const StateJson = Schema.fromJsonString(ChatState)
37
+ const RequestJson = Schema.fromJsonString(ChatRequest)
38
+
39
+ const statePath = (dir: string): string => join(dir, "state.md")
40
+ const requestsPath = (dir: string): string => join(dir, "requests.md")
41
+
42
+ const persistenceError = (message: string, cause?: unknown): PersistenceError =>
43
+ PersistenceError.make(cause === undefined ? { message } : { message, cause })
44
+
45
+ // Free text only ever appears as "> " quote lines or inside a JSON string (one
46
+ // line, newlines escaped), so a ```json line is always ours.
47
+ const jsonBlock = (json: string): string => `\`\`\`json\n${json}\n\`\`\``
48
+
49
+ const quote = (text: string): string =>
50
+ text
51
+ .split("\n")
52
+ .map((line) => `> ${line}`)
53
+ .join("\n")
54
+
55
+ /** The single-line JSON of each ```json block, in file order. */
56
+ const jsonBlocks = (markdown: string): ReadonlyArray<string> => {
57
+ const lines = markdown.split("\n")
58
+ const blocks: Array<string> = []
59
+ for (let i = 0; i < lines.length - 2; i++) {
60
+ if (lines[i] === "```json" && lines[i + 2] === "```") {
61
+ blocks.push(lines[i + 1] ?? "")
62
+ i += 2
63
+ }
64
+ }
65
+ return blocks
66
+ }
67
+
68
+ export const renderState = (state: ChatState): string =>
69
+ [
70
+ "# Chat state",
71
+ "",
72
+ `- Space: ${state.space}`,
73
+ `- Trigger: ${state.trigger}`,
74
+ `- Cursor: ${state.cursor}`,
75
+ `- Base branch: ${state.baseBranch}`,
76
+ `- Posted messages: ${state.posted.length}`,
77
+ "",
78
+ jsonBlock(Schema.encodeSync(StateJson)(state)),
79
+ ""
80
+ ].join("\n")
81
+
82
+ export const parseState = (markdown: string): Effect.Effect<ChatState, PersistenceError> => {
83
+ const block = jsonBlocks(markdown)[0]
84
+ return block === undefined
85
+ ? Effect.fail(persistenceError("chat state has no json block"))
86
+ : Schema.decodeUnknownEffect(StateJson)(block).pipe(
87
+ Effect.mapError((cause) => persistenceError("chat state json is invalid", cause))
88
+ )
89
+ }
90
+
91
+ export const loadState = (
92
+ files: PlainFileStoreShape,
93
+ dir: string
94
+ ): Effect.Effect<ChatState | undefined, PersistenceError> =>
95
+ Effect.gen(function* () {
96
+ const path = statePath(dir)
97
+ const raw = yield* files.read(path)
98
+ if (raw === undefined) return undefined
99
+ return yield* parseState(raw).pipe(
100
+ Effect.mapError((error) => persistenceError(`${path}: ${error.message}`, error))
101
+ )
102
+ })
103
+
104
+ export const saveState = (
105
+ files: PlainFileStoreShape,
106
+ dir: string,
107
+ state: ChatState
108
+ ): Effect.Effect<void, PersistenceError> => files.writeAtomic(statePath(dir), renderState(state))
109
+
110
+ export const notePosted = (state: ChatState, messageName: string): ChatState =>
111
+ ChatState.make({ ...state, posted: [...state.posted, messageName].slice(-postedLimit) })
112
+
113
+ const renderRequest = (request: ChatRequest): string =>
114
+ [
115
+ `### ${request.messageName} (${request.status})`,
116
+ "",
117
+ `- From: ${request.sender} at ${request.createTime}`,
118
+ "",
119
+ quote(request.text),
120
+ "",
121
+ jsonBlock(Schema.encodeSync(RequestJson)(request)),
122
+ ""
123
+ ].join("\n")
124
+
125
+ export const loadRequests = (
126
+ files: PlainFileStoreShape,
127
+ dir: string
128
+ ): Effect.Effect<ReadonlyArray<ChatRequest>, PersistenceError> =>
129
+ Effect.gen(function* () {
130
+ const path = requestsPath(dir)
131
+ const raw = yield* files.read(path)
132
+ if (raw === undefined) return []
133
+ return yield* Effect.forEach(jsonBlocks(raw), (block) =>
134
+ Schema.decodeUnknownEffect(RequestJson)(block).pipe(
135
+ Effect.mapError((cause) =>
136
+ persistenceError(`${path}: a request json block is invalid`, cause)
137
+ )
138
+ )
139
+ )
140
+ })
141
+
142
+ export const putRequest = (
143
+ files: PlainFileStoreShape,
144
+ dir: string,
145
+ request: ChatRequest
146
+ ): Effect.Effect<void, PersistenceError> =>
147
+ Effect.gen(function* () {
148
+ const existing = yield* loadRequests(files, dir)
149
+ const next = existing.some((item) => item.messageName === request.messageName)
150
+ ? existing.map((item) => (item.messageName === request.messageName ? request : item))
151
+ : [...existing, request]
152
+ yield* files.writeAtomic(
153
+ requestsPath(dir),
154
+ ["# Chat requests", "", ...next.map(renderRequest)].join("\n")
155
+ )
156
+ })
package/src/Cli.ts CHANGED
@@ -57,6 +57,7 @@ import {
57
57
  import { settingValue } from "@llm4ts/flow/Settings"
58
58
  import { configCommand, configView, parseAssignment, renderDoctorConfig } from "./ConfigCommand.ts"
59
59
  import { launchFlow } from "./FlowLaunch.ts"
60
+ import { chatOptionsFrom, nodeChatDeps, runChatUntilSignal } from "./ChatNode.ts"
60
61
  import { mcpOptionsFrom } from "./OperatorConfig.ts"
61
62
  import { nodeOperatorRuntime, nodeRead, runMcp } from "./OperatorNode.ts"
62
63
  import { mainMenu } from "./Menu.ts"
@@ -1199,6 +1200,59 @@ const mcpCommand = Command.make(
1199
1200
  )
1200
1201
  )
1201
1202
 
1203
+ const chatCommand = Command.make(
1204
+ "chat",
1205
+ {
1206
+ space: Flag.String("space").pipe(
1207
+ Flag.optional,
1208
+ Flag.withDescription("The Chat space, spaces/AAAA… or its id (default LLM4TS_CHAT_SPACE)")
1209
+ ),
1210
+ trigger: Flag.String("trigger").pipe(
1211
+ Flag.optional,
1212
+ Flag.withDescription(
1213
+ "The word a request starts with (default LLM4TS_CHAT_TRIGGER, else /bot)"
1214
+ )
1215
+ ),
1216
+ marker: Flag.String("marker").pipe(
1217
+ Flag.optional,
1218
+ Flag.withDescription("What every message the Chief posts starts with (default 🌙 chief:)")
1219
+ ),
1220
+ allow: Flag.String("allow").pipe(
1221
+ Flag.atLeast(0),
1222
+ Flag.withDescription(
1223
+ "A user id (users/…) who may ask besides you, repeatable; --observe prints senders' ids"
1224
+ )
1225
+ ),
1226
+ flows: Flag.String("flows").pipe(
1227
+ Flag.optional,
1228
+ Flag.withDescription("Flows the Chief may start, comma-separated (default implement)")
1229
+ ),
1230
+ interval: Flag.Int("interval").pipe(
1231
+ Flag.optional,
1232
+ Flag.withDescription("Seconds between looks at the space (default 5)")
1233
+ ),
1234
+ observe: Flag.Boolean("observe").pipe(
1235
+ Flag.withDefault(false),
1236
+ Flag.withDescription("Read and decide, but post nothing and start nothing; print instead")
1237
+ )
1238
+ },
1239
+ (flags) =>
1240
+ Effect.gen(function* () {
1241
+ const cwd = process.cwd()
1242
+ const settings = yield* verbEnvironment(cwd)
1243
+ const options = yield* chatOptionsFrom(flags, settings)
1244
+ // SIGINT/SIGTERM end the loop; closing its scope stops the runs it started.
1245
+ yield* runChatUntilSignal(
1246
+ nodeChatDeps(options, cwd, shellTierPaths({ cwd }), settings),
1247
+ process
1248
+ )
1249
+ })
1250
+ ).pipe(
1251
+ Command.withDescription(
1252
+ "Bind this repository to a Google Chat space: a Chief of Staff answers /bot, starts flows and posts progress"
1253
+ )
1254
+ )
1255
+
1202
1256
  const doctorCommand = Command.make(
1203
1257
  "doctor",
1204
1258
  {
@@ -1255,6 +1309,7 @@ export const shellCommand = Command.make("llm4ts", {}, () =>
1255
1309
  rosterCommand,
1256
1310
  geminiBridgeCommand,
1257
1311
  mcpCommand,
1312
+ chatCommand,
1258
1313
  toolCommand,
1259
1314
  configCommand,
1260
1315
  doctorCommand
@@ -35,6 +35,9 @@ export interface RunLookupDeps {
35
35
  readonly supervisor: RunSupervisorShape
36
36
  }
37
37
 
38
+ /** What reading runs off disk needs: no supervisor, no configuration. */
39
+ export type DiskRunDeps = Pick<RunLookupDeps, "files" | "listTraces" | "listEpics">
40
+
38
41
  export interface Repo {
39
42
  readonly id: string
40
43
  readonly path: string
@@ -97,7 +100,7 @@ export interface EpicRunEntry {
97
100
  }
98
101
 
99
102
  export const epicRunsOf = (
100
- deps: RunLookupDeps,
103
+ deps: DiskRunDeps,
101
104
  repo: Repo
102
105
  ): Effect.Effect<ReadonlyArray<EpicRunEntry>, ReadFailed> =>
103
106
  Effect.forEach(deps.listEpics(epicsDir(repo)), (epic) => {
@@ -203,7 +206,7 @@ export const epicOfRun = (
203
206
 
204
207
  /** Runs found on disk (epic run lists and traces) that the supervisor does not hold. */
205
208
  export const discoveredRuns = (
206
- deps: RunLookupDeps,
209
+ deps: DiskRunDeps,
207
210
  repo: Repo,
208
211
  known: ReadonlySet<string>
209
212
  ): Effect.Effect<ReadonlyArray<OperatorRun>, ReadFailed> =>
@@ -67,7 +67,7 @@ export interface SupervisorOptions {
67
67
  readonly parallelRuns: number
68
68
  /** How long `stop` waits after SIGINT before SIGTERM; default 30 s. */
69
69
  readonly graceMs?: number
70
- /** Flows that may run beside a busy repository; default `epic-retro`. */
70
+ /** Flows that may run beside a busy repository; default `epic-retro` and `chief`. */
71
71
  readonly readOnlyFlows?: ReadonlySet<string>
72
72
  /** The 4-hex run id suffix; injectable so tests are deterministic. */
73
73
  readonly random?: () => string
@@ -122,7 +122,7 @@ export const makeRunSupervisor = (
122
122
  ): Effect.Effect<RunSupervisorShape, PersistenceError, Scope.Scope> =>
123
123
  Effect.gen(function* () {
124
124
  const graceMs = options.graceMs ?? 30_000
125
- const readOnlyFlows = options.readOnlyFlows ?? new Set(["epic-retro"])
125
+ const readOnlyFlows = options.readOnlyFlows ?? new Set(["epic-retro", "chief"])
126
126
  const random = options.random ?? randomHex
127
127
  const stateDir = (repoId: string) => operatorStateDir(options.environment, repoId)
128
128
  const registryPath = (repoId: string) => join(stateDir(repoId), "runs.jsonl")