@r_masseater/masseater-utils 0.16.0 → 0.17.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,20 @@
1
+ import { Array, Config, Effect, Option, Schema, pipe } from "effect";
2
+ // src/shared/lib/cache.ts
3
+ const taggedError = Schema.TaggedError;
4
+ var CacheRootError = class extends taggedError()("CacheRootError", { message: Schema.String }) {};
5
+ const SEPARATOR = "/";
6
+ const CACHE_DIRECTORY_NAME = ".cache";
7
+ const variable = (name) => Config.option(Config.NonEmptyString(name)).pipe(Effect.orElseSucceed(Option.none));
8
+ const baseDirectory = Effect.gen(function* baseDirectory() {
9
+ const cacheHome = yield* variable("XDG_CACHE_HOME");
10
+ const home = yield* variable("HOME");
11
+ const profile = yield* variable("USERPROFILE");
12
+ return pipe(cacheHome, Option.orElse(() => pipe(Option.orElse(home, () => profile), Option.map((directory) => `${directory}${SEPARATOR}${CACHE_DIRECTORY_NAME}`))));
13
+ });
14
+ const cacheRootEffect = (segments) => baseDirectory.pipe(Effect.flatMap(Option.match({
15
+ onNone: () => Effect.fail(CacheRootError.make({ message: "set XDG_CACHE_HOME or HOME" })),
16
+ onSome: (base) => Effect.succeed(pipe([base, ...segments], Array.join(SEPARATOR)))
17
+ })));
18
+ export { CacheRootError as n, cacheRootEffect as r, CACHE_DIRECTORY_NAME as t };
19
+
20
+ //# sourceMappingURL=cache-B2pb5ulh.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-B2pb5ulh.mjs","names":["Arr"],"sources":["../src/shared/lib/cache.ts"],"sourcesContent":["import { Array as Arr, Config, Effect, Option, Schema, pipe } from \"effect\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class CacheRootError extends taggedError<\n CacheRootError,\n { readonly brand: unique symbol }\n>()(\"CacheRootError\", { message: Schema.String }) {}\n\nconst SEPARATOR = \"/\";\nexport const CACHE_DIRECTORY_NAME = \".cache\";\n\nconst variable = (name: string): Effect.Effect<Option.Option<string>> =>\n Config.option(Config.NonEmptyString(name)).pipe(Effect.orElseSucceed(Option.none));\n\nconst baseDirectory: Effect.Effect<Option.Option<string>> = Effect.gen(function* baseDirectory() {\n const cacheHome = yield* variable(\"XDG_CACHE_HOME\");\n const home = yield* variable(\"HOME\");\n const profile = yield* variable(\"USERPROFILE\");\n return pipe(\n cacheHome,\n Option.orElse(() =>\n pipe(\n Option.orElse(home, () => profile),\n Option.map((directory) => `${directory}${SEPARATOR}${CACHE_DIRECTORY_NAME}`),\n ),\n ),\n );\n});\n\nexport const cacheRootEffect = (\n segments: readonly string[],\n): Effect.Effect<string, CacheRootError> =>\n baseDirectory.pipe(\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.fail(CacheRootError.make({ message: \"set XDG_CACHE_HOME or HOME\" })),\n onSome: (base) => Effect.succeed(pipe([base, ...segments], Arr.join(SEPARATOR))),\n }),\n ),\n );\n"],"mappings":";;AAEA,MAAM,cAAc,OAAO;AAE3B,IAAa,iBAAb,cAAoC,YAGlC,CAAC,CAAC,kBAAkB,EAAE,SAAS,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;AAEnD,MAAM,YAAY;AAClB,MAAa,uBAAuB;AAEpC,MAAM,YAAY,SAChB,OAAO,OAAO,OAAO,eAAe,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,cAAc,OAAO,IAAI,CAAC;AAEnF,MAAM,gBAAsD,OAAO,IAAI,UAAU,gBAAgB;CAC/F,MAAM,YAAY,OAAO,SAAS,gBAAgB;CAClD,MAAM,OAAO,OAAO,SAAS,MAAM;CACnC,MAAM,UAAU,OAAO,SAAS,aAAa;CAC7C,OAAO,KACL,WACA,OAAO,aACL,KACE,OAAO,OAAO,YAAY,OAAO,GACjC,OAAO,KAAK,cAAc,GAAG,YAAY,YAAY,sBAAsB,CAC7E,CACF,CACF;AACF,CAAC;AAED,MAAa,mBACX,aAEA,cAAc,KACZ,OAAO,QACL,OAAO,MAAM;CACX,cAAc,OAAO,KAAK,eAAe,KAAK,EAAE,SAAS,6BAA6B,CAAC,CAAC;CACxF,SAAS,SAAS,OAAO,QAAQ,KAAK,CAAC,MAAM,GAAG,QAAQ,GAAGA,MAAI,KAAK,SAAS,CAAC,CAAC;AACjF,CAAC,CACH,CACF"}
@@ -0,0 +1,10 @@
1
+ import { Effect, Schema } from "effect";
2
+ declare const CacheRootError_base: Schema.Class<CacheRootError, Schema.TaggedStruct<"CacheRootError", {
3
+ readonly message: Schema.String;
4
+ }>, import("effect/Cause").YieldableError & {
5
+ readonly brand: unique symbol;
6
+ }>;
7
+ declare class CacheRootError extends CacheRootError_base {}
8
+ declare const CACHE_DIRECTORY_NAME = ".cache";
9
+ declare const cacheRootEffect: (segments: readonly string[]) => Effect.Effect<string, CacheRootError>;
10
+ export { CacheRootError as n, cacheRootEffect as r, CACHE_DIRECTORY_NAME as t };
@@ -0,0 +1,2 @@
1
+ import { n as CacheRootError, r as cacheRootEffect, t as CACHE_DIRECTORY_NAME } from "./cache-B_fAwTnH.mjs";
2
+ export { CACHE_DIRECTORY_NAME, CacheRootError, cacheRootEffect };
package/dist/cache.mjs ADDED
@@ -0,0 +1 @@
1
+ export { t as CACHE_DIRECTORY_NAME, n as CacheRootError, r as cacheRootEffect } from "./cache-B2pb5ulh.mjs";
@@ -1,7 +1,7 @@
1
1
  import { Array, Config, DateTime, Effect, FileSystem, Option, Path, Record, Schema, String, pipe } from "effect";
2
2
  import { Argument, Command } from "effect/cli";
3
3
  import { t as runMain } from "../run-main-CfugYs_u.mjs";
4
- import { a as succeeds, i as outputOf, r as mustSucceed } from "../process-l69KvwcT.mjs";
4
+ import { a as outputOf, i as mustSucceed, o as succeeds } from "../process-DTCkAoL_.mjs";
5
5
  // src/features/publish-updates/model/manifest.ts
6
6
  const Manifest$1 = Schema.fromJsonString(Schema.Struct({
7
7
  name: Schema.String,
@@ -1,6 +1,6 @@
1
1
  import { Config, Effect, FileSystem, PlatformError, Schema } from "effect";
2
2
  import { HttpBody, HttpClient, HttpClientError } from "effect/http";
3
- import { a as outputOf, i as mustSucceed, n as CommandFailed, o as succeeds, r as finished, t as Command } from "./process-BHJEIAWo.mjs";
3
+ import { c as outputOf, i as CommandFailed, l as succeeds, o as finished, r as Command, s as mustSucceed } from "./process-z7u_XWgI.mjs";
4
4
  /** @internal */
5
5
  type Failure = Config.ConfigError | HttpBody.HttpBodyError | HttpClientError.HttpClientError;
6
6
  /** @internal */
@@ -1,6 +1,6 @@
1
1
  import { Array, Config, Console, Effect, FileSystem, Record, Redacted, Schema, pipe } from "effect";
2
2
  import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
3
- import { a as succeeds, i as outputOf, n as finished, r as mustSucceed, t as CommandFailed } from "./process-l69KvwcT.mjs";
3
+ import { a as outputOf, i as mustSucceed, o as succeeds, r as finished, t as CommandFailed } from "./process-DTCkAoL_.mjs";
4
4
  import { Hex } from "effect/encoding";
5
5
  // src/shared/api/github/github.ts
6
6
  const API = "https://api.github.com";
@@ -1,13 +1,6 @@
1
- import { Config, Effect, FileSystem, Path, Schema } from "effect";
1
+ import { n as CacheRootError, r as cacheRootEffect, t as CACHE_DIRECTORY_NAME } from "./cache-B_fAwTnH.mjs";
2
2
  import { a as readHookInput, i as blockHook, n as runHookWith, o as writeHookOutput, r as HookBlocked, s as Platform, t as runHook } from "./index-CgNig8WC.mjs";
3
- declare const CacheRootError_base: Schema.Class<CacheRootError, Schema.TaggedStruct<"CacheRootError", {
4
- readonly message: Schema.String;
5
- }>, import("effect/Cause").YieldableError & {
6
- readonly brand: unique symbol;
7
- }>;
8
- export declare class CacheRootError extends CacheRootError_base {}
9
- export declare const CACHE_DIRECTORY_NAME = ".cache";
10
- export declare const cacheRootEffect: (segments: readonly string[]) => Effect.Effect<string, CacheRootError>;
3
+ import { Config, Effect, FileSystem, Path, Schema } from "effect";
11
4
  export declare const isRecord: <I>(input: I) => input is I & {
12
5
  readonly [x: string]: unknown;
13
6
  };
@@ -123,4 +116,4 @@ export declare const placeOf: (env: PlaceEnv) => Place;
123
116
  export declare const jevBackend: (settings: JevSettings, origin: Origin) => JevBackend;
124
117
  export declare const stateFor: (backend: JevBackend, state: JevState) => JevState | string;
125
118
  export declare const estimateTokens: (text: string) => number;
126
- export { type CompactionState, type FitOptions, type FittedState, type HistoryEntry, type HistoryToolCall, HookBlocked, type InstalledPlugin, type JevBackend, type JevSettings, type JevState, type Message, type Origin, type Place, type PlaceEnv, type Platform, type Role, type ToolCall, type ToolResult, type ToolUse, blockHook, readHookInput, runHook, runHookWith, writeHookOutput };
119
+ export { CACHE_DIRECTORY_NAME, CacheRootError, type CompactionState, type FitOptions, type FittedState, type HistoryEntry, type HistoryToolCall, HookBlocked, type InstalledPlugin, type JevBackend, type JevSettings, type JevState, type Message, type Origin, type Place, type PlaceEnv, type Platform, type Role, type ToolCall, type ToolResult, type ToolUse, blockHook, cacheRootEffect, readHookInput, runHook, runHookWith, writeHookOutput };
@@ -1,12 +1,13 @@
1
- import { Array, Cause, Config, Effect, FileSystem, Layer, Number as Number$1, Option, Path, Predicate, Record, Result, Runtime, Schema, Stdio, Stream, String as String$1, pipe } from "effect";
2
- import { Record as Record$1, String as String$2, Unknown, is } from "effect/Schema";
1
+ import { n as CacheRootError, r as cacheRootEffect, t as CACHE_DIRECTORY_NAME } from "./cache-B2pb5ulh.mjs";
2
+ import { Record, String as String$1, Unknown, is } from "effect/Schema";
3
+ import { Array, Cause, Config, Effect, FileSystem, Layer, Number as Number$1, Option, Path, Predicate, Record as Record$1, Result, Runtime, Schema, Stdio, Stream, String as String$2, pipe } from "effect";
3
4
  import { n as runMainWith } from "./run-main-CfugYs_u.mjs";
4
5
  import { t as groupOf } from "./match-groups-MH1j-WE-.mjs";
5
6
  // src/features/run-main/model/hook-io.ts
6
7
  const EXIT_BLOCKING = 2;
7
- const taggedError$2 = Schema.TaggedError;
8
+ const taggedError$1 = Schema.TaggedError;
8
9
  /** @internal */
9
- var HookBlocked = class extends taggedError$2()("HookBlocked", { reason: Schema.String }) {
10
+ var HookBlocked = class extends taggedError$1()("HookBlocked", { reason: Schema.String }) {
10
11
  [Runtime.errorExitCode] = EXIT_BLOCKING;
11
12
  [Runtime.errorReported] = false;
12
13
  };
@@ -54,24 +55,8 @@ const runHook = (serviceName) => runHookWith({
54
55
  serviceName,
55
56
  services: Layer.empty
56
57
  });
57
- // src/shared/lib/cache.ts
58
- const taggedError$1 = Schema.TaggedError;
59
- var CacheRootError = class extends taggedError$1()("CacheRootError", { message: Schema.String }) {};
60
- const SEPARATOR = "/";
61
- const CACHE_DIRECTORY_NAME = ".cache";
62
- const variable = (name) => Config.option(Config.NonEmptyString(name)).pipe(Effect.orElseSucceed(Option.none));
63
- const baseDirectory = Effect.gen(function* baseDirectory() {
64
- const cacheHome = yield* variable("XDG_CACHE_HOME");
65
- const home = yield* variable("HOME");
66
- const profile = yield* variable("USERPROFILE");
67
- return pipe(cacheHome, Option.orElse(() => pipe(Option.orElse(home, () => profile), Option.map((directory) => `${directory}${SEPARATOR}${CACHE_DIRECTORY_NAME}`))));
68
- });
69
- const cacheRootEffect = (segments) => baseDirectory.pipe(Effect.flatMap(Option.match({
70
- onNone: () => Effect.fail(CacheRootError.make({ message: "set XDG_CACHE_HOME or HOME" })),
71
- onSome: (base) => Effect.succeed(pipe([base, ...segments], Array.join(SEPARATOR)))
72
- })));
73
58
  // src/shared/lib/record.ts
74
- const isRecord = is(Record$1(String$2, Unknown));
59
+ const isRecord = is(Record(String$1, Unknown));
75
60
  // src/features/fit-history/model/calls.ts
76
61
  const FIRST = 0;
77
62
  const ONE$3 = 1;
@@ -82,13 +67,13 @@ const SPACES = /\s+/gu;
82
67
  const encodeJson$1 = Schema.encodeOption(Schema.fromJsonString(Schema.Unknown));
83
68
  const jsonOf = (value) => encodeJson$1(value);
84
69
  const truncate = (text, limit) => {
85
- if (String$1.length(text) <= limit) return text;
86
- return `${String$1.slice(FIRST, Math.max(FIRST, limit - ONE$3))(text)}${ELLIPSIS}`;
70
+ if (String$2.length(text) <= limit) return text;
71
+ return `${String$2.slice(FIRST, Math.max(FIRST, limit - ONE$3))(text)}${ELLIPSIS}`;
87
72
  };
88
73
  const isPinned = (index, total, preserveRecentMessages) => index === FIRST || index >= total - preserveRecentMessages;
89
74
  const resultsOf = (messages) => new Map(pipe(messages, Array.flatMap((message, index) => pipe(message.toolResults, Array.map((result) => [result.tool_use_id, {
90
75
  index,
91
- chars: String$1.length(result.text),
76
+ chars: String$2.length(result.text),
92
77
  isError: result.isError
93
78
  }])))));
94
79
  const collectToolCalls = (messages, preserveRecentMessages) => {
@@ -118,13 +103,13 @@ const outcomeOf = (call) => {
118
103
  const resultNote = (call) => `${outcomeOf(call)}, ${String(call.resultChars)} chars (omitted)`;
119
104
  const valueText = ([key, value]) => {
120
105
  const text = pipe(Option.liftPredicate(value, (raw) => typeof raw === "string"), Option.getOrElse(() => inputText({ [key]: value }, VALUE_CHARS)));
121
- return `${key}=${String$1.replaceAll(SPACES, " ")(text)}`;
106
+ return `${key}=${String$2.replaceAll(SPACES, " ")(text)}`;
122
107
  };
123
108
  const compactCall = (call) => {
124
- const input = pipe(Record.toEntries(call.input), Array.map(valueText), Array.join(" "));
109
+ const input = pipe(Record$1.toEntries(call.input), Array.map(valueText), Array.join(" "));
125
110
  return `${call.id} ${call.tool} ${truncate(input, COMPACT_INPUT_CHARS)} → ${outcomeOf(call)} ${String(call.resultChars)}ch`;
126
111
  };
127
- const callsByMessage = (calls) => new Map(pipe(calls, Array.groupBy((call) => String(call.callIndex)), Record.toEntries, Array.map(([index, own]) => [Number(index), own])));
112
+ const callsByMessage = (calls) => new Map(pipe(calls, Array.groupBy((call) => String(call.callIndex)), Record$1.toEntries, Array.map(([index, own]) => [Number(index), own])));
128
113
  const historyCallOf = (inputChars) => (call) => ({
129
114
  id: call.id,
130
115
  tool: call.tool,
@@ -145,7 +130,7 @@ const historyEntries = (messages, calls, inputChars) => {
145
130
  ...entry,
146
131
  tool_calls: toolCalls
147
132
  }];
148
- if (String$1.isEmpty(String$1.trim(message.text))) return [];
133
+ if (String$2.isEmpty(String$2.trim(message.text))) return [];
149
134
  return [entry];
150
135
  }));
151
136
  };
@@ -155,8 +140,8 @@ const DIGITS_PER_TOKEN = 2;
155
140
  const LETTERS_PER_TOKEN = 6;
156
141
  const SYMBOL_TOKENS = .9;
157
142
  const ONE$2 = 1;
158
- const pieceTokens = (match) => pipe(groupOf("digits")(match), Option.map((digits) => String$1.length(digits) / DIGITS_PER_TOKEN), Option.orElse(() => Option.map(groupOf("alpha")(match), (alpha) => ONE$2 + Math.floor((String$1.length(alpha) - ONE$2) / LETTERS_PER_TOKEN))), Option.getOrElse(() => SYMBOL_TOKENS));
159
- const matchesOf = (pattern, text) => Array.fromIterable(String$1.matchAll(pattern)(text));
143
+ const pieceTokens = (match) => pipe(groupOf("digits")(match), Option.map((digits) => String$2.length(digits) / DIGITS_PER_TOKEN), Option.orElse(() => Option.map(groupOf("alpha")(match), (alpha) => ONE$2 + Math.floor((String$2.length(alpha) - ONE$2) / LETTERS_PER_TOKEN))), Option.getOrElse(() => SYMBOL_TOKENS));
144
+ const matchesOf = (pattern, text) => Array.fromIterable(String$2.matchAll(pattern)(text));
160
145
  const estimateTokens = (text) => {
161
146
  const pieces = pipe(matchesOf(PIECES, text), Array.map(pieceTokens));
162
147
  return Math.ceil(Number$1.sumAll(pieces));
@@ -230,20 +215,20 @@ const RECENT_GOALS = 3;
230
215
  const GOAL_CHARS = 500;
231
216
  const ONE = 1;
232
217
  const abridge = (text) => {
233
- const omitted = String$1.length(text) - TEXT_HEAD - TEXT_TAIL;
234
- return `${String$1.takeLeft(TEXT_HEAD)(text)}\n[… ${String(omitted)} chars omitted …]\n${String$1.takeRight(TEXT_TAIL)(text)}`;
218
+ const omitted = String$2.length(text) - TEXT_HEAD - TEXT_TAIL;
219
+ return `${String$2.takeLeft(TEXT_HEAD)(text)}\n[… ${String(omitted)} chars omitted …]\n${String$2.takeRight(TEXT_TAIL)(text)}`;
235
220
  };
236
- const goalFromMessages = (messages) => pipe(messages, Array.filter((message) => message.role === "user" && String$1.isNonEmpty(String$1.trim(message.text)) && Array.isReadonlyArrayEmpty(message.toolResults)), Array.takeRight(RECENT_GOALS), Array.map((message) => truncate(message.text, GOAL_CHARS)), Array.join("\n"));
221
+ const goalFromMessages = (messages) => pipe(messages, Array.filter((message) => message.role === "user" && String$2.isNonEmpty(String$2.trim(message.text)) && Array.isReadonlyArrayEmpty(message.toolResults)), Array.takeRight(RECENT_GOALS), Array.map((message) => truncate(message.text, GOAL_CHARS)), Array.join("\n"));
237
222
  const abridgeText = (entry) => Option.liftPredicate(Option.some({
238
223
  ...entry,
239
224
  text: abridge(entry.text)
240
- }), () => String$1.length(entry.text) > 590);
225
+ }), () => String$2.length(entry.text) > 590);
241
226
  const collapseText = (plan) => (entry) => {
242
- const original = pipe(Array.get(plan.messages, entry.index), Option.map((message) => String$1.length(message.text)), Option.getOrElse(() => String$1.length(entry.text)));
227
+ const original = pipe(Array.get(plan.messages, entry.index), Option.map((message) => String$2.length(message.text)), Option.getOrElse(() => String$2.length(entry.text)));
243
228
  return Option.liftPredicate(Option.some({
244
229
  ...entry,
245
230
  text: `[… ${String(original)} chars omitted …]`
246
- }), () => !pinnedEntry(plan, entry) && String$1.isNonEmpty(entry.text));
231
+ }), () => !pinnedEntry(plan, entry) && String$2.isNonEmpty(entry.text));
247
232
  };
248
233
  const compactCalls = (plan) => (entry) => pipe(Option.fromUndefinedOr(plan.byMessage.get(entry.index)), Option.filter(() => !pinnedEntry(plan, entry)), Option.map((own) => Option.some({
249
234
  ...entry,
@@ -252,7 +237,7 @@ const compactCalls = (plan) => (entry) => pipe(Option.fromUndefinedOr(plan.byMes
252
237
  const leaveOut = (plan) => (entry) => Option.liftPredicate(Option.none(), () => !pinnedEntry(plan, entry) && Predicate.isUndefined(entry.tool_calls));
253
238
  const callsOf = (entry) => Option.getOrElse(Option.fromUndefinedOr(entry.tool_calls), () => []);
254
239
  const stringCalls = (entry) => pipe(callsOf(entry), Array.filter(Predicate.isString));
255
- const foldable = (plan, entry) => !pinnedEntry(plan, entry) && String$1.isEmpty(entry.text) && pipe(Array.head(callsOf(entry)), Option.exists(Predicate.isString));
240
+ const foldable = (plan, entry) => !pinnedEntry(plan, entry) && String$2.isEmpty(entry.text) && pipe(Array.head(callsOf(entry)), Option.exists(Predicate.isString));
256
241
  const mergedRun = (group) => {
257
242
  const first = Array.headNonEmpty(group);
258
243
  if (group.length === ONE) return first;
@@ -290,7 +275,7 @@ const throughStages = (plan, fitting, stages) => Option.match(Array.head(stages)
290
275
  });
291
276
  const jsonText = (value) => Option.getOrElse(jsonOf(value), () => "");
292
277
  const planOf = (messages, calls, options) => {
293
- const goal = pipe(Option.liftPredicate(options.goal, String$1.isNonEmpty), Option.getOrElse(() => goalFromMessages(messages)));
278
+ const goal = pipe(Option.liftPredicate(options.goal, String$2.isNonEmpty), Option.getOrElse(() => goalFromMessages(messages)));
294
279
  const stateOf = (history) => ({
295
280
  context: STATE_CONTEXT,
296
281
  goal,
@@ -316,14 +301,14 @@ const fitState = (messages, calls, options) => {
316
301
  };
317
302
  // src/shared/lib/owner-command.ts
318
303
  const OWNER_BODIES = [/<message\b[^>]*\bfrom="human"[^>]*\btrust="principal"[^>]*>(?<body>[\s\S]*?)<\/message>/gu, /<cited\b[^>]*\bauthor="user"[^>]*>(?<body>[\s\S]*?)<\/cited>/gu];
319
- const bodiesOf = (prompt) => pipe(OWNER_BODIES, Array.flatMap((pattern) => Array.fromIterable(pipe(prompt, String$1.matchAll(pattern)))), Array.map((found) => pipe(Option.fromUndefinedOr(found.groups), Option.flatMap((groups) => Option.fromUndefinedOr(groups["body"])))), Array.getSomes);
320
- const argumentsAfter = (text) => (command) => pipe(Option.some(String$1.trimStart(text)), Option.filter(String$1.startsWith(command)), Option.map((typed) => String$1.slice(command.length)(typed)), Option.filter((rest) => String$1.isEmpty(rest) || /^\s/u.test(rest)), Option.map(String$1.trim));
304
+ const bodiesOf = (prompt) => pipe(OWNER_BODIES, Array.flatMap((pattern) => Array.fromIterable(pipe(prompt, String$2.matchAll(pattern)))), Array.map((found) => pipe(Option.fromUndefinedOr(found.groups), Option.flatMap((groups) => Option.fromUndefinedOr(groups["body"])))), Array.getSomes);
305
+ const argumentsAfter = (text) => (command) => pipe(Option.some(String$2.trimStart(text)), Option.filter(String$2.startsWith(command)), Option.map((typed) => String$2.slice(command.length)(typed)), Option.filter((rest) => String$2.isEmpty(rest) || /^\s/u.test(rest)), Option.map(String$2.trim));
321
306
  const typedIn = (commands) => (text) => Array.findFirst(commands, argumentsAfter(text));
322
307
  const ownerBody = (commands) => (prompt) => pipe(bodiesOf(prompt), Array.map(typedIn(commands)), Array.getSomes, Array.last);
323
308
  const ownerCommand = (prompt, commands) => Option.orElse(typedIn(commands)(prompt), () => ownerBody(commands)(prompt));
324
309
  // src/shared/lib/session-switch.ts
325
310
  const OFF = "disable";
326
- const turnsOn = (args) => !pipe(String$1.split(args, /\s+/u), Array.head, Option.exists((word) => word === OFF));
311
+ const turnsOn = (args) => !pipe(String$2.split(args, /\s+/u), Array.head, Option.exists((word) => word === OFF));
327
312
  const ownerSwitch = (prompt, commands) => Option.map(ownerCommand(prompt, commands), turnsOn);
328
313
  const blank = Schema.String.pipe(Schema.withDecodingDefaultKey(Effect.succeed("")));
329
314
  const OwnerPrompt = Schema.Struct({
@@ -351,14 +336,14 @@ const switchSession = Effect.fn("switchSession")(function* switchSession(name, s
351
336
  /** @internal */
352
337
  const sessionSwitchedOn = Effect.fn("sessionSwitchedOn")(function* sessionSwitchedOn(name, session) {
353
338
  const fs = yield* FileSystem.FileSystem;
354
- if (String$1.isEmpty(session)) return false;
339
+ if (String$2.isEmpty(session)) return false;
355
340
  const directory = yield* directoryOf(name);
356
341
  const marker = yield* markerOf(directory, session);
357
342
  return yield* fs.exists(marker);
358
343
  }, Effect.orElseSucceed(() => false));
359
344
  /** @internal */
360
345
  const followOwnerSwitch = Effect.fn("followOwnerSwitch")(function* followOwnerSwitch(input, name, commands) {
361
- if (String$1.isEmpty(input.session_id)) return;
346
+ if (String$2.isEmpty(input.session_id)) return;
362
347
  yield* Option.match(ownerSwitch(input.prompt, commands), {
363
348
  onNone: () => Effect.void,
364
349
  onSome: (on) => switchSession(name, input.session_id, on)
@@ -372,7 +357,7 @@ const InstalledEntry = Schema.Struct({
372
357
  });
373
358
  const InstalledPlugins = Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(InstalledEntry)) });
374
359
  const decodeInstalled = Schema.decodeUnknownEffect(Schema.fromJsonString(InstalledPlugins));
375
- const flattened = (installed) => pipe(Record.toEntries(installed.plugins), Array.flatMap(([id, entries]) => pipe(entries, Array.map((entry) => ({
360
+ const flattened = (installed) => pipe(Record$1.toEntries(installed.plugins), Array.flatMap(([id, entries]) => pipe(entries, Array.map((entry) => ({
376
361
  id,
377
362
  installPath: entry.installPath,
378
363
  version: entry.version,
@@ -398,8 +383,8 @@ const dataCollection = (allowTraining) => {
398
383
  return "deny";
399
384
  };
400
385
  const jevBackend = (settings, origin) => {
401
- const model = pipe(Option.liftPredicate(settings.openRouterModel, String$1.isNonEmpty), Option.getOrElse(() => DEFAULT_OPENROUTER_MODEL));
402
- const session = pipe(Option.liftPredicate(origin.sessionId, String$1.isNonEmpty), Option.match({
386
+ const model = pipe(Option.liftPredicate(settings.openRouterModel, String$2.isNonEmpty), Option.getOrElse(() => DEFAULT_OPENROUTER_MODEL));
387
+ const session = pipe(Option.liftPredicate(origin.sessionId, String$2.isNonEmpty), Option.match({
403
388
  onNone: () => ({}),
404
389
  onSome: (id) => ({ session_id: id })
405
390
  }));
@@ -413,7 +398,7 @@ const jevBackend = (settings, origin) => {
413
398
  ...session
414
399
  },
415
400
  headers: settings.attribution,
416
- textState: String$1.startsWith(TEXT_STATE_PREFIX)(model)
401
+ textState: String$2.startsWith(TEXT_STATE_PREFIX)(model)
417
402
  };
418
403
  };
419
404
  const sectionOf = ([key, value]) => {
@@ -421,7 +406,7 @@ const sectionOf = ([key, value]) => {
421
406
  };
422
407
  const stateFor = (backend, state) => {
423
408
  if (!backend.textState) return state;
424
- return pipe(Record.toEntries(state), Array.map(sectionOf), Array.join("\n\n"));
409
+ return pipe(Record$1.toEntries(state), Array.map(sectionOf), Array.join("\n\n"));
425
410
  };
426
411
  export { CACHE_DIRECTORY_NAME, CacheRootError, HistoryTooLarge, HookBlocked, OwnerPrompt, blockHook, cacheRootEffect, collectToolCalls, estimateTokens, fitState, followOwnerSwitch, installedPlugins, isRecord, jevBackend, placeOf, readHookInput, runHook, runHookWith, sessionSwitchedOn, stateFor, writeHookOutput };
427
412
 
@@ -1 +1 @@
1
- {"version":3,"file":"plugin-kit.mjs","names":["taggedError","taggedError","Arr","RecordSchema","StringSchema","ONE","encodeJson","Str","Arr","Rec","ONE","Str","Arr","Num","ONE","Arr","Num","Str","Arr","Arr","Str","Str","Arr","Rec","Arr","Str","Rec","Arr"],"sources":["../src/features/run-main/model/hook-io.ts","../src/features/run-main/model/run-hook.ts","../src/shared/lib/cache.ts","../src/shared/lib/record.ts","../src/features/fit-history/model/calls.ts","../src/shared/lib/tokens.ts","../src/features/fit-history/model/fitting.ts","../src/features/fit-history/model/state.ts","../src/shared/lib/owner-command.ts","../src/shared/lib/session-switch.ts","../src/shared/lib/installed-plugins.ts","../src/shared/lib/jev-backend.ts"],"sourcesContent":["import { Effect, Runtime, Schema, Stdio, Stream } from \"effect\";\n\nconst EXIT_BLOCKING = 2;\n\nconst taggedError = Schema.TaggedError;\n\n/** @internal */\nexport class HookBlocked extends taggedError<HookBlocked, { readonly brand: unique symbol }>()(\n \"HookBlocked\",\n { reason: Schema.String },\n) {\n public override readonly [Runtime.errorExitCode] = EXIT_BLOCKING;\n public override readonly [Runtime.errorReported] = false;\n}\n\n/** @internal */\nexport const isHookBlocked = Schema.is(HookBlocked);\n\n/** @internal */\nexport const blockHook = (reason: string): Effect.Effect<never, HookBlocked> =>\n Effect.fail(HookBlocked.make({ reason }));\n\n/** @internal */\nexport const readStdin: Effect.Effect<string, never, Stdio.Stdio> = Effect.gen(\n function* readStdin() {\n const stdio = yield* Stdio.Stdio;\n return yield* stdio.stdin.pipe(Stream.decodeText, Stream.mkString, Effect.orDie);\n },\n);\n\n/** @internal */\nexport const readHookInput = <Codec extends Schema.Top>(\n schema: Codec,\n): Effect.Effect<Codec[\"Type\"], Schema.SchemaError, Stdio.Stdio | Codec[\"DecodingServices\"]> =>\n Effect.gen(function* read() {\n const text = yield* readStdin;\n const json = Schema.fromJsonString(schema);\n return yield* Schema.decodeEffect(json)(text);\n });\n\n/** @internal */\nexport const writeStdout = (text: string): Effect.Effect<void, never, Stdio.Stdio> =>\n Effect.gen(function* toStdout() {\n const stdio = yield* Stdio.Stdio;\n yield* Stream.make(text).pipe(Stream.run(stdio.stdout()), Effect.orDie);\n });\n\n/** @internal */\nexport const writeStderr = (text: string): Effect.Effect<void, never, Stdio.Stdio> =>\n Effect.gen(function* toStderr() {\n const stdio = yield* Stdio.Stdio;\n yield* Stream.make(text).pipe(Stream.run(stdio.stderr()), Effect.orDie);\n });\n\n/** @internal */\nexport const writeHookOutput =\n <Codec extends Schema.Top>(schema: Codec) =>\n (value: Codec[\"Type\"]): Effect.Effect<void, never, Stdio.Stdio | Codec[\"EncodingServices\"]> =>\n Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.orDie,\n Effect.flatMap(writeStdout),\n );\n","import { Cause, Effect, Layer, Option } from \"effect\";\nimport type { Stdio } from \"effect\";\n\nimport { isHookBlocked, writeStderr } from \"./hook-io.ts\";\nimport type { HookBlocked } from \"./hook-io.ts\";\nimport { runMainWith } from \"./run-main.ts\";\nimport type { Platform, Run } from \"./run-main.ts\";\n\nconst blockedIn = <Failure>(cause: Cause.Cause<Failure>): Option.Option<HookBlocked> =>\n Cause.findErrorOption(cause).pipe(\n Option.filter((error): error is Failure & HookBlocked => isHookBlocked(error)),\n );\n\nconst reportBlocked = <Failure>(\n cause: Cause.Cause<Failure>,\n): Effect.Effect<void, never, Stdio.Stdio> =>\n cause.pipe(\n blockedIn,\n Option.match({\n onNone: () => Effect.void,\n onSome: (blocked) => writeStderr(`${blocked.reason}\\n`),\n }),\n );\n\n/** @internal */\nexport const runHookWith =\n <Provided, LayerFailure>({\n serviceName,\n services,\n }: Readonly<{\n serviceName: string;\n services: Layer.Layer<Provided, LayerFailure, Platform>;\n }>): Run<Provided> =>\n (program) => {\n runMainWith({ serviceName, services })(program.pipe(Effect.tapCause(reportBlocked)));\n };\n\n/** @internal */\nexport const runHook = (serviceName: string): Run<never> =>\n runHookWith({ serviceName, services: Layer.empty });\n","import { Array as Arr, Config, Effect, Option, Schema, pipe } from \"effect\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class CacheRootError extends taggedError<\n CacheRootError,\n { readonly brand: unique symbol }\n>()(\"CacheRootError\", { message: Schema.String }) {}\n\nconst SEPARATOR = \"/\";\nexport const CACHE_DIRECTORY_NAME = \".cache\";\n\nconst variable = (name: string): Effect.Effect<Option.Option<string>> =>\n Config.option(Config.NonEmptyString(name)).pipe(Effect.orElseSucceed(Option.none));\n\nconst baseDirectory: Effect.Effect<Option.Option<string>> = Effect.gen(function* baseDirectory() {\n const cacheHome = yield* variable(\"XDG_CACHE_HOME\");\n const home = yield* variable(\"HOME\");\n const profile = yield* variable(\"USERPROFILE\");\n return pipe(\n cacheHome,\n Option.orElse(() =>\n pipe(\n Option.orElse(home, () => profile),\n Option.map((directory) => `${directory}${SEPARATOR}${CACHE_DIRECTORY_NAME}`),\n ),\n ),\n );\n});\n\nexport const cacheRootEffect = (\n segments: readonly string[],\n): Effect.Effect<string, CacheRootError> =>\n baseDirectory.pipe(\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.fail(CacheRootError.make({ message: \"set XDG_CACHE_HOME or HOME\" })),\n onSome: (base) => Effect.succeed(pipe([base, ...segments], Arr.join(SEPARATOR))),\n }),\n ),\n );\n","import { Record as RecordSchema, String as StringSchema, Unknown, is } from \"effect/Schema\";\n\nexport const isRecord = is(RecordSchema(StringSchema, Unknown));\n","import { Array as Arr, Option, Record as Rec, Schema, String as Str, pipe } from \"effect\";\n\nimport type { HistoryEntry, HistoryToolCall, Message, ToolCall } from \"./types.ts\";\n\nconst FIRST = 0;\nconst ONE = 1;\nconst ELLIPSIS = \"…\";\nconst VALUE_CHARS = 200;\nconst COMPACT_INPUT_CHARS = 60;\nconst SPACES = /\\s+/gu;\nconst encodeJson = Schema.encodeOption(Schema.fromJsonString(Schema.Unknown));\n\nexport const jsonOf = (value: unknown): Option.Option<string> => encodeJson(value);\n\nexport const truncate = (text: string, limit: number): string => {\n if (Str.length(text) <= limit) {\n return text;\n }\n return `${Str.slice(FIRST, Math.max(FIRST, limit - ONE))(text)}${ELLIPSIS}`;\n};\n\nexport const isPinned = (index: number, total: number, preserveRecentMessages: number): boolean =>\n index === FIRST || index >= total - preserveRecentMessages;\n\ninterface Found {\n readonly index: number;\n readonly chars: number;\n readonly isError: boolean;\n}\n\nconst resultsOf = (messages: readonly Message[]): ReadonlyMap<string, Found> =>\n new Map(\n pipe(\n messages,\n Arr.flatMap((message, index) =>\n pipe(\n message.toolResults,\n Arr.map(\n (result) =>\n [\n result.tool_use_id,\n { index, chars: Str.length(result.text), isError: result.isError },\n ] as const,\n ),\n ),\n ),\n ),\n );\n\nexport const collectToolCalls = (\n messages: readonly Message[],\n preserveRecentMessages: number,\n): readonly ToolCall[] => {\n const results = resultsOf(messages);\n const pinned = (index: number): boolean =>\n isPinned(index, messages.length, preserveRecentMessages);\n return pipe(\n messages,\n Arr.flatMap((message, callIndex) =>\n pipe(\n message.toolUses,\n Arr.flatMap((tool) =>\n pipe(\n Option.fromUndefinedOr(results.get(tool.tool_use_id)),\n Option.map((found) => ({ tool, callIndex, found })),\n Option.toArray,\n ),\n ),\n ),\n ),\n Arr.map(({ tool, callIndex, found }, index) => ({\n id: `t${String(index + ONE)}`,\n tool_use_id: tool.tool_use_id,\n tool: tool.tool,\n input: tool.input,\n callIndex,\n resultIndex: found.index,\n resultChars: found.chars,\n isError: found.isError,\n pinned: pinned(callIndex) || pinned(found.index),\n })),\n );\n};\n\nexport const inputText = (input: Readonly<Record<string, unknown>>, limit: number): string =>\n truncate(\n Option.getOrElse(jsonOf(input), () => \"[unserializable input]\"),\n limit,\n );\n\nconst outcomeOf = (call: ToolCall): string => {\n if (call.isError) {\n return \"error\";\n }\n return \"ok\";\n};\n\nconst resultNote = (call: ToolCall): string =>\n `${outcomeOf(call)}, ${String(call.resultChars)} chars (omitted)`;\n\nconst valueText = ([key, value]: readonly [string, unknown]): string => {\n const text = pipe(\n Option.liftPredicate(value, (raw): raw is string => typeof raw === \"string\"),\n Option.getOrElse(() => inputText({ [key]: value }, VALUE_CHARS)),\n );\n return `${key}=${Str.replaceAll(SPACES, \" \")(text)}`;\n};\n\nexport const compactCall = (call: ToolCall): string => {\n const input = pipe(Rec.toEntries(call.input), Arr.map(valueText), Arr.join(\" \"));\n return `${call.id} ${call.tool} ${truncate(input, COMPACT_INPUT_CHARS)} → ${outcomeOf(call)} ${String(call.resultChars)}ch`;\n};\n\nexport const callsByMessage = (\n calls: readonly ToolCall[],\n): ReadonlyMap<number, readonly ToolCall[]> =>\n new Map(\n pipe(\n calls,\n Arr.groupBy((call) => String(call.callIndex)),\n Rec.toEntries,\n Arr.map(([index, own]) => [Number(index), own] as const),\n ),\n );\n\nconst historyCallOf =\n (inputChars: number) =>\n (call: ToolCall): HistoryToolCall => ({\n id: call.id,\n tool: call.tool,\n input: inputText(call.input, inputChars),\n result: resultNote(call),\n });\n\nexport const historyEntries = (\n messages: readonly Message[],\n calls: readonly ToolCall[],\n inputChars: number,\n): readonly HistoryEntry[] => {\n const byMessage = callsByMessage(calls);\n return pipe(\n messages,\n Arr.flatMap((message, index): readonly HistoryEntry[] => {\n const own = Option.getOrElse(Option.fromUndefinedOr(byMessage.get(index)), () => []);\n const toolCalls = pipe(own, Arr.map(historyCallOf(inputChars)));\n const entry = { index, role: message.role, text: message.text };\n if (Arr.isReadonlyArrayNonEmpty(toolCalls)) {\n return [{ ...entry, tool_calls: toolCalls }];\n }\n if (Str.isEmpty(Str.trim(message.text))) {\n return [];\n }\n return [entry];\n }),\n );\n};\n","import { Array as Arr, Number as Num, Option, String as Str, pipe } from \"effect\";\n\nimport { groupOf } from \"./match-groups.ts\";\n\nconst PIECES = /(?<alpha>[A-Za-z]+)|(?<digits>\\d+)|(?<other>[^\\sA-Za-z\\d])/gu;\nconst DIGITS_PER_TOKEN = 2;\nconst LETTERS_PER_TOKEN = 6;\nconst SYMBOL_TOKENS = 0.9;\nconst ONE = 1;\n\nconst pieceTokens = (match: RegExpMatchArray): number =>\n pipe(\n groupOf(\"digits\")(match),\n Option.map((digits) => Str.length(digits) / DIGITS_PER_TOKEN),\n Option.orElse(() =>\n Option.map(\n groupOf(\"alpha\")(match),\n (alpha) => ONE + Math.floor((Str.length(alpha) - ONE) / LETTERS_PER_TOKEN),\n ),\n ),\n Option.getOrElse(() => SYMBOL_TOKENS),\n );\n\nconst matchesOf = (pattern: RegExp, text: string): readonly RegExpMatchArray[] =>\n Arr.fromIterable(Str.matchAll(pattern)(text));\n\nexport const estimateTokens = (text: string): number => {\n const pieces = pipe(matchesOf(PIECES, text), Arr.map(pieceTokens));\n return Math.ceil(Num.sumAll(pieces));\n};\n","import { Array as Arr, Number as Num, Option, pipe } from \"effect\";\n\nimport { estimateTokens } from \"#/shared/lib/tokens.ts\";\n\nimport { isPinned, jsonOf } from \"./calls.ts\";\nimport type {\n CompactionState,\n FitOptions,\n FittedState,\n HistoryEntry,\n Message,\n ToolCall,\n} from \"./types.ts\";\n\nconst ONE = 1;\nconst NONE = 0;\n\nexport const entryTokens = (entry: HistoryEntry): number =>\n jsonOf(entry).pipe(\n Option.getOrElse(() => \"\"),\n estimateTokens,\n ) + ONE;\n\nexport interface Fitting {\n readonly history: readonly Option.Option<HistoryEntry>[];\n readonly perEntry: readonly number[];\n readonly tokens: number;\n}\n\nexport interface Plan {\n readonly messages: readonly Message[];\n readonly calls: readonly ToolCall[];\n readonly options: FitOptions;\n readonly stateOf: (history: readonly HistoryEntry[]) => CompactionState;\n readonly baseTokens: number;\n readonly byMessage: ReadonlyMap<number, readonly ToolCall[]>;\n}\n\nexport type Change = (entry: HistoryEntry) => Option.Option<Option.Option<HistoryEntry>>;\n\nexport const fittingOf = (plan: Plan, history: readonly HistoryEntry[]): Fitting => {\n const perEntry = pipe(history, Arr.map(entryTokens));\n return {\n history: pipe(history, Arr.map(Option.some)),\n perEntry,\n tokens: plan.baseTokens + Num.sumAll(perEntry),\n };\n};\n\nexport const kept = (fitting: Fitting): readonly HistoryEntry[] => Arr.getSomes(fitting.history);\n\nexport const fits = (plan: Plan, fitting: Fitting): boolean =>\n fitting.tokens <= plan.options.maxStateTokens;\n\nexport const fitted = (plan: Plan, fitting: Fitting, stage: string): FittedState => ({\n state: plan.stateOf(kept(fitting)),\n tokens: fitting.tokens,\n stage,\n});\n\nexport const pinnedEntry = (plan: Plan, entry: HistoryEntry): boolean =>\n isPinned(entry.index, plan.messages.length, plan.options.preserveRecentMessages);\n\nconst orderOf = (plan: Plan, fitting: Fitting): readonly number[] => {\n const present = pipe(\n fitting.history,\n Arr.flatMap((entry, index) =>\n pipe(\n entry,\n Option.map((value) => [index, pinnedEntry(plan, value)] as const),\n Option.toArray,\n ),\n ),\n );\n const loose = pipe(\n present,\n Arr.filter(([, pinned]) => !pinned),\n );\n const pinned = pipe(\n present,\n Arr.filter(([, isPinnedEntry]) => isPinnedEntry),\n );\n return pipe(\n [...loose, ...pinned],\n Arr.map(([index]) => index),\n );\n};\n\ninterface Step {\n readonly index: number;\n readonly entry: Option.Option<HistoryEntry>;\n readonly tokens: number;\n}\n\nconst stepOf =\n (fitting: Fitting, change: Change) =>\n (index: number): Option.Option<Step> =>\n pipe(\n Option.flatten(Option.fromUndefinedOr(fitting.history[index])),\n Option.flatMap(change),\n Option.map((entry) => ({\n index,\n entry,\n tokens: Option.match(entry, { onNone: () => NONE, onSome: entryTokens }),\n })),\n );\n\nconst applied = (fitting: Fitting, steps: readonly Step[]): Fitting => {\n const byIndex = new Map(\n pipe(\n steps,\n Arr.map((step) => [step.index, step] as const),\n ),\n );\n const pick = <Value>(index: number, value: Value, of: (step: Step) => Value): Value =>\n Option.match(Option.fromUndefinedOr(byIndex.get(index)), { onNone: () => value, onSome: of });\n const history = pipe(\n fitting.history,\n Arr.map((entry, index) => pick(index, entry, (step) => step.entry)),\n );\n const perEntry = pipe(\n fitting.perEntry,\n Arr.map((tokens, index) => pick(index, tokens, (step) => step.tokens)),\n );\n const delta = Num.sumAll(\n pipe(\n steps,\n Arr.map(\n (step) => step.tokens - Option.getOrElse(Arr.get(fitting.perEntry, step.index), () => NONE),\n ),\n ),\n );\n return { history, perEntry, tokens: fitting.tokens + delta };\n};\n\nexport const staged = (\n plan: Plan,\n fitting: Fitting,\n change: Change,\n): readonly [Fitting, boolean] => {\n const steps = pipe(\n orderOf(plan, fitting),\n Arr.flatMap((index) => Option.toArray(stepOf(fitting, change)(index))),\n );\n const totals = pipe(\n steps,\n Arr.scan(\n fitting.tokens,\n (tokens, step) =>\n tokens + step.tokens - Option.getOrElse(Arr.get(fitting.perEntry, step.index), () => NONE),\n ),\n Arr.drop(ONE),\n );\n return Option.match(\n Arr.findFirstIndex(totals, (tokens) => tokens <= plan.options.maxStateTokens),\n {\n onNone: () => [applied(fitting, steps), false] as const,\n onSome: (at) => [applied(fitting, Arr.take(steps, at + ONE)), true] as const,\n },\n );\n};\n","import {\n Array as Arr,\n Effect,\n Option,\n Predicate,\n Result,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport { estimateTokens } from \"#/shared/lib/tokens.ts\";\n\nimport { callsByMessage, compactCall, historyEntries, jsonOf, truncate } from \"./calls.ts\";\nimport { fits, fitted, fittingOf, kept, pinnedEntry, staged } from \"./fitting.ts\";\nimport type { Change, Fitting, Plan } from \"./fitting.ts\";\nimport type {\n CompactionState,\n FitOptions,\n FittedState,\n HistoryEntry,\n HistoryToolCall,\n Message,\n ToolCall,\n} from \"./types.ts\";\n\nexport const STATE_CONTEXT =\n \"A coding assistant conversation is being compacted to free context. `history` is the whole conversation so far, oldest first; tool outputs are replaced by a short `result` note and long texts may be abridged. Each question asks whether one tool call, or the full output of that call, still needs to stay in the history verbatim. Whatever is not kept is deleted permanently, but the assistant can always re-run a tool or re-read a file.\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class HistoryTooLarge extends taggedError<\n HistoryTooLarge,\n { readonly brand: unique symbol }\n>()(\"HistoryTooLarge\", { reason: Schema.String }) {}\n\nconst FULL_INPUT_CHARS = 1000;\nconst SHORT_INPUT_CHARS = 200;\nconst SHORTEST_INPUT_CHARS = 60;\nconst SHORTER_INPUT_CHARS = [SHORT_INPUT_CHARS, SHORTEST_INPUT_CHARS] as const;\nconst TEXT_HEAD = 400;\nconst TEXT_TAIL = 150;\nconst ABRIDGE_MARGIN = 40;\nconst RECENT_GOALS = 3;\nconst GOAL_CHARS = 500;\nconst ONE = 1;\n\nconst abridge = (text: string): string => {\n const omitted = Str.length(text) - TEXT_HEAD - TEXT_TAIL;\n return `${Str.takeLeft(TEXT_HEAD)(text)}\\n[… ${String(omitted)} chars omitted …]\\n${Str.takeRight(TEXT_TAIL)(text)}`;\n};\n\nexport const goalFromMessages = (messages: readonly Message[]): string =>\n pipe(\n messages,\n Arr.filter(\n (message) =>\n message.role === \"user\" &&\n Str.isNonEmpty(Str.trim(message.text)) &&\n Arr.isReadonlyArrayEmpty(message.toolResults),\n ),\n Arr.takeRight(RECENT_GOALS),\n Arr.map((message) => truncate(message.text, GOAL_CHARS)),\n Arr.join(\"\\n\"),\n );\n\nconst abridgeText: Change = (entry: HistoryEntry) =>\n Option.liftPredicate(\n Option.some({ ...entry, text: abridge(entry.text) }),\n () => Str.length(entry.text) > TEXT_HEAD + TEXT_TAIL + ABRIDGE_MARGIN,\n );\n\nconst collapseText =\n (plan: Plan): Change =>\n (entry: HistoryEntry) => {\n const original = pipe(\n Arr.get(plan.messages, entry.index),\n Option.map((message) => Str.length(message.text)),\n Option.getOrElse(() => Str.length(entry.text)),\n );\n return Option.liftPredicate(\n Option.some({ ...entry, text: `[… ${String(original)} chars omitted …]` }),\n () => !pinnedEntry(plan, entry) && Str.isNonEmpty(entry.text),\n );\n };\n\nconst compactCalls =\n (plan: Plan): Change =>\n (entry: HistoryEntry) =>\n pipe(\n Option.fromUndefinedOr(plan.byMessage.get(entry.index)),\n Option.filter(() => !pinnedEntry(plan, entry)),\n Option.map((own) => Option.some({ ...entry, tool_calls: pipe(own, Arr.map(compactCall)) })),\n );\n\nconst leaveOut =\n (plan: Plan): Change =>\n (entry: HistoryEntry) =>\n Option.liftPredicate(\n Option.none<HistoryEntry>(),\n () => !pinnedEntry(plan, entry) && Predicate.isUndefined(entry.tool_calls),\n );\n\nconst callsOf = (entry: HistoryEntry): readonly (HistoryToolCall | string)[] =>\n Option.getOrElse(Option.fromUndefinedOr(entry.tool_calls), () => []);\n\nconst stringCalls = (entry: HistoryEntry): readonly string[] =>\n pipe(callsOf(entry), Arr.filter(Predicate.isString));\n\nconst foldable = (plan: Plan, entry: HistoryEntry): boolean =>\n !pinnedEntry(plan, entry) &&\n Str.isEmpty(entry.text) &&\n pipe(Arr.head(callsOf(entry)), Option.exists(Predicate.isString));\n\nconst mergedRun = (group: Arr.NonEmptyReadonlyArray<HistoryEntry>): HistoryEntry => {\n const first = Arr.headNonEmpty(group);\n if (group.length === ONE) {\n return first;\n }\n return { ...first, tool_calls: pipe(group, Arr.flatMap(stringCalls)) };\n};\n\nconst mergeRuns = (plan: Plan, history: readonly HistoryEntry[]): readonly HistoryEntry[] => {\n if (!Arr.isReadonlyArrayNonEmpty(history)) {\n return [];\n }\n return pipe(\n Arr.groupWith(\n history,\n (left, right) => foldable(plan, left) && foldable(plan, right) && left.role === right.role,\n ),\n Arr.map(mergedRun),\n );\n};\n\ntype Staged = readonly [Fitting, boolean];\n\ntype Stage = readonly [string, (fitting: Fitting) => Staged];\n\nconst rebuilt = (plan: Plan, inputChars: number) => (): readonly [Fitting, boolean] => {\n const fitting = fittingOf(plan, historyEntries(plan.messages, plan.calls, inputChars));\n return [fitting, fits(plan, fitting)];\n};\n\nconst stagesOf = (plan: Plan): readonly Stage[] => [\n ...pipe(\n SHORTER_INPUT_CHARS,\n Arr.map((limit): Stage => [`inputs<=${String(limit)}`, rebuilt(plan, limit)]),\n ),\n [\"texts abridged\", (fitting): Staged => staged(plan, fitting, abridgeText)],\n [\"old messages collapsed\", (fitting): Staged => staged(plan, fitting, collapseText(plan))],\n [\"old calls compacted\", (fitting): Staged => staged(plan, fitting, compactCalls(plan))],\n [\"old messages left out\", (fitting): Staged => staged(plan, fitting, leaveOut(plan))],\n [\n \"old calls merged\",\n (fitting): Staged => {\n const merged = fittingOf(plan, mergeRuns(plan, kept(fitting)));\n return [merged, fits(plan, merged)];\n },\n ],\n];\n\nconst throughStages = (\n plan: Plan,\n fitting: Fitting,\n stages: readonly Stage[],\n): Result.Result<FittedState, Fitting> =>\n Option.match(Arr.head(stages), {\n onNone: () => Result.fail(fitting),\n onSome: ([name, run]) => {\n const [next, done] = run(fitting);\n if (done) {\n return Result.succeed(fitted(plan, next, name));\n }\n return throughStages(plan, next, Arr.drop(stages, ONE));\n },\n });\n\nconst jsonText = (value: unknown): string => Option.getOrElse(jsonOf(value), () => \"\");\n\nconst planOf = (\n messages: readonly Message[],\n calls: readonly ToolCall[],\n options: FitOptions,\n): Plan => {\n const goal = pipe(\n Option.liftPredicate(options.goal, Str.isNonEmpty),\n Option.getOrElse(() => goalFromMessages(messages)),\n );\n const stateOf = (history: readonly HistoryEntry[]): CompactionState => ({\n context: STATE_CONTEXT,\n goal,\n history,\n });\n return {\n messages,\n calls,\n options,\n stateOf,\n baseTokens: estimateTokens(jsonText(stateOf([]))),\n byMessage: callsByMessage(calls),\n };\n};\n\nexport const fitState = (\n messages: readonly Message[],\n calls: readonly ToolCall[],\n options: FitOptions,\n): Effect.Effect<FittedState, HistoryTooLarge> => {\n const plan = planOf(messages, calls, options);\n const full = fittingOf(plan, historyEntries(messages, calls, FULL_INPUT_CHARS));\n if (fits(plan, full)) {\n return Effect.succeed(fitted(plan, full, \"full\"));\n }\n return Result.match(throughStages(plan, full, stagesOf(plan)), {\n onSuccess: Effect.succeed,\n onFailure: (last) =>\n Effect.fail(\n HistoryTooLarge.make({\n reason: `history too large for Jev (~${String(last.tokens)} tokens after truncation, limit ${String(options.maxStateTokens)})`,\n }),\n ),\n });\n};\n","import { Array as Arr, Option, String as Str, pipe } from \"effect\";\n\nconst OWNER_BODIES: readonly RegExp[] = [\n /<message\\b[^>]*\\bfrom=\"human\"[^>]*\\btrust=\"principal\"[^>]*>(?<body>[\\s\\S]*?)<\\/message>/gu,\n /<cited\\b[^>]*\\bauthor=\"user\"[^>]*>(?<body>[\\s\\S]*?)<\\/cited>/gu,\n];\n\nconst bodiesOf = (prompt: string): readonly string[] =>\n pipe(\n OWNER_BODIES,\n Arr.flatMap((pattern) => Arr.fromIterable(pipe(prompt, Str.matchAll(pattern)))),\n Arr.map((found) =>\n pipe(\n Option.fromUndefinedOr(found.groups),\n Option.flatMap((groups) => Option.fromUndefinedOr(groups[\"body\"])),\n ),\n ),\n Arr.getSomes,\n );\n\nconst argumentsAfter =\n (text: string) =>\n (command: string): Option.Option<string> =>\n pipe(\n Option.some(Str.trimStart(text)),\n Option.filter(Str.startsWith(command)),\n Option.map((typed) => Str.slice(command.length)(typed)),\n Option.filter((rest) => Str.isEmpty(rest) || /^\\s/u.test(rest)),\n Option.map(Str.trim),\n );\n\nconst typedIn =\n (commands: readonly string[]) =>\n (text: string): Option.Option<string> =>\n Arr.findFirst(commands, argumentsAfter(text));\n\nconst ownerBody =\n (commands: readonly string[]) =>\n (prompt: string): Option.Option<string> =>\n pipe(bodiesOf(prompt), Arr.map(typedIn(commands)), Arr.getSomes, Arr.last);\n\nexport const ownerCommand = (prompt: string, commands: readonly string[]): Option.Option<string> =>\n Option.orElse(typedIn(commands)(prompt), () => ownerBody(commands)(prompt));\n","import {\n Array as Arr,\n Config,\n Effect,\n FileSystem,\n Option,\n Path,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport { ownerCommand } from \"./owner-command.ts\";\n\nconst OFF = \"disable\";\n\nconst turnsOn = (args: string): boolean =>\n !pipe(\n Str.split(args, /\\s+/u),\n Arr.head,\n Option.exists((word) => word === OFF),\n );\n\nexport const ownerSwitch = (prompt: string, commands: readonly string[]): Option.Option<boolean> =>\n Option.map(ownerCommand(prompt, commands), turnsOn);\n\nconst blank = Schema.String.pipe(Schema.withDecodingDefaultKey(Effect.succeed(\"\")));\n\nexport const OwnerPrompt = Schema.Struct({ prompt: blank, session_id: blank });\n\nconst directoryOf = Effect.fn(\"directoryOf\")(function* directoryOf(name: string) {\n const path = yield* Path.Path;\n const data = yield* Config.NonEmptyString(\"CLAUDE_PLUGIN_DATA\");\n return path.join(data, name);\n});\n\nconst markerOf = Effect.fn(\"markerOf\")(function* markerOf(directory: string, session: string) {\n const path = yield* Path.Path;\n return path.join(directory, path.basename(session));\n});\n\n/** @internal */\nexport const switchSession = Effect.fn(\"switchSession\")(function* switchSession(\n name: string,\n session: string,\n on: boolean,\n) {\n const fs = yield* FileSystem.FileSystem;\n const directory = yield* directoryOf(name);\n const marker = yield* markerOf(directory, session);\n if (!on) {\n return yield* fs.remove(marker, { force: true });\n }\n yield* fs.makeDirectory(directory, { recursive: true });\n return yield* fs.writeFileString(marker, \"\");\n});\n\n/** @internal */\nexport const sessionSwitchedOn = Effect.fn(\"sessionSwitchedOn\")(\n function* sessionSwitchedOn(name: string, session: string) {\n const fs = yield* FileSystem.FileSystem;\n if (Str.isEmpty(session)) {\n return false;\n }\n const directory = yield* directoryOf(name);\n const marker = yield* markerOf(directory, session);\n return yield* fs.exists(marker);\n },\n Effect.orElseSucceed(() => false),\n);\n\n/** @internal */\nexport const followOwnerSwitch = Effect.fn(\"followOwnerSwitch\")(function* followOwnerSwitch(\n input: typeof OwnerPrompt.Type,\n name: string,\n commands: readonly string[],\n) {\n if (Str.isEmpty(input.session_id)) {\n return;\n }\n yield* Option.match(ownerSwitch(input.prompt, commands), {\n onNone: () => Effect.void,\n onSome: (on) => switchSession(name, input.session_id, on),\n });\n});\n","import { Array as Arr, Effect, FileSystem, Path, Record as Rec, Schema, pipe } from \"effect\";\n\nconst InstalledEntry = Schema.Struct({\n installPath: Schema.String,\n version: Schema.Unknown,\n gitCommitSha: Schema.Unknown,\n});\nconst InstalledPlugins = Schema.Struct({\n plugins: Schema.Record(Schema.String, Schema.Array(InstalledEntry)),\n});\nconst decodeInstalled = Schema.decodeUnknownEffect(Schema.fromJsonString(InstalledPlugins));\n\nexport interface InstalledPlugin {\n readonly id: string;\n readonly installPath: string;\n readonly version: unknown;\n readonly sha: unknown;\n}\n\nconst flattened = (installed: typeof InstalledPlugins.Type): readonly InstalledPlugin[] =>\n pipe(\n Rec.toEntries(installed.plugins),\n Arr.flatMap(([id, entries]) =>\n pipe(\n entries,\n Arr.map((entry) => ({\n id,\n installPath: entry.installPath,\n version: entry.version,\n sha: entry.gitCommitSha,\n })),\n ),\n ),\n );\n\n/** @internal */\nexport const installedPlugins = Effect.fn(\"installedPlugins\")(function* installedPlugins(\n home: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(home, \".claude\", \"plugins\", \"installed_plugins.json\");\n return yield* fs.readFileString(file).pipe(\n Effect.flatMap(decodeInstalled),\n Effect.map(flattened),\n Effect.orElseSucceed((): readonly InstalledPlugin[] => []),\n );\n});\n","import {\n Array as Arr,\n Option,\n Predicate,\n Record as Rec,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\n\nexport type Place = \"ci\" | \"cloud\" | \"local\";\n\nexport interface Origin {\n readonly place: Place;\n readonly project: string;\n readonly hook: string;\n readonly sessionId: string;\n}\n\nexport interface JevSettings {\n readonly openRouterKey: string;\n readonly openRouterModel: string;\n readonly allowTraining: boolean;\n readonly attribution: Readonly<Record<string, string>>;\n}\n\nexport interface JevBackend {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly model: string;\n readonly extra: Readonly<Record<string, unknown>>;\n readonly headers: Readonly<Record<string, string>>;\n readonly textState: boolean;\n}\n\nexport interface PlaceEnv {\n readonly githubActions: string;\n readonly remote: string;\n}\n\nexport type JevState = Readonly<Record<string, string>>;\n\nconst DEFAULT_OPENROUTER_MODEL = \"respan/span-01-lite\";\nconst TEXT_STATE_PREFIX = \"respan/\";\nconst encodeJson = Schema.encodeOption(Schema.fromJsonString(Schema.Unknown));\n\nexport const placeOf = (env: PlaceEnv): Place => {\n if (env.githubActions === \"true\") {\n return \"ci\";\n }\n if (env.remote === \"true\") {\n return \"cloud\";\n }\n return \"local\";\n};\n\nconst dataCollection = (allowTraining: boolean): string => {\n if (allowTraining) {\n return \"allow\";\n }\n return \"deny\";\n};\n\nexport const jevBackend = (settings: JevSettings, origin: Origin): JevBackend => {\n const model = pipe(\n Option.liftPredicate(settings.openRouterModel, Str.isNonEmpty),\n Option.getOrElse(() => DEFAULT_OPENROUTER_MODEL),\n );\n const session = pipe(\n Option.liftPredicate(origin.sessionId, Str.isNonEmpty),\n Option.match({ onNone: () => ({}), onSome: (id) => ({ session_id: id }) }),\n );\n return {\n apiKey: settings.openRouterKey,\n baseURL: \"https://openrouter.ai/api\",\n model,\n extra: {\n provider: { data_collection: dataCollection(settings.allowTraining) },\n user: `${origin.place}:${origin.project}:${origin.hook}`,\n ...session,\n },\n headers: settings.attribution,\n textState: Str.startsWith(TEXT_STATE_PREFIX)(model),\n };\n};\n\nconst sectionOf = ([key, value]: readonly [string, unknown]): string => {\n const text = pipe(\n Option.liftPredicate(value, Predicate.isString),\n Option.orElse(() => encodeJson(value)),\n Option.getOrElse(() => \"\"),\n );\n return `## ${key}\\n${text}`;\n};\n\nexport const stateFor = (backend: JevBackend, state: JevState): JevState | string => {\n if (!backend.textState) {\n return state;\n }\n return pipe(Rec.toEntries(state), Arr.map(sectionOf), Arr.join(\"\\n\\n\"));\n};\n"],"mappings":";;;;;AAEA,MAAM,gB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,aAAa,CAAC,KAAK,WAA+C;CAMtE,OAAO,MAAM,IAAI,IALJ,KACX,OAAO,cAAc,OAAO,UAAU,QAAQ,GAC9C,OAAO,aAAa,WAAW,KAAK,CAAC,GACrC,OAAO,gBAAgB,EAAE,CAEH;AAC1B;AAEA,MAAa,YAAY,SAAqB,UAAuC;CACnF,IAAI,CAAC,QAAQ,WACX,OAAO;CAET,OAAO,KAAKC,OAAI,UAAU,KAAK,GAAGC,MAAI,IAAI,SAAS,GAAGA,MAAI,KAAK,MAAM,CAAC;AACxE"}
1
+ {"version":3,"file":"plugin-kit.mjs","names":["taggedError","RecordSchema","StringSchema","ONE","encodeJson","Str","Arr","Rec","ONE","Str","Arr","Num","ONE","Arr","Num","Str","Arr","Arr","Str","Str","Arr","Rec","Arr","Str","Rec","Arr"],"sources":["../src/features/run-main/model/hook-io.ts","../src/features/run-main/model/run-hook.ts","../src/shared/lib/record.ts","../src/features/fit-history/model/calls.ts","../src/shared/lib/tokens.ts","../src/features/fit-history/model/fitting.ts","../src/features/fit-history/model/state.ts","../src/shared/lib/owner-command.ts","../src/shared/lib/session-switch.ts","../src/shared/lib/installed-plugins.ts","../src/shared/lib/jev-backend.ts"],"sourcesContent":["import { Effect, Runtime, Schema, Stdio, Stream } from \"effect\";\n\nconst EXIT_BLOCKING = 2;\n\nconst taggedError = Schema.TaggedError;\n\n/** @internal */\nexport class HookBlocked extends taggedError<HookBlocked, { readonly brand: unique symbol }>()(\n \"HookBlocked\",\n { reason: Schema.String },\n) {\n public override readonly [Runtime.errorExitCode] = EXIT_BLOCKING;\n public override readonly [Runtime.errorReported] = false;\n}\n\n/** @internal */\nexport const isHookBlocked = Schema.is(HookBlocked);\n\n/** @internal */\nexport const blockHook = (reason: string): Effect.Effect<never, HookBlocked> =>\n Effect.fail(HookBlocked.make({ reason }));\n\n/** @internal */\nexport const readStdin: Effect.Effect<string, never, Stdio.Stdio> = Effect.gen(\n function* readStdin() {\n const stdio = yield* Stdio.Stdio;\n return yield* stdio.stdin.pipe(Stream.decodeText, Stream.mkString, Effect.orDie);\n },\n);\n\n/** @internal */\nexport const readHookInput = <Codec extends Schema.Top>(\n schema: Codec,\n): Effect.Effect<Codec[\"Type\"], Schema.SchemaError, Stdio.Stdio | Codec[\"DecodingServices\"]> =>\n Effect.gen(function* read() {\n const text = yield* readStdin;\n const json = Schema.fromJsonString(schema);\n return yield* Schema.decodeEffect(json)(text);\n });\n\n/** @internal */\nexport const writeStdout = (text: string): Effect.Effect<void, never, Stdio.Stdio> =>\n Effect.gen(function* toStdout() {\n const stdio = yield* Stdio.Stdio;\n yield* Stream.make(text).pipe(Stream.run(stdio.stdout()), Effect.orDie);\n });\n\n/** @internal */\nexport const writeStderr = (text: string): Effect.Effect<void, never, Stdio.Stdio> =>\n Effect.gen(function* toStderr() {\n const stdio = yield* Stdio.Stdio;\n yield* Stream.make(text).pipe(Stream.run(stdio.stderr()), Effect.orDie);\n });\n\n/** @internal */\nexport const writeHookOutput =\n <Codec extends Schema.Top>(schema: Codec) =>\n (value: Codec[\"Type\"]): Effect.Effect<void, never, Stdio.Stdio | Codec[\"EncodingServices\"]> =>\n Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.orDie,\n Effect.flatMap(writeStdout),\n );\n","import { Cause, Effect, Layer, Option } from \"effect\";\nimport type { Stdio } from \"effect\";\n\nimport { isHookBlocked, writeStderr } from \"./hook-io.ts\";\nimport type { HookBlocked } from \"./hook-io.ts\";\nimport { runMainWith } from \"./run-main.ts\";\nimport type { Platform, Run } from \"./run-main.ts\";\n\nconst blockedIn = <Failure>(cause: Cause.Cause<Failure>): Option.Option<HookBlocked> =>\n Cause.findErrorOption(cause).pipe(\n Option.filter((error): error is Failure & HookBlocked => isHookBlocked(error)),\n );\n\nconst reportBlocked = <Failure>(\n cause: Cause.Cause<Failure>,\n): Effect.Effect<void, never, Stdio.Stdio> =>\n cause.pipe(\n blockedIn,\n Option.match({\n onNone: () => Effect.void,\n onSome: (blocked) => writeStderr(`${blocked.reason}\\n`),\n }),\n );\n\n/** @internal */\nexport const runHookWith =\n <Provided, LayerFailure>({\n serviceName,\n services,\n }: Readonly<{\n serviceName: string;\n services: Layer.Layer<Provided, LayerFailure, Platform>;\n }>): Run<Provided> =>\n (program) => {\n runMainWith({ serviceName, services })(program.pipe(Effect.tapCause(reportBlocked)));\n };\n\n/** @internal */\nexport const runHook = (serviceName: string): Run<never> =>\n runHookWith({ serviceName, services: Layer.empty });\n","import { Record as RecordSchema, String as StringSchema, Unknown, is } from \"effect/Schema\";\n\nexport const isRecord = is(RecordSchema(StringSchema, Unknown));\n","import { Array as Arr, Option, Record as Rec, Schema, String as Str, pipe } from \"effect\";\n\nimport type { HistoryEntry, HistoryToolCall, Message, ToolCall } from \"./types.ts\";\n\nconst FIRST = 0;\nconst ONE = 1;\nconst ELLIPSIS = \"…\";\nconst VALUE_CHARS = 200;\nconst COMPACT_INPUT_CHARS = 60;\nconst SPACES = /\\s+/gu;\nconst encodeJson = Schema.encodeOption(Schema.fromJsonString(Schema.Unknown));\n\nexport const jsonOf = (value: unknown): Option.Option<string> => encodeJson(value);\n\nexport const truncate = (text: string, limit: number): string => {\n if (Str.length(text) <= limit) {\n return text;\n }\n return `${Str.slice(FIRST, Math.max(FIRST, limit - ONE))(text)}${ELLIPSIS}`;\n};\n\nexport const isPinned = (index: number, total: number, preserveRecentMessages: number): boolean =>\n index === FIRST || index >= total - preserveRecentMessages;\n\ninterface Found {\n readonly index: number;\n readonly chars: number;\n readonly isError: boolean;\n}\n\nconst resultsOf = (messages: readonly Message[]): ReadonlyMap<string, Found> =>\n new Map(\n pipe(\n messages,\n Arr.flatMap((message, index) =>\n pipe(\n message.toolResults,\n Arr.map(\n (result) =>\n [\n result.tool_use_id,\n { index, chars: Str.length(result.text), isError: result.isError },\n ] as const,\n ),\n ),\n ),\n ),\n );\n\nexport const collectToolCalls = (\n messages: readonly Message[],\n preserveRecentMessages: number,\n): readonly ToolCall[] => {\n const results = resultsOf(messages);\n const pinned = (index: number): boolean =>\n isPinned(index, messages.length, preserveRecentMessages);\n return pipe(\n messages,\n Arr.flatMap((message, callIndex) =>\n pipe(\n message.toolUses,\n Arr.flatMap((tool) =>\n pipe(\n Option.fromUndefinedOr(results.get(tool.tool_use_id)),\n Option.map((found) => ({ tool, callIndex, found })),\n Option.toArray,\n ),\n ),\n ),\n ),\n Arr.map(({ tool, callIndex, found }, index) => ({\n id: `t${String(index + ONE)}`,\n tool_use_id: tool.tool_use_id,\n tool: tool.tool,\n input: tool.input,\n callIndex,\n resultIndex: found.index,\n resultChars: found.chars,\n isError: found.isError,\n pinned: pinned(callIndex) || pinned(found.index),\n })),\n );\n};\n\nexport const inputText = (input: Readonly<Record<string, unknown>>, limit: number): string =>\n truncate(\n Option.getOrElse(jsonOf(input), () => \"[unserializable input]\"),\n limit,\n );\n\nconst outcomeOf = (call: ToolCall): string => {\n if (call.isError) {\n return \"error\";\n }\n return \"ok\";\n};\n\nconst resultNote = (call: ToolCall): string =>\n `${outcomeOf(call)}, ${String(call.resultChars)} chars (omitted)`;\n\nconst valueText = ([key, value]: readonly [string, unknown]): string => {\n const text = pipe(\n Option.liftPredicate(value, (raw): raw is string => typeof raw === \"string\"),\n Option.getOrElse(() => inputText({ [key]: value }, VALUE_CHARS)),\n );\n return `${key}=${Str.replaceAll(SPACES, \" \")(text)}`;\n};\n\nexport const compactCall = (call: ToolCall): string => {\n const input = pipe(Rec.toEntries(call.input), Arr.map(valueText), Arr.join(\" \"));\n return `${call.id} ${call.tool} ${truncate(input, COMPACT_INPUT_CHARS)} → ${outcomeOf(call)} ${String(call.resultChars)}ch`;\n};\n\nexport const callsByMessage = (\n calls: readonly ToolCall[],\n): ReadonlyMap<number, readonly ToolCall[]> =>\n new Map(\n pipe(\n calls,\n Arr.groupBy((call) => String(call.callIndex)),\n Rec.toEntries,\n Arr.map(([index, own]) => [Number(index), own] as const),\n ),\n );\n\nconst historyCallOf =\n (inputChars: number) =>\n (call: ToolCall): HistoryToolCall => ({\n id: call.id,\n tool: call.tool,\n input: inputText(call.input, inputChars),\n result: resultNote(call),\n });\n\nexport const historyEntries = (\n messages: readonly Message[],\n calls: readonly ToolCall[],\n inputChars: number,\n): readonly HistoryEntry[] => {\n const byMessage = callsByMessage(calls);\n return pipe(\n messages,\n Arr.flatMap((message, index): readonly HistoryEntry[] => {\n const own = Option.getOrElse(Option.fromUndefinedOr(byMessage.get(index)), () => []);\n const toolCalls = pipe(own, Arr.map(historyCallOf(inputChars)));\n const entry = { index, role: message.role, text: message.text };\n if (Arr.isReadonlyArrayNonEmpty(toolCalls)) {\n return [{ ...entry, tool_calls: toolCalls }];\n }\n if (Str.isEmpty(Str.trim(message.text))) {\n return [];\n }\n return [entry];\n }),\n );\n};\n","import { Array as Arr, Number as Num, Option, String as Str, pipe } from \"effect\";\n\nimport { groupOf } from \"./match-groups.ts\";\n\nconst PIECES = /(?<alpha>[A-Za-z]+)|(?<digits>\\d+)|(?<other>[^\\sA-Za-z\\d])/gu;\nconst DIGITS_PER_TOKEN = 2;\nconst LETTERS_PER_TOKEN = 6;\nconst SYMBOL_TOKENS = 0.9;\nconst ONE = 1;\n\nconst pieceTokens = (match: RegExpMatchArray): number =>\n pipe(\n groupOf(\"digits\")(match),\n Option.map((digits) => Str.length(digits) / DIGITS_PER_TOKEN),\n Option.orElse(() =>\n Option.map(\n groupOf(\"alpha\")(match),\n (alpha) => ONE + Math.floor((Str.length(alpha) - ONE) / LETTERS_PER_TOKEN),\n ),\n ),\n Option.getOrElse(() => SYMBOL_TOKENS),\n );\n\nconst matchesOf = (pattern: RegExp, text: string): readonly RegExpMatchArray[] =>\n Arr.fromIterable(Str.matchAll(pattern)(text));\n\nexport const estimateTokens = (text: string): number => {\n const pieces = pipe(matchesOf(PIECES, text), Arr.map(pieceTokens));\n return Math.ceil(Num.sumAll(pieces));\n};\n","import { Array as Arr, Number as Num, Option, pipe } from \"effect\";\n\nimport { estimateTokens } from \"#/shared/lib/tokens.ts\";\n\nimport { isPinned, jsonOf } from \"./calls.ts\";\nimport type {\n CompactionState,\n FitOptions,\n FittedState,\n HistoryEntry,\n Message,\n ToolCall,\n} from \"./types.ts\";\n\nconst ONE = 1;\nconst NONE = 0;\n\nexport const entryTokens = (entry: HistoryEntry): number =>\n jsonOf(entry).pipe(\n Option.getOrElse(() => \"\"),\n estimateTokens,\n ) + ONE;\n\nexport interface Fitting {\n readonly history: readonly Option.Option<HistoryEntry>[];\n readonly perEntry: readonly number[];\n readonly tokens: number;\n}\n\nexport interface Plan {\n readonly messages: readonly Message[];\n readonly calls: readonly ToolCall[];\n readonly options: FitOptions;\n readonly stateOf: (history: readonly HistoryEntry[]) => CompactionState;\n readonly baseTokens: number;\n readonly byMessage: ReadonlyMap<number, readonly ToolCall[]>;\n}\n\nexport type Change = (entry: HistoryEntry) => Option.Option<Option.Option<HistoryEntry>>;\n\nexport const fittingOf = (plan: Plan, history: readonly HistoryEntry[]): Fitting => {\n const perEntry = pipe(history, Arr.map(entryTokens));\n return {\n history: pipe(history, Arr.map(Option.some)),\n perEntry,\n tokens: plan.baseTokens + Num.sumAll(perEntry),\n };\n};\n\nexport const kept = (fitting: Fitting): readonly HistoryEntry[] => Arr.getSomes(fitting.history);\n\nexport const fits = (plan: Plan, fitting: Fitting): boolean =>\n fitting.tokens <= plan.options.maxStateTokens;\n\nexport const fitted = (plan: Plan, fitting: Fitting, stage: string): FittedState => ({\n state: plan.stateOf(kept(fitting)),\n tokens: fitting.tokens,\n stage,\n});\n\nexport const pinnedEntry = (plan: Plan, entry: HistoryEntry): boolean =>\n isPinned(entry.index, plan.messages.length, plan.options.preserveRecentMessages);\n\nconst orderOf = (plan: Plan, fitting: Fitting): readonly number[] => {\n const present = pipe(\n fitting.history,\n Arr.flatMap((entry, index) =>\n pipe(\n entry,\n Option.map((value) => [index, pinnedEntry(plan, value)] as const),\n Option.toArray,\n ),\n ),\n );\n const loose = pipe(\n present,\n Arr.filter(([, pinned]) => !pinned),\n );\n const pinned = pipe(\n present,\n Arr.filter(([, isPinnedEntry]) => isPinnedEntry),\n );\n return pipe(\n [...loose, ...pinned],\n Arr.map(([index]) => index),\n );\n};\n\ninterface Step {\n readonly index: number;\n readonly entry: Option.Option<HistoryEntry>;\n readonly tokens: number;\n}\n\nconst stepOf =\n (fitting: Fitting, change: Change) =>\n (index: number): Option.Option<Step> =>\n pipe(\n Option.flatten(Option.fromUndefinedOr(fitting.history[index])),\n Option.flatMap(change),\n Option.map((entry) => ({\n index,\n entry,\n tokens: Option.match(entry, { onNone: () => NONE, onSome: entryTokens }),\n })),\n );\n\nconst applied = (fitting: Fitting, steps: readonly Step[]): Fitting => {\n const byIndex = new Map(\n pipe(\n steps,\n Arr.map((step) => [step.index, step] as const),\n ),\n );\n const pick = <Value>(index: number, value: Value, of: (step: Step) => Value): Value =>\n Option.match(Option.fromUndefinedOr(byIndex.get(index)), { onNone: () => value, onSome: of });\n const history = pipe(\n fitting.history,\n Arr.map((entry, index) => pick(index, entry, (step) => step.entry)),\n );\n const perEntry = pipe(\n fitting.perEntry,\n Arr.map((tokens, index) => pick(index, tokens, (step) => step.tokens)),\n );\n const delta = Num.sumAll(\n pipe(\n steps,\n Arr.map(\n (step) => step.tokens - Option.getOrElse(Arr.get(fitting.perEntry, step.index), () => NONE),\n ),\n ),\n );\n return { history, perEntry, tokens: fitting.tokens + delta };\n};\n\nexport const staged = (\n plan: Plan,\n fitting: Fitting,\n change: Change,\n): readonly [Fitting, boolean] => {\n const steps = pipe(\n orderOf(plan, fitting),\n Arr.flatMap((index) => Option.toArray(stepOf(fitting, change)(index))),\n );\n const totals = pipe(\n steps,\n Arr.scan(\n fitting.tokens,\n (tokens, step) =>\n tokens + step.tokens - Option.getOrElse(Arr.get(fitting.perEntry, step.index), () => NONE),\n ),\n Arr.drop(ONE),\n );\n return Option.match(\n Arr.findFirstIndex(totals, (tokens) => tokens <= plan.options.maxStateTokens),\n {\n onNone: () => [applied(fitting, steps), false] as const,\n onSome: (at) => [applied(fitting, Arr.take(steps, at + ONE)), true] as const,\n },\n );\n};\n","import {\n Array as Arr,\n Effect,\n Option,\n Predicate,\n Result,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport { estimateTokens } from \"#/shared/lib/tokens.ts\";\n\nimport { callsByMessage, compactCall, historyEntries, jsonOf, truncate } from \"./calls.ts\";\nimport { fits, fitted, fittingOf, kept, pinnedEntry, staged } from \"./fitting.ts\";\nimport type { Change, Fitting, Plan } from \"./fitting.ts\";\nimport type {\n CompactionState,\n FitOptions,\n FittedState,\n HistoryEntry,\n HistoryToolCall,\n Message,\n ToolCall,\n} from \"./types.ts\";\n\nexport const STATE_CONTEXT =\n \"A coding assistant conversation is being compacted to free context. `history` is the whole conversation so far, oldest first; tool outputs are replaced by a short `result` note and long texts may be abridged. Each question asks whether one tool call, or the full output of that call, still needs to stay in the history verbatim. Whatever is not kept is deleted permanently, but the assistant can always re-run a tool or re-read a file.\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class HistoryTooLarge extends taggedError<\n HistoryTooLarge,\n { readonly brand: unique symbol }\n>()(\"HistoryTooLarge\", { reason: Schema.String }) {}\n\nconst FULL_INPUT_CHARS = 1000;\nconst SHORT_INPUT_CHARS = 200;\nconst SHORTEST_INPUT_CHARS = 60;\nconst SHORTER_INPUT_CHARS = [SHORT_INPUT_CHARS, SHORTEST_INPUT_CHARS] as const;\nconst TEXT_HEAD = 400;\nconst TEXT_TAIL = 150;\nconst ABRIDGE_MARGIN = 40;\nconst RECENT_GOALS = 3;\nconst GOAL_CHARS = 500;\nconst ONE = 1;\n\nconst abridge = (text: string): string => {\n const omitted = Str.length(text) - TEXT_HEAD - TEXT_TAIL;\n return `${Str.takeLeft(TEXT_HEAD)(text)}\\n[… ${String(omitted)} chars omitted …]\\n${Str.takeRight(TEXT_TAIL)(text)}`;\n};\n\nexport const goalFromMessages = (messages: readonly Message[]): string =>\n pipe(\n messages,\n Arr.filter(\n (message) =>\n message.role === \"user\" &&\n Str.isNonEmpty(Str.trim(message.text)) &&\n Arr.isReadonlyArrayEmpty(message.toolResults),\n ),\n Arr.takeRight(RECENT_GOALS),\n Arr.map((message) => truncate(message.text, GOAL_CHARS)),\n Arr.join(\"\\n\"),\n );\n\nconst abridgeText: Change = (entry: HistoryEntry) =>\n Option.liftPredicate(\n Option.some({ ...entry, text: abridge(entry.text) }),\n () => Str.length(entry.text) > TEXT_HEAD + TEXT_TAIL + ABRIDGE_MARGIN,\n );\n\nconst collapseText =\n (plan: Plan): Change =>\n (entry: HistoryEntry) => {\n const original = pipe(\n Arr.get(plan.messages, entry.index),\n Option.map((message) => Str.length(message.text)),\n Option.getOrElse(() => Str.length(entry.text)),\n );\n return Option.liftPredicate(\n Option.some({ ...entry, text: `[… ${String(original)} chars omitted …]` }),\n () => !pinnedEntry(plan, entry) && Str.isNonEmpty(entry.text),\n );\n };\n\nconst compactCalls =\n (plan: Plan): Change =>\n (entry: HistoryEntry) =>\n pipe(\n Option.fromUndefinedOr(plan.byMessage.get(entry.index)),\n Option.filter(() => !pinnedEntry(plan, entry)),\n Option.map((own) => Option.some({ ...entry, tool_calls: pipe(own, Arr.map(compactCall)) })),\n );\n\nconst leaveOut =\n (plan: Plan): Change =>\n (entry: HistoryEntry) =>\n Option.liftPredicate(\n Option.none<HistoryEntry>(),\n () => !pinnedEntry(plan, entry) && Predicate.isUndefined(entry.tool_calls),\n );\n\nconst callsOf = (entry: HistoryEntry): readonly (HistoryToolCall | string)[] =>\n Option.getOrElse(Option.fromUndefinedOr(entry.tool_calls), () => []);\n\nconst stringCalls = (entry: HistoryEntry): readonly string[] =>\n pipe(callsOf(entry), Arr.filter(Predicate.isString));\n\nconst foldable = (plan: Plan, entry: HistoryEntry): boolean =>\n !pinnedEntry(plan, entry) &&\n Str.isEmpty(entry.text) &&\n pipe(Arr.head(callsOf(entry)), Option.exists(Predicate.isString));\n\nconst mergedRun = (group: Arr.NonEmptyReadonlyArray<HistoryEntry>): HistoryEntry => {\n const first = Arr.headNonEmpty(group);\n if (group.length === ONE) {\n return first;\n }\n return { ...first, tool_calls: pipe(group, Arr.flatMap(stringCalls)) };\n};\n\nconst mergeRuns = (plan: Plan, history: readonly HistoryEntry[]): readonly HistoryEntry[] => {\n if (!Arr.isReadonlyArrayNonEmpty(history)) {\n return [];\n }\n return pipe(\n Arr.groupWith(\n history,\n (left, right) => foldable(plan, left) && foldable(plan, right) && left.role === right.role,\n ),\n Arr.map(mergedRun),\n );\n};\n\ntype Staged = readonly [Fitting, boolean];\n\ntype Stage = readonly [string, (fitting: Fitting) => Staged];\n\nconst rebuilt = (plan: Plan, inputChars: number) => (): readonly [Fitting, boolean] => {\n const fitting = fittingOf(plan, historyEntries(plan.messages, plan.calls, inputChars));\n return [fitting, fits(plan, fitting)];\n};\n\nconst stagesOf = (plan: Plan): readonly Stage[] => [\n ...pipe(\n SHORTER_INPUT_CHARS,\n Arr.map((limit): Stage => [`inputs<=${String(limit)}`, rebuilt(plan, limit)]),\n ),\n [\"texts abridged\", (fitting): Staged => staged(plan, fitting, abridgeText)],\n [\"old messages collapsed\", (fitting): Staged => staged(plan, fitting, collapseText(plan))],\n [\"old calls compacted\", (fitting): Staged => staged(plan, fitting, compactCalls(plan))],\n [\"old messages left out\", (fitting): Staged => staged(plan, fitting, leaveOut(plan))],\n [\n \"old calls merged\",\n (fitting): Staged => {\n const merged = fittingOf(plan, mergeRuns(plan, kept(fitting)));\n return [merged, fits(plan, merged)];\n },\n ],\n];\n\nconst throughStages = (\n plan: Plan,\n fitting: Fitting,\n stages: readonly Stage[],\n): Result.Result<FittedState, Fitting> =>\n Option.match(Arr.head(stages), {\n onNone: () => Result.fail(fitting),\n onSome: ([name, run]) => {\n const [next, done] = run(fitting);\n if (done) {\n return Result.succeed(fitted(plan, next, name));\n }\n return throughStages(plan, next, Arr.drop(stages, ONE));\n },\n });\n\nconst jsonText = (value: unknown): string => Option.getOrElse(jsonOf(value), () => \"\");\n\nconst planOf = (\n messages: readonly Message[],\n calls: readonly ToolCall[],\n options: FitOptions,\n): Plan => {\n const goal = pipe(\n Option.liftPredicate(options.goal, Str.isNonEmpty),\n Option.getOrElse(() => goalFromMessages(messages)),\n );\n const stateOf = (history: readonly HistoryEntry[]): CompactionState => ({\n context: STATE_CONTEXT,\n goal,\n history,\n });\n return {\n messages,\n calls,\n options,\n stateOf,\n baseTokens: estimateTokens(jsonText(stateOf([]))),\n byMessage: callsByMessage(calls),\n };\n};\n\nexport const fitState = (\n messages: readonly Message[],\n calls: readonly ToolCall[],\n options: FitOptions,\n): Effect.Effect<FittedState, HistoryTooLarge> => {\n const plan = planOf(messages, calls, options);\n const full = fittingOf(plan, historyEntries(messages, calls, FULL_INPUT_CHARS));\n if (fits(plan, full)) {\n return Effect.succeed(fitted(plan, full, \"full\"));\n }\n return Result.match(throughStages(plan, full, stagesOf(plan)), {\n onSuccess: Effect.succeed,\n onFailure: (last) =>\n Effect.fail(\n HistoryTooLarge.make({\n reason: `history too large for Jev (~${String(last.tokens)} tokens after truncation, limit ${String(options.maxStateTokens)})`,\n }),\n ),\n });\n};\n","import { Array as Arr, Option, String as Str, pipe } from \"effect\";\n\nconst OWNER_BODIES: readonly RegExp[] = [\n /<message\\b[^>]*\\bfrom=\"human\"[^>]*\\btrust=\"principal\"[^>]*>(?<body>[\\s\\S]*?)<\\/message>/gu,\n /<cited\\b[^>]*\\bauthor=\"user\"[^>]*>(?<body>[\\s\\S]*?)<\\/cited>/gu,\n];\n\nconst bodiesOf = (prompt: string): readonly string[] =>\n pipe(\n OWNER_BODIES,\n Arr.flatMap((pattern) => Arr.fromIterable(pipe(prompt, Str.matchAll(pattern)))),\n Arr.map((found) =>\n pipe(\n Option.fromUndefinedOr(found.groups),\n Option.flatMap((groups) => Option.fromUndefinedOr(groups[\"body\"])),\n ),\n ),\n Arr.getSomes,\n );\n\nconst argumentsAfter =\n (text: string) =>\n (command: string): Option.Option<string> =>\n pipe(\n Option.some(Str.trimStart(text)),\n Option.filter(Str.startsWith(command)),\n Option.map((typed) => Str.slice(command.length)(typed)),\n Option.filter((rest) => Str.isEmpty(rest) || /^\\s/u.test(rest)),\n Option.map(Str.trim),\n );\n\nconst typedIn =\n (commands: readonly string[]) =>\n (text: string): Option.Option<string> =>\n Arr.findFirst(commands, argumentsAfter(text));\n\nconst ownerBody =\n (commands: readonly string[]) =>\n (prompt: string): Option.Option<string> =>\n pipe(bodiesOf(prompt), Arr.map(typedIn(commands)), Arr.getSomes, Arr.last);\n\nexport const ownerCommand = (prompt: string, commands: readonly string[]): Option.Option<string> =>\n Option.orElse(typedIn(commands)(prompt), () => ownerBody(commands)(prompt));\n","import {\n Array as Arr,\n Config,\n Effect,\n FileSystem,\n Option,\n Path,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport { ownerCommand } from \"./owner-command.ts\";\n\nconst OFF = \"disable\";\n\nconst turnsOn = (args: string): boolean =>\n !pipe(\n Str.split(args, /\\s+/u),\n Arr.head,\n Option.exists((word) => word === OFF),\n );\n\nexport const ownerSwitch = (prompt: string, commands: readonly string[]): Option.Option<boolean> =>\n Option.map(ownerCommand(prompt, commands), turnsOn);\n\nconst blank = Schema.String.pipe(Schema.withDecodingDefaultKey(Effect.succeed(\"\")));\n\nexport const OwnerPrompt = Schema.Struct({ prompt: blank, session_id: blank });\n\nconst directoryOf = Effect.fn(\"directoryOf\")(function* directoryOf(name: string) {\n const path = yield* Path.Path;\n const data = yield* Config.NonEmptyString(\"CLAUDE_PLUGIN_DATA\");\n return path.join(data, name);\n});\n\nconst markerOf = Effect.fn(\"markerOf\")(function* markerOf(directory: string, session: string) {\n const path = yield* Path.Path;\n return path.join(directory, path.basename(session));\n});\n\n/** @internal */\nexport const switchSession = Effect.fn(\"switchSession\")(function* switchSession(\n name: string,\n session: string,\n on: boolean,\n) {\n const fs = yield* FileSystem.FileSystem;\n const directory = yield* directoryOf(name);\n const marker = yield* markerOf(directory, session);\n if (!on) {\n return yield* fs.remove(marker, { force: true });\n }\n yield* fs.makeDirectory(directory, { recursive: true });\n return yield* fs.writeFileString(marker, \"\");\n});\n\n/** @internal */\nexport const sessionSwitchedOn = Effect.fn(\"sessionSwitchedOn\")(\n function* sessionSwitchedOn(name: string, session: string) {\n const fs = yield* FileSystem.FileSystem;\n if (Str.isEmpty(session)) {\n return false;\n }\n const directory = yield* directoryOf(name);\n const marker = yield* markerOf(directory, session);\n return yield* fs.exists(marker);\n },\n Effect.orElseSucceed(() => false),\n);\n\n/** @internal */\nexport const followOwnerSwitch = Effect.fn(\"followOwnerSwitch\")(function* followOwnerSwitch(\n input: typeof OwnerPrompt.Type,\n name: string,\n commands: readonly string[],\n) {\n if (Str.isEmpty(input.session_id)) {\n return;\n }\n yield* Option.match(ownerSwitch(input.prompt, commands), {\n onNone: () => Effect.void,\n onSome: (on) => switchSession(name, input.session_id, on),\n });\n});\n","import { Array as Arr, Effect, FileSystem, Path, Record as Rec, Schema, pipe } from \"effect\";\n\nconst InstalledEntry = Schema.Struct({\n installPath: Schema.String,\n version: Schema.Unknown,\n gitCommitSha: Schema.Unknown,\n});\nconst InstalledPlugins = Schema.Struct({\n plugins: Schema.Record(Schema.String, Schema.Array(InstalledEntry)),\n});\nconst decodeInstalled = Schema.decodeUnknownEffect(Schema.fromJsonString(InstalledPlugins));\n\nexport interface InstalledPlugin {\n readonly id: string;\n readonly installPath: string;\n readonly version: unknown;\n readonly sha: unknown;\n}\n\nconst flattened = (installed: typeof InstalledPlugins.Type): readonly InstalledPlugin[] =>\n pipe(\n Rec.toEntries(installed.plugins),\n Arr.flatMap(([id, entries]) =>\n pipe(\n entries,\n Arr.map((entry) => ({\n id,\n installPath: entry.installPath,\n version: entry.version,\n sha: entry.gitCommitSha,\n })),\n ),\n ),\n );\n\n/** @internal */\nexport const installedPlugins = Effect.fn(\"installedPlugins\")(function* installedPlugins(\n home: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(home, \".claude\", \"plugins\", \"installed_plugins.json\");\n return yield* fs.readFileString(file).pipe(\n Effect.flatMap(decodeInstalled),\n Effect.map(flattened),\n Effect.orElseSucceed((): readonly InstalledPlugin[] => []),\n );\n});\n","import {\n Array as Arr,\n Option,\n Predicate,\n Record as Rec,\n Schema,\n String as Str,\n pipe,\n} from \"effect\";\n\nexport type Place = \"ci\" | \"cloud\" | \"local\";\n\nexport interface Origin {\n readonly place: Place;\n readonly project: string;\n readonly hook: string;\n readonly sessionId: string;\n}\n\nexport interface JevSettings {\n readonly openRouterKey: string;\n readonly openRouterModel: string;\n readonly allowTraining: boolean;\n readonly attribution: Readonly<Record<string, string>>;\n}\n\nexport interface JevBackend {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly model: string;\n readonly extra: Readonly<Record<string, unknown>>;\n readonly headers: Readonly<Record<string, string>>;\n readonly textState: boolean;\n}\n\nexport interface PlaceEnv {\n readonly githubActions: string;\n readonly remote: string;\n}\n\nexport type JevState = Readonly<Record<string, string>>;\n\nconst DEFAULT_OPENROUTER_MODEL = \"respan/span-01-lite\";\nconst TEXT_STATE_PREFIX = \"respan/\";\nconst encodeJson = Schema.encodeOption(Schema.fromJsonString(Schema.Unknown));\n\nexport const placeOf = (env: PlaceEnv): Place => {\n if (env.githubActions === \"true\") {\n return \"ci\";\n }\n if (env.remote === \"true\") {\n return \"cloud\";\n }\n return \"local\";\n};\n\nconst dataCollection = (allowTraining: boolean): string => {\n if (allowTraining) {\n return \"allow\";\n }\n return \"deny\";\n};\n\nexport const jevBackend = (settings: JevSettings, origin: Origin): JevBackend => {\n const model = pipe(\n Option.liftPredicate(settings.openRouterModel, Str.isNonEmpty),\n Option.getOrElse(() => DEFAULT_OPENROUTER_MODEL),\n );\n const session = pipe(\n Option.liftPredicate(origin.sessionId, Str.isNonEmpty),\n Option.match({ onNone: () => ({}), onSome: (id) => ({ session_id: id }) }),\n );\n return {\n apiKey: settings.openRouterKey,\n baseURL: \"https://openrouter.ai/api\",\n model,\n extra: {\n provider: { data_collection: dataCollection(settings.allowTraining) },\n user: `${origin.place}:${origin.project}:${origin.hook}`,\n ...session,\n },\n headers: settings.attribution,\n textState: Str.startsWith(TEXT_STATE_PREFIX)(model),\n };\n};\n\nconst sectionOf = ([key, value]: readonly [string, unknown]): string => {\n const text = pipe(\n Option.liftPredicate(value, Predicate.isString),\n Option.orElse(() => encodeJson(value)),\n Option.getOrElse(() => \"\"),\n );\n return `## ${key}\\n${text}`;\n};\n\nexport const stateFor = (backend: JevBackend, state: JevState): JevState | string => {\n if (!backend.textState) {\n return state;\n }\n return pipe(Rec.toEntries(state), Arr.map(sectionOf), Arr.join(\"\\n\\n\"));\n};\n"],"mappings":";;;;;;AAEA,MAAM,gBAAgB;AAEtB,MAAMA,gBAAc,OAAO;;AAG3B,IAAa,cAAb,cAAiCA,cAA4D,CAAC,CAC5F,eACA,EAAE,QAAQ,OAAO,OAAO,CAC1B,CAAC,CAAC;CACA,CAA0B,QAAQ,iBAAiB;CACnD,CAA0B,QAAQ,iBAAiB;AACrD;;AAGA,MAAa,gBAAgB,OAAO,GAAG,WAAW;;AAGlD,MAAa,aAAa,WACxB,OAAO,KAAK,YAAY,KAAK,EAAE,OAAO,CAAC,CAAC;;AAG1C,MAAa,YAAuD,OAAO,IACzE,UAAU,YAAY;CAEpB,OAAO,QAAO,OADO,MAAM,MAAA,CACP,MAAM,KAAK,OAAO,YAAY,OAAO,UAAU,OAAO,KAAK;AACjF,CACF;;AAGA,MAAa,iBACX,WAEA,OAAO,IAAI,UAAU,OAAO;CAC1B,MAAM,OAAO,OAAO;CACpB,MAAM,OAAO,OAAO,eAAe,MAAM;CACzC,OAAO,OAAO,OAAO,aAAa,IAAI,CAAC,CAAC,IAAI;AAC9C,CAAC;;AAGH,MAAa,eAAe,SAC1B,OAAO,IAAI,UAAU,WAAW;CAC9B,MAAM,QAAQ,OAAO,MAAM;CAC3B,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,KAAK,OAAO,IAAI,MAAM,OAAO,CAAC,GAAG,OAAO,KAAK;AACxE,CAAC;;AAGH,MAAa,eAAe,SAC1B,OAAO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a,OAAO,eAAe,OAAO,OAAO,CAAC;AAE5E,MAAa,WAAW,QAAyB;CAC/C,IAAI,IAAI,kBAAkB,QACxB,OAAO;CAET,IAAI,IAAI,WAAW,QACjB,OAAO;CAET,OAAO;AACT;AAEA,MAAM,kBAAkB,kBAAmC;CACzD,IAAI,eACF,OAAO;CAET,OAAO;AACT;AAEA,MAAa,cAAc,UAAuB,WAA+B;CAC/E,MAAM,QAAQ,KACZ,OAAO,cAAc,SAAS,iBAAiBC,SAAI,UAAU,GAC7D,OAAO,gBAAgB,wBAAwB,CACjD;CACA,MAAM,UAAU,KACd,OAAO,cAAc,OAAO,WAAWA,SAAI,UAAU,GACrD,OAAO,MAAM;EAAE,eAAe,CAAC;EAAI,SAAS,QAAQ,EAAE,YAAY,GAAG;CAAG,CAAC,CAC3E;CACA,OAAO;EACL,QAAQ,SAAS;EACjB,SAAS;EACT;EACA,OAAO;GACL,UAAU,EAAE,iBAAiB,eAAe,SAAS,aAAa,EAAE;GACpE,MAAM,GAAG,OAAO,MAAM,GAAG,OAAO,QAAQ,GAAG,OAAO;GAClD,GAAG;EACL;EACA,SAAS,SAAS;EAClB,WAAWA,SAAI,WAAW,iBAAiB,CAAC,CAAC,KAAK;CACpD;AACF;AAEA,MAAM,aAAa,CAAC,KAAK,WAA+C;CAMtE,OAAO,MAAM,IAAI,IALJ,KACX,OAAO,cAAc,OAAO,UAAU,QAAQ,GAC9C,OAAO,aAAa,WAAW,KAAK,CAAC,GACrC,OAAO,gBAAgB,EAAE,CAEH;AAC1B;AAEA,MAAa,YAAY,SAAqB,UAAuC;CACnF,IAAI,CAAC,QAAQ,WACX,OAAO;CAET,OAAO,KAAKC,SAAI,UAAU,KAAK,GAAGC,MAAI,IAAI,SAAS,GAAGA,MAAI,KAAK,MAAM,CAAC;AACxE"}
@@ -35,6 +35,22 @@ const collected = Effect.fn("collected")(function* collected({ command, args, en
35
35
  };
36
36
  });
37
37
  const outputWith = (command) => collected(command).pipe(Effect.scoped, Effect.filterOrFail(({ code }) => code === SUCCESS, () => failed(command)), Effect.map(({ output }) => String.trim(output)));
38
+ const capturedWith = ({ command, args, env, cwd, forceKillAfter = FORCE_KILL_AFTER, output = "all" }) => Effect.gen(function* captured() {
39
+ const handle = yield* ChildProcess.make(command, args, {
40
+ cwd,
41
+ env,
42
+ extendEnv: true,
43
+ stdin: "ignore",
44
+ forceKillAfter
45
+ });
46
+ const [text, code] = yield* Effect.all([handle[output].pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], { concurrency: "unbounded" });
47
+ return {
48
+ valid: code === SUCCESS,
49
+ output: text
50
+ };
51
+ }).pipe(Effect.scoped);
52
+ /** @internal */
53
+ const captured = capturedWith;
38
54
  /** @internal */
39
55
  const succeeds = succeedsWith;
40
56
  /** @internal */
@@ -44,6 +60,6 @@ const finishedWith = (command) => Effect.scoped(collected(command));
44
60
  const outputOf = outputWith;
45
61
  /** @internal */
46
62
  const finished = finishedWith;
47
- export { succeeds as a, outputOf as i, finished as n, mustSucceed as r, CommandFailed as t };
63
+ export { outputOf as a, mustSucceed as i, captured as n, succeeds as o, finished as r, CommandFailed as t };
48
64
 
49
- //# sourceMappingURL=process-l69KvwcT.mjs.map
65
+ //# sourceMappingURL=process-DTCkAoL_.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-DTCkAoL_.mjs","names":["Arr","Str"],"sources":["../src/shared/lib/process.ts"],"sourcesContent":["import { Array as Arr, Duration, Effect, Schema, Stream, String as Str } from \"effect\";\nimport type { PlatformError } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\n\nconst SUCCESS = 0;\nconst FORCE_KILL_AFTER_SECONDS = 10;\nconst FORCE_KILL_AFTER = Duration.seconds(FORCE_KILL_AFTER_SECONDS);\n\nconst taggedError = Schema.TaggedError;\n\nexport class CommandFailed extends taggedError<CommandFailed, { readonly brand: unique symbol }>()(\n \"CommandFailed\",\n { message: Schema.String },\n) {}\n\nexport interface Command {\n readonly command: string;\n readonly args: readonly string[];\n readonly env?: Readonly<Record<string, string>>;\n readonly cwd?: string;\n readonly forceKillAfter?: Duration.Input;\n}\n\n/** @internal */\nexport type Spawned<Success> = Effect.Effect<\n Success,\n CommandFailed | PlatformError.PlatformError,\n ChildProcessSpawner.ChildProcessSpawner\n>;\n\nconst failed = ({ command, args }: Command): CommandFailed =>\n CommandFailed.make({ message: `${command} ${Arr.join(args, \" \")} failed` });\n\nconst exitCodeOf = Effect.fn(\"exitCodeOf\")(function* exitCodeOf({\n command,\n args,\n env,\n cwd,\n forceKillAfter = FORCE_KILL_AFTER,\n}: Command) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return yield* spawner.exitCode(\n ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: true,\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"inherit\",\n forceKillAfter,\n }),\n );\n});\n\nconst succeedsWith = (command: Command): Spawned<boolean> =>\n exitCodeOf(command).pipe(Effect.map((code) => code === SUCCESS));\n\nconst mustSucceedWith = (command: Command): Spawned<void> =>\n succeedsWith(command).pipe(\n Effect.filterOrFail(\n (passed) => passed,\n () => failed(command),\n ),\n Effect.asVoid,\n );\n\nconst collected = Effect.fn(\"collected\")(function* collected({\n command,\n args,\n env,\n cwd,\n forceKillAfter = FORCE_KILL_AFTER,\n}: Command) {\n const handle = yield* ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: true,\n stdin: \"ignore\",\n stderr: \"inherit\",\n forceKillAfter,\n });\n const [output, code] = yield* Effect.all(\n [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],\n { concurrency: \"unbounded\" },\n );\n return { output, code };\n});\n\nconst outputWith = (command: Command): Spawned<string> =>\n collected(command).pipe(\n Effect.scoped,\n Effect.filterOrFail(\n ({ code }) => code === SUCCESS,\n () => failed(command),\n ),\n Effect.map(({ output }) => Str.trim(output)),\n );\n\nexport interface Captured {\n readonly valid: boolean;\n readonly output: string;\n}\n\nexport type CapturedCommand = Command & Readonly<{ output?: \"all\" | \"stdout\" }>;\n\nconst capturedWith = ({\n command,\n args,\n env,\n cwd,\n forceKillAfter = FORCE_KILL_AFTER,\n output = \"all\",\n}: CapturedCommand): Effect.Effect<\n Captured,\n PlatformError.PlatformError,\n ChildProcessSpawner.ChildProcessSpawner\n> =>\n Effect.gen(function* captured() {\n const handle = yield* ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: true,\n stdin: \"ignore\",\n forceKillAfter,\n });\n const [text, code] = yield* Effect.all(\n [handle[output].pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],\n { concurrency: \"unbounded\" },\n );\n return { valid: code === SUCCESS, output: text };\n }).pipe(Effect.scoped);\n\n/** @internal */\nexport const captured = capturedWith;\n\n/** @internal */\nexport const succeeds = succeedsWith;\n\n/** @internal */\nexport const mustSucceed = mustSucceedWith;\n\nconst finishedWith = (command: Command): Spawned<Readonly<{ output: string; code: number }>> =>\n Effect.scoped(collected(command));\n\n/** @internal */\nexport const outputOf = outputWith;\n\n/** @internal */\nexport const finished = finishedWith;\n"],"mappings":";;;AAIA,MAAM,UAAU;AAEhB,MAAM,mBAAmB,SAAS,QAAQ,EAAwB;AAElE,MAAM,cAAc,OAAO;AAE3B,IAAa,gBAAb,cAAmC,YAA8D,CAAC,CAChG,iBACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;AAiBH,MAAM,UAAU,EAAE,SAAS,WACzB,cAAc,KAAK,EAAE,SAAS,GAAG,QAAQ,GAAGA,MAAI,KAAK,MAAM,GAAG,EAAE,SAAS,CAAC;AAE5E,MAAM,aAAa,OAAO,GAAG,YAAY,CAAC,CAAC,UAAU,WAAW,EAC9D,SACA,MACA,KACA,KACA,iBAAiB,oBACP;CAEV,OAAO,QAAO,OADS,oBAAoB,oBAAA,CACrB,SACpB,aAAa,KAAK,SAAS,MAAM;EAC/B;EACA;EACA,WAAW;EACX,OAAO;EACP,QAAQ;EACR,QAAQ;EACR;CACF,CAAC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AC,KAAK,OAAO,MAAM;;AAGvB,MAAa,WAAW;;AAGxB,MAAa,WAAW;;AAGxB,MAAa,cAAc;AAE3B,MAAM,gBAAgB,YACpB,OAAO,OAAO,UAAU,OAAO,CAAC;;AAGlC,MAAa,WAAW;;AAGxB,MAAa,WAAW"}
@@ -18,6 +18,16 @@ type Spawned<Success> = Effect.Effect<Success, CommandFailed | PlatformError.Pla
18
18
  declare const succeedsWith: (command: Command) => Spawned<boolean>;
19
19
  declare const mustSucceedWith: (command: Command) => Spawned<void>;
20
20
  declare const outputWith: (command: Command) => Spawned<string>;
21
+ interface Captured {
22
+ readonly valid: boolean;
23
+ readonly output: string;
24
+ }
25
+ type CapturedCommand = Command & Readonly<{
26
+ output?: "all" | "stdout";
27
+ }>;
28
+ declare const capturedWith: ({ command, args, env, cwd, forceKillAfter, output }: CapturedCommand) => Effect.Effect<Captured, PlatformError.PlatformError, ChildProcessSpawner.ChildProcessSpawner>;
29
+ /** @internal */
30
+ declare const captured: typeof capturedWith;
21
31
  /** @internal */
22
32
  declare const succeeds: typeof succeedsWith;
23
33
  /** @internal */
@@ -30,4 +40,4 @@ declare const finishedWith: (command: Command) => Spawned<Readonly<{
30
40
  declare const outputOf: typeof outputWith;
31
41
  /** @internal */
32
42
  declare const finished: typeof finishedWith;
33
- export { outputOf as a, mustSucceed as i, CommandFailed as n, succeeds as o, finished as r, Command as t };
43
+ export { captured as a, outputOf as c, CommandFailed as i, succeeds as l, CapturedCommand as n, finished as o, Command as r, mustSucceed as s, Captured as t };
@@ -1,2 +1,2 @@
1
- import { a as outputOf, i as mustSucceed, n as CommandFailed, o as succeeds, t as Command } from "./process-BHJEIAWo.mjs";
2
- export { type Command, CommandFailed, mustSucceed, outputOf, succeeds };
1
+ import { a as captured, c as outputOf, i as CommandFailed, l as succeeds, n as CapturedCommand, r as Command, s as mustSucceed, t as Captured } from "./process-z7u_XWgI.mjs";
2
+ export { type Captured, type CapturedCommand, type Command, CommandFailed, captured, mustSucceed, outputOf, succeeds };
package/dist/process.mjs CHANGED
@@ -1 +1 @@
1
- export { t as CommandFailed, r as mustSucceed, i as outputOf, a as succeeds } from "./process-l69KvwcT.mjs";
1
+ export { t as CommandFailed, n as captured, i as mustSucceed, a as outputOf, o as succeeds } from "./process-DTCkAoL_.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r_masseater/masseater-utils",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "The small shared libraries of masseater's repositories as subpaths of one package: a chip row for React, Claude Code plugin helpers, Effect entry points for Node.js and GitHub Actions, file import mapping, Node package readers, OTLP assertions for Vitest and Cloudflare Workers tracing, and what the Tauri desktop apps share: OpenTelemetry for the screens, Vite settings, the media-notes screens and the release commands.",
5
5
  "keywords": [
6
6
  "actions",
@@ -68,6 +68,7 @@
68
68
  "./app-name": "./dist/app-name.mjs",
69
69
  "./browser-test/fonts.conf": "./src/app/browser-test-fonts.conf",
70
70
  "./browser-test/vite": "./dist/browser-test/vite.mjs",
71
+ "./cache": "./dist/cache.mjs",
71
72
  "./desktop-shell/media-notes": "./dist/desktop-shell/media-notes.mjs",
72
73
  "./desktop-shell/media-notes/protocol": "./dist/desktop-shell/media-notes/protocol.mjs",
73
74
  "./desktop-shell/release-cli": "./dist/desktop-shell/release-cli.mjs",
@@ -8,7 +8,7 @@ description: >
8
8
  metadata:
9
9
  type: core
10
10
  library: "@r_masseater/masseater-utils"
11
- library_version: 0.16.0
11
+ library_version: 0.17.0
12
12
  sources:
13
13
  - src/app
14
14
  - src/features/scroll-chip-row
@@ -8,7 +8,7 @@ description: >
8
8
  metadata:
9
9
  type: core
10
10
  library: "@r_masseater/masseater-utils"
11
- library_version: 0.16.0
11
+ library_version: 0.17.0
12
12
  sources:
13
13
  - src/app
14
14
  - src/features/receive-otlp
@@ -8,7 +8,7 @@ description: >
8
8
  metadata:
9
9
  type: core
10
10
  library: "@r_masseater/masseater-utils"
11
- library_version: 0.16.0
11
+ library_version: 0.17.0
12
12
  sources:
13
13
  - src
14
14
  - bin
@@ -7,7 +7,7 @@ description: >
7
7
  metadata:
8
8
  type: core
9
9
  library: "@r_masseater/masseater-utils"
10
- library_version: 0.16.0
10
+ library_version: 0.17.0
11
11
  sources:
12
12
  - src/app
13
13
  - src/shared/lib/cache.ts
@@ -8,7 +8,7 @@ description: >
8
8
  metadata:
9
9
  type: core
10
10
  library: "@r_masseater/masseater-utils"
11
- library_version: 0.16.0
11
+ library_version: 0.17.0
12
12
  sources:
13
13
  - src/entities/segment
14
14
  - src/features/map-content
@@ -8,7 +8,7 @@ description: >
8
8
  metadata:
9
9
  type: core
10
10
  library: "@r_masseater/masseater-utils"
11
- library_version: 0.16.0
11
+ library_version: 0.17.0
12
12
  sources:
13
13
  - src/app/app-name.ts
14
14
  - src/features/name-app
@@ -8,7 +8,7 @@ description: >
8
8
  metadata:
9
9
  type: core
10
10
  library: "@r_masseater/masseater-utils"
11
- library_version: 0.16.0
11
+ library_version: 0.17.0
12
12
  sources:
13
13
  - src/app
14
14
  - src/features/run-main/model/hook-io.ts
@@ -9,7 +9,7 @@ description: >
9
9
  metadata:
10
10
  type: core
11
11
  library: "@r_masseater/masseater-utils"
12
- library_version: 0.16.0
12
+ library_version: 0.17.0
13
13
  sources:
14
14
  - src/app
15
15
  - src/entities/package-json
@@ -7,7 +7,7 @@ description: >
7
7
  metadata:
8
8
  type: core
9
9
  library: "@r_masseater/masseater-utils"
10
- library_version: 0.16.0
10
+ library_version: 0.17.0
11
11
  sources:
12
12
  - src/app
13
13
  - src/features/run-main
@@ -12,7 +12,7 @@ description: >
12
12
  metadata:
13
13
  type: core
14
14
  library: "@r_masseater/masseater-utils"
15
- library_version: 0.16.0
15
+ library_version: 0.17.0
16
16
  sources:
17
17
  - src/app
18
18
  - src/entities/rust-item
@@ -9,7 +9,7 @@ description: >
9
9
  metadata:
10
10
  type: core
11
11
  library: "@r_masseater/masseater-utils"
12
- library_version: 0.16.0
12
+ library_version: 0.17.0
13
13
  sources:
14
14
  - src/app
15
15
  - src/features/sink-traces
@@ -9,7 +9,7 @@ description: >
9
9
  metadata:
10
10
  type: core
11
11
  library: "@r_masseater/masseater-utils"
12
- library_version: 0.16.0
12
+ library_version: 0.17.0
13
13
  sources:
14
14
  - src/app
15
15
  - src/entities/embedding/model/text.ts
@@ -9,7 +9,7 @@ description: >
9
9
  metadata:
10
10
  type: core
11
11
  library: "@r_masseater/masseater-utils"
12
- library_version: 0.16.0
12
+ library_version: 0.17.0
13
13
  sources:
14
14
  - src/app
15
15
  - src/shared/api/github
@@ -1 +0,0 @@
1
- {"version":3,"file":"process-l69KvwcT.mjs","names":["Arr","Str"],"sources":["../src/shared/lib/process.ts"],"sourcesContent":["import { Array as Arr, Duration, Effect, Schema, Stream, String as Str } from \"effect\";\nimport type { PlatformError } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\n\nconst SUCCESS = 0;\nconst FORCE_KILL_AFTER_SECONDS = 10;\nconst FORCE_KILL_AFTER = Duration.seconds(FORCE_KILL_AFTER_SECONDS);\n\nconst taggedError = Schema.TaggedError;\n\nexport class CommandFailed extends taggedError<CommandFailed, { readonly brand: unique symbol }>()(\n \"CommandFailed\",\n { message: Schema.String },\n) {}\n\nexport interface Command {\n readonly command: string;\n readonly args: readonly string[];\n readonly env?: Readonly<Record<string, string>>;\n readonly cwd?: string;\n readonly forceKillAfter?: Duration.Input;\n}\n\n/** @internal */\nexport type Spawned<Success> = Effect.Effect<\n Success,\n CommandFailed | PlatformError.PlatformError,\n ChildProcessSpawner.ChildProcessSpawner\n>;\n\nconst failed = ({ command, args }: Command): CommandFailed =>\n CommandFailed.make({ message: `${command} ${Arr.join(args, \" \")} failed` });\n\nconst exitCodeOf = Effect.fn(\"exitCodeOf\")(function* exitCodeOf({\n command,\n args,\n env,\n cwd,\n forceKillAfter = FORCE_KILL_AFTER,\n}: Command) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n return yield* spawner.exitCode(\n ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: true,\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"inherit\",\n forceKillAfter,\n }),\n );\n});\n\nconst succeedsWith = (command: Command): Spawned<boolean> =>\n exitCodeOf(command).pipe(Effect.map((code) => code === SUCCESS));\n\nconst mustSucceedWith = (command: Command): Spawned<void> =>\n succeedsWith(command).pipe(\n Effect.filterOrFail(\n (passed) => passed,\n () => failed(command),\n ),\n Effect.asVoid,\n );\n\nconst collected = Effect.fn(\"collected\")(function* collected({\n command,\n args,\n env,\n cwd,\n forceKillAfter = FORCE_KILL_AFTER,\n}: Command) {\n const handle = yield* ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: true,\n stdin: \"ignore\",\n stderr: \"inherit\",\n forceKillAfter,\n });\n const [output, code] = yield* Effect.all(\n [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],\n { concurrency: \"unbounded\" },\n );\n return { output, code };\n});\n\nconst outputWith = (command: Command): Spawned<string> =>\n collected(command).pipe(\n Effect.scoped,\n Effect.filterOrFail(\n ({ code }) => code === SUCCESS,\n () => failed(command),\n ),\n Effect.map(({ output }) => Str.trim(output)),\n );\n\n/** @internal */\nexport const succeeds = succeedsWith;\n\n/** @internal */\nexport const mustSucceed = mustSucceedWith;\n\nconst finishedWith = (command: Command): Spawned<Readonly<{ output: string; code: number }>> =>\n Effect.scoped(collected(command));\n\n/** @internal */\nexport const outputOf = outputWith;\n\n/** @internal */\nexport const finished = finishedWith;\n"],"mappings":";;;AAIA,MAAM,UAAU;AAEhB,MAAM,mBAAmB,SAAS,QAAQ,EAAwB;AAElE,MAAM,cAAc,OAAO;AAE3B,IAAa,gBAAb,cAAmC,YAA8D,CAAC,CAChG,iBACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;AAiBH,MAAM,UAAU,EAAE,SAAS,WACzB,cAAc,KAAK,EAAE,SAAS,GAAG,QAAQ,GAAGA,MAAI,KAAK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