SLOPSHOPPER

Genshin Mods

Six Claude Code mods: five under one band above the prompt, waypoints (the next steps, one press each), resin (cache, context, limits and cost, with warm…

bandrowsguardcommandtoastprompt
★ 23v?Apache-2.0updated 2026-10-25Esposter/Esposter/packages/genshin-mods
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · genshin-mods
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /commission ⎿ genshin-mods: commission is off. ● Veil on: values are hidden on screen ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
● Veil on: values are hidden on screen
README

genshin-mods

[![Apache-2.0 licensed][badge-license]][url-license] [![NPM version][badge-npm-version]][url-npm] [![NPM downloads][badge-npm-downloads]][url-npm] [![NPM Unpacked Size (with version)][badge-npm-unpacked-size]][url-npm]

A Claude Code plugin of mods: five drawn as one band above the prompt, in the session character's colour (the next steps one press away, what the session is spending with a one-press handoff, recording mode, a goal's task list and clock, and a question before editing a file another session just changed), a delegation guard that refuses any subagent not on haiku and nudges a run of lookups toward a haiku agent, a disk-scan guard that refuses a Bash scan from a root or a home folder, and a whole-index guard that refuses a git command over the whole index while another session shares the checkout.

  • Waypoints — after each answered turn, up to three next steps the session suggests, each a button that sends it as the next prompt.
  • Resin — the prompt cache's time left, the context window, the five-hour and weekly limits and the cost so far, with Warm, Compact and Handoff, a toast before the cache goes cold, and a usage reserve past four-fifths of a limit window, or past half of one spent ahead of an even pace, that has the session clean up on cheap agents, then wind down, until the window resets, refusing a workflow at launch meanwhile.
  • Veil — recording mode: emails, amounts, phone numbers and secrets shown as placeholders while the model still reads the real values.
  • Commission — a goal meter over the session's task list: the goal, tasks done, the share complete and the minutes since it started.
  • Ward — before an edit to a file another session changed in the last half hour, a question: proceed, move to a worktree, or cancel.
  • Delegation guard — every subagent launch not on haiku refused, a fork included, and after every third lookup in a row with no decision between them, a note on that call's result that the chain goes to a haiku agent as one bounded question.
  • Disk-scan guard — a Bash find, du, grep -r or ls -R that starts at /, a drive, ~ or a home folder is refused, with the known place to look for the file.
  • Pulse — keeps the machine watcher running from any session with the plugin, so its heartbeat and the machine's state keep being written.
  • Whole-index guard — while another session edits this checkout, a Bash git add ., git add -A, git reset with no path, git stash, git checkout . or git clean is refused, with the path-scoped form to use instead.

Table of Contents


<a name="getting-started">🚀 Getting Started</a>

This repository is a Claude Code plugin marketplace named esposter:

claude plugin marketplace add Esposter/Esposter
claude plugin install genshin-mods@esposter

A clone of this repository needs neither command: .agents/settings.json enables the plugin at project scope once you trust the repository. With genshin-persona installed beside it, the band takes the session character's colour; without it, the game's interface gold.

Developing the plugin from a checkout loads the directory itself, with the installed copy disabled so only one of them answers:

claude plugin disable genshin-mods@esposter
claude --plugin-dir packages/genshin-mods

<a name="documentation">📖 Documentation</a>

We highly recommend you take a look at the documentation to level up.

Command reference

Each mod is switched by its own slash command; bare, it flips, and the choice is kept across sessions:

CommandWhat it does
`/waypoints [on \off]`Suggests the next steps after each answered turn, or stops
`/resin [on \off]`Shows the cache, context, limits and cost row and its warning toast
`/veil [on \off]`Turns recording mode on or off; off by default
`/commission [on \off]`Shows the goal meter while a turn works through a task list
`/pulse [on \off]`Keeps the machine watcher running, or stops
`/ward [on \off]`Asks before an edit to a file another session just changed, and refuses a whole-index git command while one shares the checkout

With the band focused (a click or ctrl+x tab), w, c and h warm, compact and hand off, 1 to 3 send a waypoint and g opens or closes the whole task list.

Commands

Run from packages/genshin-mods/:

pnpm test         # vitest watch mode (coverage is run from the repo root)
pnpm validate     # claude plugin validate: the engine's own reading of the hooks module
pnpm lint:fix     # auto-fix lint

<a name="license">⚖️ License</a>

This project is licensed under the Apache-2.0 license.

[badge-license]: https://img.shields.io/github/license/Esposter/Esposter.svg?color=blue [url-license]: https://github.com/Esposter/Esposter/blob/main/LICENSE [badge-npm-version]: https://img.shields.io/npm/v/genshin-mods/latest?color=brightgreen [url-npm]: https://www.npmjs.com/package/genshin-mods/v/latest [badge-npm-unpacked-size]: https://img.shields.io/npm/unpacked-size/genshin-mods/latest?label=npm [badge-npm-downloads]: https://img.shields.io/npm/dm/genshin-mods.svg

Source 52 files
src/register.ts 24 lines
1import type { Register } from "claude-code";
2
3import { registerBand } from "./services/band/registerBand";
4import { registerCommission } from "./services/commission/registerCommission";
5import { registerDelegation } from "./services/delegation/registerDelegation";
6import { registerDiskScan } from "./services/diskScan/registerDiskScan";
7import { registerLifecycle } from "./services/registerLifecycle";
8import { registerReserveGate } from "./services/resin/registerReserveGate";
9import { registerVeil } from "./services/veil/registerVeil";
10import { registerWard } from "./services/ward/registerWard";
11import { registerWholeIndex } from "./services/ward/registerWholeIndex";
12
13export const register: Register = (on) => {
14  registerBand(on);
15  registerCommission(on);
16  registerDelegation(on);
17  registerDiskScan(on);
18  registerLifecycle(on);
19  registerReserveGate(on);
20  registerVeil(on);
21  registerWard(on);
22  registerWholeIndex(on);
23};
24
src/services/band/registerBand.ts 216 lines
1import type { EngineInterface, On, RenderElement, RenderInput } from "claude-code";
2
3import { atom, read, update } from "claude-code";
4
5import type { EnabledMods } from "../../../types";
6
7import { ACCENT_COLOR, HANDOFF_QUESTION, MAX_SHOWN_TASKS, WARM_QUESTION } from "../constants";
8import { InitialState } from "../InitialState";
9import { getResinFigures } from "../resin/getResinFigures";
10import { getCommissionSummary } from "./getCommissionSummary";
11
12// The plugin's one band, a row per mod with something to say. `$` is followed only into functions in the file that
13// Hooked it, so each row and each button's action lives here beside the hook
14const commissionAtom = atom({ key: "commission", plugin: "genshin-mods" } as const, InitialState.commission);
15const enabledModsAtom = atom({ key: "enabledMods", plugin: "genshin-mods" } as const, InitialState.enabledMods);
16const isCommissionExpandedAtom = atom(
17  { key: "isCommissionExpanded", plugin: "genshin-mods" } as const,
18  InitialState.isCommissionExpanded,
19);
20const isHandingOffAtom = atom({ key: "isHandingOff", plugin: "genshin-mods" } as const, InitialState.isHandingOff);
21const lastCacheRequestAtAtom = atom(
22  { key: "lastCacheRequestAt", plugin: "genshin-mods" } as const,
23  InitialState.lastCacheRequestAt,
24);
25const nowAtom = atom({ key: "now", plugin: "genshin-mods" } as const, InitialState.now);
26const waypointsAtom = atom({ key: "waypoints", plugin: "genshin-mods" } as const, InitialState.waypoints);
27
28// The engine's press slot takes no promise; every action here resolves each of its outcomes itself
29const press = (action: () => Promise<unknown>) => () => {
30  // oxlint-disable-next-line typescript/no-floating-promises -- The press slot is the engine's and returns nothing
31  action();
32};
33
34const StatusMarkMap = { completed: "✓", in_progress: "▸", pending: "·" } as const;
35
36// A fork re-sends the conversation's prefix, which renews the cache from the moment it is sent, and adds no row to the
37// Transcript
38const warmCache = async ($: EngineInterface) => {
39  const requestedAt = await $.clock.now();
40  const answer = await $.model.fork({ prompt: WARM_QUESTION });
41  if (!answer.isAnswered) {
42    $.ui.toast(`The cache was not warmed: ${answer.reason}.`);
43    return;
44  }
45
46  await update($, lastCacheRequestAtAtom, () => requestedAt);
47  await update($, nowAtom, () => requestedAt);
48};
49
50// The whole relay in one press: the clear waits for the handoff text, so a fork that fails clears nothing
51const relay = async ($: EngineInterface) => {
52  const answer = await $.model.fork({ prompt: HANDOFF_QUESTION });
53  if (answer.isAnswered && answer.text.trim()) {
54    await $.command.run({ command: "clear" });
55    await $.prompt.submit({ text: answer.text });
56  } else $.ui.toast(`The handoff was not written: ${answer.isAnswered ? "it came back empty" : answer.reason}.`);
57};
58
59// The relay is settled rather than awaited, so a clear or submit that rejects still brings the buttons back
60const handOff = async ($: EngineInterface) => {
61  await update($, isHandingOffAtom, () => true);
62  const [outcome] = await Promise.allSettled([relay($)]);
63  await update($, isHandingOffAtom, () => false);
64  if (outcome.status === "rejected") $.ui.toast(`The handoff failed: ${String(outcome.reason)}.`);
65};
66
67// The session character's colour, which the persona publishes, else the game's interface gold
68const readAccent = async ($: EngineInterface) =>
69  (await read($, { key: "character", plugin: "genshin-persona" } as const))?.color || ACCENT_COLOR;
70
71const drawResinRow = async (
72  $: EngineInterface,
73  e: RenderInput<"AbovePrompt">,
74  enabledMods: EnabledMods,
75  accent: string,
76): Promise<RenderElement | undefined> => {
77  const lastCacheRequestAt = await read($, lastCacheRequestAtAtom);
78  if (lastCacheRequestAt === 0 || !enabledMods.resin) return undefined;
79
80  const figures = getResinFigures(await $.session.usage(), lastCacheRequestAt, await read($, nowAtom));
81  const isHandingOff = await read($, isHandingOffAtom);
82  const { Box, Button, Text } = $.ui.resolve(e);
83  return Box({
84    children: [
85      Text({ bold: true, children: "Resin  ", color: accent }),
86      ...figures.map(({ isWarning, label, text }) =>
87        Text({ children: `${label} ${text}  `, color: isWarning ? "yellow" : undefined, dimColor: !isWarning }),
88      ),
89      isHandingOff
90        ? Text({ children: "writing the handoff…", dimColor: true })
91        : Box({
92            children: [
93              Button({ hotkey: "w", key: "resin-warm", label: "Warm", onPress: press(() => warmCache($)) }),
94              Button({
95                hotkey: "c",
96                key: "resin-compact",
97                label: "Compact",
98                onPress: press(() => $.session.compact()),
99              }),
100              Button({
101                hotkey: "h",
102                key: "resin-handoff",
103                label: "Handoff",
104                onPress: press(() => handOff($)),
105                variant: "primary",
106              }),
107            ],
108            flexDirection: "row",
109          }),
110    ],
111    flexDirection: "row",
112    flexWrap: "wrap",
113  });
114};
115
116const drawCommissionRow = async (
117  $: EngineInterface,
118  e: RenderInput<"AbovePrompt">,
119  enabledMods: EnabledMods,
120  accent: string,
121): Promise<RenderElement | undefined> => {
122  const commission = await read($, commissionAtom);
123  if (commission.tasks.length === 0 || !enabledMods.commission) return undefined;
124
125  const isExpanded = await read($, isCommissionExpandedAtom);
126  const shownTasks = isExpanded
127    ? commission.tasks.slice(0, MAX_SHOWN_TASKS)
128    : commission.tasks.filter(({ status }) => status === "in_progress");
129  const { Box, Button, Text } = $.ui.resolve(e);
130  return Box({
131    children: [
132      Box({
133        children: [
134          Text({ bold: true, children: "Commission  ", color: accent }),
135          Text({ children: `${getCommissionSummary(commission, await read($, nowAtom))}  `, wrap: "truncate-end" }),
136          Button({
137            hotkey: "g",
138            key: "commission-expand",
139            label: isExpanded ? "Fewer" : "All tasks",
140            onPress: press(() => update($, isCommissionExpandedAtom, (value) => !value)),
141            plain: true,
142          }),
143        ],
144        flexDirection: "row",
145      }),
146      ...shownTasks.map(({ status, subject }) =>
147        Text({
148          children: `  ${StatusMarkMap[status]} ${subject}`,
149          dimColor: status !== "in_progress",
150          wrap: "truncate-end",
151        }),
152      ),
153    ],
154    flexDirection: "column",
155  });
156};
157
158const drawWaypointsRow = async (
159  $: EngineInterface,
160  e: RenderInput<"AbovePrompt">,
161  enabledMods: EnabledMods,
162  accent: string,
163): Promise<RenderElement | undefined> => {
164  const waypoints = await read($, waypointsAtom);
165  if (waypoints.length === 0 || e.props.isWorking || !enabledMods.waypoints) return undefined;
166
167  const { Box, Button, Text } = $.ui.resolve(e);
168  return Box({
169    children: [
170      Text({ bold: true, children: "Waypoints", color: accent }),
171      ...waypoints.map((waypoint, index) =>
172        Button({
173          hotkey: `${index + 1}`,
174          key: `waypoint-${index}`,
175          label: waypoint,
176          onPress: press(() => $.prompt.submit({ text: waypoint })),
177          plain: true,
178        }),
179      ),
180      Button({
181        key: "waypoints-dismiss",
182        label: "Dismiss",
183        onPress: press(() => update($, waypointsAtom, () => InitialState.waypoints)),
184        plain: true,
185        role: "dismiss",
186      }),
187    ],
188    flexDirection: "column",
189  });
190};
191
192// The veil's marker first, so a recording never runs with it off unnoticed, and the engine's own band whenever no
193// Mod has anything to say
194export const registerBand = (on: On): void => {
195  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
196    if (e.props.hasSurvey) return next(e);
197
198    const enabledMods = await read($, enabledModsAtom);
199    const accent = await readAccent($);
200    const rows = (
201      await Promise.all([
202        drawResinRow($, e, enabledMods, accent),
203        drawCommissionRow($, e, enabledMods, accent),
204        drawWaypointsRow($, e, enabledMods, accent),
205      ])
206    ).filter((row) => row !== undefined);
207    if (rows.length === 0 && !enabledMods.veil) return next(e);
208
209    const { Box, Text } = $.ui.resolve(e);
210    const marker = enabledMods.veil
211      ? [Text({ bold: true, children: "● Veil on: values are hidden on screen", color: "red" })]
212      : [];
213    return Box({ children: [...marker, ...rows], flexDirection: "column" });
214  });
215};
216
src/services/commission/registerCommission.ts 49 lines
1import type { EngineInterface, On } from "claude-code";
2
3import { atom, read, update } from "claude-code";
4
5import type { TaskCall } from "../../models/TaskCall";
6
7import { TaskTool } from "../../models/TaskTool";
8import { InitialState } from "../InitialState";
9import { foldTaskCall } from "./foldTaskCall";
10
11const commissionAtom = atom({ key: "commission", plugin: "genshin-mods" } as const, InitialState.commission);
12const enabledModsAtom = atom({ key: "enabledMods", plugin: "genshin-mods" } as const, InitialState.enabledMods);
13const lastPromptAtom = atom({ key: "lastPrompt", plugin: "genshin-mods" } as const, InitialState.lastPrompt);
14
15// A task tool's call folded in once the tool has answered, opening the commission on its first task with the goal
16// Read off the prompt that started the turn
17const fold = async ($: EngineInterface, call: TaskCall) => {
18  if (!(await read($, enabledModsAtom)).commission) return;
19  const now = await $.clock.now();
20  const lastPrompt = await read($, lastPromptAtom);
21  await update($, commissionAtom, (commission) => ({
22    goal: commission.goal || (lastPrompt.split("\n").find(Boolean) ?? "").trim(),
23    openedAt: commission.openedAt || now,
24    tasks: foldTaskCall(commission.tasks, call),
25  }));
26};
27
28export const registerCommission = (on: On): void => {
29  on("tool.call", { tool: "TaskCreate" }, async ($, e, next) => {
30    const result = await next(e);
31    if (!result.deny && !result.isError && result.result)
32      await fold($, { id: result.result.task.id, subject: e.subject, tool: TaskTool.TaskCreate });
33    return result;
34  });
35
36  on("tool.call", { tool: "TaskUpdate" }, async ($, e, next) => {
37    const result = await next(e);
38    if (!result.deny && !result.isError)
39      await fold($, { id: e.taskId, status: e.status, subject: e.subject, tool: TaskTool.TaskUpdate });
40    return result;
41  });
42
43  on("tool.call", { tool: "TodoWrite" }, async ($, e, next) => {
44    const result = await next(e);
45    if (!result.deny && !result.isError) await fold($, { todos: e.todos, tool: TaskTool.TodoWrite });
46    return result;
47  });
48};
49
src/services/delegation/registerDelegation.ts 47 lines
1import type { EngineInterface, On } from "claude-code";
2
3import { atom, update } from "claude-code";
4
5import type { DelegationCall } from "../../models/DelegationCall";
6
7import { DelegationStep } from "../../models/DelegationStep";
8import { InitialState } from "../InitialState";
9import { getCallStep } from "./getCallStep";
10import { getLaunchRefusal } from "./getLaunchRefusal";
11import { getNextStreak } from "./getNextStreak";
12import { getNudge } from "./getNudge";
13
14const lookupStreakAtom = atom({ key: "lookupStreak", plugin: "genshin-mods" } as const, InitialState.lookupStreak);
15
16// The count is one update, so calls the model sends in one batch each see the count the call before them left. The
17// Nudge is the count's, and a neutral call earns none
18const countCall = async ($: EngineInterface, call: DelegationCall): Promise<string | undefined> => {
19  const step = getCallStep(call);
20  if (step === DelegationStep.Neutral) return undefined;
21  const streak = await update($, lookupStreakAtom, (value) => getNextStreak(value, step));
22  return step === DelegationStep.Lookup ? getNudge(streak) : undefined;
23};
24
25// Any failure lets the call through, as the ward's does: a count that blocked on its own failure would block every
26// Call after it. `next` is replay-safe here, so a call the hook had already counted is not run twice
27const letCallThrough = <E, R>(_$: EngineInterface, e: E, next: (e: E) => R): R => next(e);
28
29export const registerDelegation = (on: On): void => {
30  // An agent launch on any model but haiku is refused before it counts. A nudge rides on the call's own result as
31  // Context the model reads after it, and never blocks the call
32  // eslint-disable-next-line no-restricted-syntax -- The engine's registration handler, run when the hook rejects, not a promise
33  on(
34    "tool.call",
35    { tool: ["Agent", "Bash", "Edit", "Glob", "Grep", "NotebookEdit", "PowerShell", "Read", "WebFetch", "Write"] },
36    async ($, e, next) => {
37      const refusal = e.tool === "Agent" ? getLaunchRefusal(e) : undefined;
38      if (refusal !== undefined) return { deny: refusal };
39      const nudge = await countCall($, e);
40      const result = await next(e);
41      return nudge !== undefined && result.deny === undefined
42        ? { ...result, context: [...(result.context ?? []), nudge] }
43        : result;
44    },
45  ).catch(letCallThrough);
46};
47
src/services/diskScan/registerDiskScan.ts 18 lines
1import type { EngineInterface, On } from "claude-code";
2
3import { getDenyReason, getDiskScanRefusal } from "./getDiskScanRefusal";
4
5// Any failure lets the command through, as the ward's and the delegation guard's do: a guard that blocked on its own
6// Failure would block every command after it
7const letCommandThrough = <E, R>(_$: EngineInterface, e: E, next: (e: E) => R): R => next(e);
8
9// A Bash command that scans from a root or a home folder is refused before it runs: the scan reads the whole disk for
10// A file whose home is known, and the rule is cheapest enforced at the call itself
11export const registerDiskScan = (on: On): void => {
12  // eslint-disable-next-line no-restricted-syntax -- The engine's registration handler, run when the hook rejects, not a promise
13  on("tool.call", { tool: "Bash" }, (_$, e, next) => {
14    const refusal = getDiskScanRefusal(e.command);
15    return refusal === undefined ? next(e) : { deny: getDenyReason(refusal) };
16  }).catch(letCommandThrough);
17};
18
src/services/registerLifecycle.ts 227 lines
1import type { EngineInterface, On } from "claude-code";
2
3import { atom, read, update } from "claude-code";
4
5import type { EnabledMods } from "../../types";
6
7import {
8  CACHE_WARNING_MS,
9  MACHINE_WATCHER_RETRY_MILLISECONDS,
10  MACHINE_WATCHER_SCRIPT,
11  RESERVE_SECTION_ID,
12  VEIL_SECTION_ID,
13  VEIL_SYSTEM_SECTION,
14  WAYPOINTS_QUESTION,
15} from "./constants";
16import { InitialState } from "./InitialState";
17import { ModDescriptionMap, ModNames } from "./ModDescriptionMap";
18import { getCacheRemainingMs } from "./resin/getCacheRemainingMs";
19import { getCacheWarningDelayMs } from "./resin/getCacheWarningDelayMs";
20import { getReserveSummary } from "./resin/getReserveSummary";
21import { getReserveWindow } from "./resin/getReserveWindow";
22import { reserveText } from "./resin/reserveText";
23import { parseWaypoints } from "./waypoints/parseWaypoints";
24
25const commissionAtom = atom({ key: "commission", plugin: "genshin-mods" } as const, InitialState.commission);
26const enabledModsAtom = atom({ key: "enabledMods", plugin: "genshin-mods" } as const, InitialState.enabledMods);
27const isCommissionExpandedAtom = atom(
28  { key: "isCommissionExpanded", plugin: "genshin-mods" } as const,
29  InitialState.isCommissionExpanded,
30);
31const lastPromptAtom = atom({ key: "lastPrompt", plugin: "genshin-mods" } as const, InitialState.lastPrompt);
32const lastCacheRequestAtAtom = atom(
33  { key: "lastCacheRequestAt", plugin: "genshin-mods" } as const,
34  InitialState.lastCacheRequestAt,
35);
36const lookupStreakAtom = atom({ key: "lookupStreak", plugin: "genshin-mods" } as const, InitialState.lookupStreak);
37const nowAtom = atom({ key: "now", plugin: "genshin-mods" } as const, InitialState.now);
38const reserveWindowAtom = atom({ key: "reserveWindow", plugin: "genshin-mods" } as const, InitialState.reserveWindow);
39const waypointsAtom = atom({ key: "waypoints", plugin: "genshin-mods" } as const, InitialState.waypoints);
40
41// The events a plugin may hook once with no matcher, each hooked here for every mod, with the commands that switch
42// The mods. Neither variable is drawn: the expiry already warned about, so each warns once, and whether a turn is
43// Renewing the cache itself, when no warning is owed
44let warnedLastCacheRequestAt = 0;
45let isTurnRunning = false;
46
47// The cache goes cold at a known instant, so its warning is one timer armed for that instant at each turn's end, from the
48// Request that last read or wrote the cache, rather than a check on a clock. The timer warns once for that request, and
49// Stands down while a turn runs, since that turn's end arms it again. A timer left from an earlier turn finds the cache
50// Renewed and does nothing more than the warning it would have given
51const warnCache = async ($: EngineInterface) => {
52  const now = await $.clock.now();
53  await update($, nowAtom, () => now);
54  const lastCacheRequestAt = await read($, lastCacheRequestAtAtom);
55  const remainingMs = getCacheRemainingMs(lastCacheRequestAt, now);
56  const isWarningDue = lastCacheRequestAt > 0 && remainingMs > 0 && remainingMs <= CACHE_WARNING_MS;
57  if (
58    !isWarningDue ||
59    isTurnRunning ||
60    warnedLastCacheRequestAt === lastCacheRequestAt ||
61    !(await read($, enabledModsAtom)).resin
62  )
63    return;
64
65  warnedLastCacheRequestAt = lastCacheRequestAt;
66  $.ui.toast("The prompt cache goes cold in five minutes: warm it, compact or hand off from the band.");
67};
68
69const armCacheWarning = async ($: EngineInterface) => {
70  const delayMs = getCacheWarningDelayMs(await read($, lastCacheRequestAtAtom), await $.clock.now());
71  if (delayMs === undefined) return;
72
73  $.clock.after(delayMs, () => {
74    // oxlint-disable-next-line typescript/no-floating-promises -- The engine's timer slot takes no promise, and every call in the warning resolves
75    warnCache($);
76  });
77};
78
79const suggestWaypoints = async ($: EngineInterface) => {
80  const answer = await $.model.fork({ prompt: WAYPOINTS_QUESTION });
81  if (answer.isAnswered) await update($, waypointsAtom, () => parseWaypoints(answer.text));
82};
83
84// Keeps the machine watcher running as this session's child. The watcher writes the machine's state, holds its lock and
85// Pushes its heartbeat, so its output is read only to keep the child's pipe drained. A watcher exits at once while another
86// Session's holds the machine's lock, so each exit starts the watcher again after a wait, and the session that outlives the
87// One watching takes the watching over
88const watchPulse = async ($: EngineInterface) => {
89  if (!(await read($, enabledModsAtom)).pulse) return;
90
91  const cwd = await $.session.cwd();
92  if (!(await $.fs.exists(`${cwd}/${MACHINE_WATCHER_SCRIPT}`))) return;
93
94  // oxlint-disable-next-line no-underscore-dangle -- The chunks are discarded, and the binding is only the loop's syntax
95  for await (const _chunk of $.process.spawn({ argv: ["pnpm", "ai:machine:watch"], cwd })) {
96    // The watcher's output is discarded, since nothing in the session reads it
97  }
98
99  $.clock.after(MACHINE_WATCHER_RETRY_MILLISECONDS, () => {
100    // oxlint-disable-next-line typescript/no-floating-promises -- The engine's timer slot takes no promise, and the watcher's run settles as its process exits
101    watchPulse($);
102  });
103};
104
105const closeCommission = async ($: EngineInterface) => {
106  await update($, commissionAtom, () => InitialState.commission);
107  await update($, isCommissionExpandedAtom, () => InitialState.isCommissionExpanded);
108};
109
110export const registerLifecycle = (on: On): void => {
111  // The bare command flips a mod and an argument sets it, kept in the store so it holds for every later session
112  for (const name of ModNames)
113    on("command.run", { command: name }, async ($, e) => {
114      const argument = e.args.trim().toLowerCase();
115      const enabledMods = await update($, enabledModsAtom, (value) => ({
116        ...value,
117        [name]: argument ? argument === "on" : !value[name],
118      }));
119      await $.store.set(enabledModsAtom.ref.key, enabledMods);
120      return { text: `${name} is ${enabledMods[name] ? "on" : "off"}.` };
121    });
122
123  on("session.start", async ($, e, next) => {
124    const stored = (await $.store.get(enabledModsAtom.ref.key)) as Partial<EnabledMods> | undefined;
125    await update($, enabledModsAtom, (value) => ({ ...value, ...stored }));
126    await Promise.all(
127      ModNames.map((name) =>
128        $.command.register({ argumentHint: "[on|off]", description: ModDescriptionMap[name], name }),
129      ),
130    );
131    watchPulse($);
132    return next(e);
133  });
134
135  // A `/clear` or a resume carries on in this process under another conversation, with no `session.start` for it, so
136  // Nothing the old one showed is kept
137  on("session.end", async ($, e, next) => {
138    if (e.reason === "clear" || e.reason === "resume") {
139      await update($, lastCacheRequestAtAtom, () => InitialState.lastCacheRequestAt);
140      await update($, waypointsAtom, () => InitialState.waypoints);
141      await closeCommission($);
142    }
143
144    return next(e);
145  });
146
147  // The prompt is kept as the goal of a commission this turn may open, and a commission whose every task is done has
148  // Shown its finished row since the last turn ended, so it closes as the person moves on. A new prompt also starts
149  // The lookup count again, since the lookups of the last turn are not the chain of this one
150  on("prompt.submit", async ($, e, next) => {
151    await update($, waypointsAtom, () => InitialState.waypoints);
152    await update($, lookupStreakAtom, () => InitialState.lookupStreak);
153    await update($, lastPromptAtom, () => e.text);
154    const { tasks } = await read($, commissionAtom);
155    if (tasks.length > 0 && tasks.every(({ status }) => status === "completed")) await closeCommission($);
156    return next(e);
157  });
158
159  // While the veil is on, the model is told to write placeholders too, so a reply never holds a value to hide. While a
160  // Usage reserve holds and the resin mod is on, the model is told what the reserve's tier asks until the window resets,
161  // Which it may have done since the last measurement
162  on("prompt.compose", async ($, e, next) => {
163    const result = await next(e);
164    const { resin, veil } = await read($, enabledModsAtom);
165    const reserveWindow = await read($, reserveWindowAtom);
166    const sections = [...result.sections];
167    if (veil) sections.push({ id: VEIL_SECTION_ID, scope: "session", text: VEIL_SYSTEM_SECTION });
168    if (resin && reserveWindow.name && Date.parse(reserveWindow.resetsAt) > (await $.clock.now()))
169      sections.push({ id: RESERVE_SECTION_ID, scope: "session", text: reserveText(reserveWindow) });
170    return { sections };
171  });
172
173  on("turn.start", (_$, e, next) => {
174    isTurnRunning = true;
175    return next(e);
176  });
177
178  // The cache's lifetime runs from the request that read or wrote it, so each of the main conversation's requests
179  // Restarts the countdown as it is sent, not as its reply ends
180  on("turn.step", async function* ($, e, next) {
181    if (e.agentId === undefined) {
182      const now = await $.clock.now();
183      await update($, lastCacheRequestAtAtom, () => now);
184      await update($, nowAtom, () => now);
185    }
186
187    return yield* next(e);
188  });
189
190  // An answer of the main conversation asks for waypoints off the turn's own dispatch, so the fork never holds the
191  // Turn's end or the next prompt behind it
192  on("turn.complete", async ($, e, next) => {
193    const result = await next(e);
194    if (e.agentId !== undefined) return result;
195
196    isTurnRunning = false;
197
198    const now = await $.clock.now();
199    await update($, nowAtom, () => now);
200    await armCacheWarning($);
201    if (e.reason === "answer" && (await read($, enabledModsAtom)).waypoints)
202      $.clock.after(0, () => {
203        // oxlint-disable-next-line typescript/no-floating-promises -- The engine's timer slot takes no promise, and a fork resolves every outcome rather than rejecting
204        suggestWaypoints($);
205      });
206    return result;
207  });
208
209  // The reserve is read off each measurement: it starts at the first window past a tier's line and lifts at the
210  // Measurement a window's reset raises, which finds none. The toast names the window once, as the reserve starts, and
211  // Again as its maintenance tier is raised to the wind-down
212  on("session.measure", async ($, e, next) => {
213    const now = await $.clock.now();
214    const reserveWindow = getReserveWindow(e.rateLimits, now);
215    const previousReserveWindow = await read($, reserveWindowAtom);
216    await update($, reserveWindowAtom, () => reserveWindow ?? InitialState.reserveWindow);
217    if (
218      reserveWindow &&
219      (!previousReserveWindow.name || (reserveWindow.isWindDown && !previousReserveWindow.isWindDown)) &&
220      (await read($, enabledModsAtom)).resin
221    )
222      $.ui.toast(`${getReserveSummary(reserveWindow)}.`);
223
224    return next(e);
225  });
226};
227
src/services/resin/registerReserveGate.ts 28 lines
1import type { EngineInterface, On } from "claude-code";
2
3import { atom, read } from "claude-code";
4
5import { RESERVE_REFUSAL_INSTRUCTION } from "../constants";
6import { InitialState } from "../InitialState";
7import { getReserveSummary } from "./getReserveSummary";
8
9const enabledModsAtom = atom({ key: "enabledMods", plugin: "genshin-mods" } as const, InitialState.enabledMods);
10const reserveWindowAtom = atom({ key: "reserveWindow", plugin: "genshin-mods" } as const, InitialState.reserveWindow);
11
12// Any failure lets the launch through, as the ward's does: a gate that blocked on its own failure would block every
13// Launch after it. `next` is replay-safe here, so a launch the hook had already decided is not run twice
14const letLaunchThrough = <E, R>(_$: EngineInterface, e: E, next: (e: E) => R): R => next(e);
15
16export const registerReserveGate = (on: On): void => {
17  // The section only describes the reserve, and a workflow already launched never reads it, so the launch itself is
18  // Refused while the reserve holds, past the window's reset too, which the next measurement is yet to read. An agent
19  // Launch is the delegation guard's, which refuses one on any model but haiku whether or not a reserve holds
20  // eslint-disable-next-line no-restricted-syntax -- The engine's registration handler, run when the hook rejects, not a promise
21  on("tool.call", { tool: ["Workflow"] }, async ($, e, next) => {
22    if (!(await read($, enabledModsAtom)).resin) return next(e);
23    const reserveWindow = await read($, reserveWindowAtom);
24    if (!reserveWindow.name || Date.parse(reserveWindow.resetsAt) <= (await $.clock.now())) return next(e);
25    return { deny: `${getReserveSummary(reserveWindow)}. ${RESERVE_REFUSAL_INSTRUCTION}` };
26  }).catch(letLaunchThrough);
27};
28
src/services/veil/registerVeil.ts 33 lines
1import type { On } from "claude-code";
2
3import { atom, read } from "claude-code";
4
5import { InitialState } from "../InitialState";
6import { veilText } from "./veilText";
7import { veilValue } from "./veilValue";
8
9const enabledModsAtom = atom({ key: "enabledMods", plugin: "genshin-mods" } as const, InitialState.enabledMods);
10
11// Only the drawing changes: the transcript and what the model reads keep the real values. Each read subscribes the
12// Row, so switching the veil redraws every row already on screen. The instruction the veil adds to the system prompt is
13// An unmatched hook, so it is the lifecycle file's
14export const registerVeil = (on: On): void => {
15  on("ui.render", { component: "AssistantMessage" }, async ($, e, next) =>
16    (await read($, enabledModsAtom)).veil
17      ? next({ ...e, props: { ...e.props, text: veilText(e.props.text) } })
18      : next(e),
19  );
20
21  on("ui.render", { component: "UserMessage" }, async ($, e, next) =>
22    (await read($, enabledModsAtom)).veil
23      ? next({ ...e, props: { ...e.props, text: veilText(e.props.text) } })
24      : next(e),
25  );
26
27  on("ui.render", { component: "ToolResult" }, async ($, e, next) =>
28    (await read($, enabledModsAtom)).veil
29      ? next({ ...e, props: { ...e.props, output: veilValue(e.props.output) } })
30      : next(e),
31  );
32};
33
src/services/ward/registerWard.ts 70 lines
1import type { EngineInterface, On, ToolCallResult } from "claude-code";
2
3import { atom, read } from "claude-code";
4
5import { WardAnswer, WardAnswers } from "../../models/WardAnswer";
6import { InitialState } from "../InitialState";
7import { getCollidingRecord } from "./getCollidingRecord";
8import { getRecordsWithEdit } from "./getRecordsWithEdit";
9import { readRecords } from "./readRecords";
10import { resolveRecordsPath } from "./resolveRecordsPath";
11
12const enabledModsAtom = atom({ key: "enabledMods", plugin: "genshin-mods" } as const, InitialState.enabledMods);
13const AGE_FORMATTER = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
14
15// Before the edit: the question, when another session's record calls for one. After it: the edit recorded
16const ward = async (
17  $: EngineInterface,
18  path: string,
19  proceed: () => Promise<ToolCallResult>,
20): Promise<ToolCallResult> => {
21  if (!(await read($, enabledModsAtom)).ward) return proceed();
22  const recordsPath = await resolveRecordsPath($);
23  const sessionId = await $.session.id();
24  const now = await $.clock.now();
25  const collision = getCollidingRecord((await readRecords($, recordsPath))[path], sessionId, now);
26  // A session nobody watches has nobody to ask, and a guard that blocks unattended work is worse than none
27  if (collision && (await $.session.surfaces()).length > 0) {
28    const minutes = -Math.round(Temporal.Duration.from({ milliseconds: now - collision.editedAt }).total("minutes"));
29    const age = AGE_FORMATTER.format(minutes, "minute");
30    const answer = await $.ui.ask(`Another session edited ${path} ${age}. Edit it here too?`, {
31      header: "Ward",
32      options: WardAnswers,
33    });
34    if (answer === WardAnswer.Worktree)
35      return {
36        deny: `The person asked to move this work into a git worktree before editing ${path}: another session changed it ${age}. Enter a worktree, then carry on there.`,
37      };
38    else if (answer === WardAnswer.Cancel)
39      return { deny: `The person stopped this edit: another session changed ${path} ${age}.` };
40    else if (answer !== WardAnswer.Proceed) return { deny: `The person stopped this edit and said: ${answer}` };
41  }
42
43  const result = await proceed();
44  if (!result.deny && !result.isError) {
45    const records = getRecordsWithEdit(await readRecords($, recordsPath), path, {
46      editedAt: await $.clock.now(),
47      sessionId,
48    });
49    await $.fs.write(recordsPath, JSON.stringify(records));
50  }
51
52  return result;
53};
54
55// Any failure lets the edit through, the question dismissed or the record unreadable alike: a guard that blocked on
56// Its own failure would block every edit after it, and Cancel is the person's way to stop one. `next` is replay-safe
57// Here, so an edit the hook had already made is not made twice
58const letEditThrough = <E, R>(_$: EngineInterface, e: E, next: (e: E) => R): R => next(e);
59
60export const registerWard = (on: On): void => {
61  // eslint-disable-next-line no-restricted-syntax -- The engine's registration handler, run when the hook rejects, not a promise
62  on("tool.call", { tool: "Edit" }, ($, e, next) => ward($, e.file_path, () => next(e))).catch(letEditThrough);
63  // eslint-disable-next-line no-restricted-syntax -- The engine's registration handler, run when the hook rejects, not a promise
64  on("tool.call", { tool: "Write" }, ($, e, next) => ward($, e.file_path, () => next(e))).catch(letEditThrough);
65  // eslint-disable-next-line no-restricted-syntax -- The engine's registration handler, run when the hook rejects, not a promise
66  on("tool.call", { tool: "NotebookEdit" }, ($, e, next) => ward($, e.notebook_path, () => next(e))).catch(
67    letEditThrough,
68  );
69};
70
src/services/ward/registerWholeIndex.ts 50 lines
1import type { EngineInterface, On, ToolCallResult } from "claude-code";
2
3import { atom, read } from "claude-code";
4
5import { InitialState } from "../InitialState";
6import { joinDirectory } from "../shell/joinDirectory";
7import { getCheckoutPeer } from "./getCheckoutPeer";
8import { getParentFolder } from "./getParentFolder";
9import { getWholeIndexDenyReason, getWholeIndexRefusal } from "./getWholeIndexRefusal";
10import { readRecords } from "./readRecords";
11import { resolveRecordsPath } from "./resolveRecordsPath";
12
13const enabledModsAtom = atom({ key: "enabledMods", plugin: "genshin-mods" } as const, InitialState.enabledMods);
14
15// The nearest folder at or above `folder` holding a `.git`, a worktree's file included, undefined when none does
16const findCheckoutRoot = async ($: EngineInterface, folder: string): Promise<string | undefined> => {
17  if (await $.fs.exists(`${folder}/.git`)) return folder;
18  const parent = getParentFolder(folder);
19  return parent === undefined ? undefined : findCheckoutRoot($, parent);
20};
21
22// The checkout a session's git commands run in: the folder with the `.git`, or the session's own folder where none is
23const getCheckoutRoot = async ($: EngineInterface, cwd: string): Promise<string> =>
24  (await findCheckoutRoot($, cwd)) ?? cwd;
25
26// A whole-index git command is refused while the ward's records show another session editing the checkout it runs in,
27// The session's folder moved by a `cd` before it and by its `-C`. With the Ward off nothing is recorded, so there is no
28// Peer to see and the command runs
29const wholeIndex = async (
30  $: EngineInterface,
31  command: string,
32  proceed: () => Promise<ToolCallResult>,
33): Promise<ToolCallResult> => {
34  const refusal = getWholeIndexRefusal(command);
35  if (refusal === undefined || !(await read($, enabledModsAtom)).ward) return proceed();
36  const records = await readRecords($, await resolveRecordsPath($));
37  const checkoutRoot = await getCheckoutRoot($, joinDirectory(await $.session.cwd(), refusal.directory));
38  const peerPath = getCheckoutPeer(records, checkoutRoot, await $.session.id(), await $.clock.now());
39  return peerPath === undefined ? proceed() : { deny: getWholeIndexDenyReason(refusal.form, peerPath) };
40};
41
42// Any failure lets the command through, as the disk-scan guard's does: a guard that blocked on its own failure would
43// Block every command after it
44const letCommandThrough = <E, R>(_$: EngineInterface, e: E, next: (e: E) => R): R => next(e);
45
46export const registerWholeIndex = (on: On): void => {
47  // eslint-disable-next-line no-restricted-syntax -- The engine's registration handler, run when the hook rejects, not a promise
48  on("tool.call", { tool: "Bash" }, ($, e, next) => wholeIndex($, e.command, () => next(e))).catch(letCommandThrough);
49};
50
src/services/constants.ts 77 lines
1// The game's own interface gold, the accent wherever the persona publishes no character
2export const ACCENT_COLOR = "#d3bc8e";
3// The prompt cache's lifetime, which the engine chooses and does not report: an hour on a subscription
4export const CACHE_LIFETIME_MS: number = Temporal.Duration.from({ hours: 1 }).total("milliseconds");
5export const CACHE_LOW_MS: number = Temporal.Duration.from({ minutes: 10 }).total("milliseconds");
6export const CACHE_WARNING_MS: number = Temporal.Duration.from({ minutes: 5 }).total("milliseconds");
7export const USAGE_WARNING_PERCENTAGE = 80;
8// The usage lines each window's two tiers start at: the maintenance tier, then the wind-down
9export const FIVE_HOUR_MAINTENANCE_PERCENTAGE = 80;
10export const FIVE_HOUR_WIND_DOWN_PERCENTAGE = 90;
11export const WEEKLY_MAINTENANCE_PERCENTAGE = 80;
12export const WEEKLY_WIND_DOWN_PERCENTAGE = 90;
13// A window under this share is never read for its pace, since an early reading projects wildly
14export const PACE_FLOOR_PERCENTAGE = 50;
15// Each window's length, which its reset time is counted back from
16export const FIVE_HOUR_WINDOW_MS: number = Temporal.Duration.from({ hours: 5 }).total("milliseconds");
17export const WEEKLY_WINDOW_MS: number = Temporal.Duration.from({ hours: 168 }).total("milliseconds");
18// The only model a subagent launches on: the main session thinks, and everything it delegates runs on haiku
19export const AGENT_MODEL = "haiku";
20// What a launch on any other model, or a fork, is told instead
21// oxlint-disable-next-line typescript/no-inferrable-types -- `isolatedDeclarations` demands the annotation this template literal would otherwise infer
22export const AGENT_MODEL_REFUSAL: string = `A subagent runs on "${AGENT_MODEL}" alone: pass model "${AGENT_MODEL}", and never a fork, which runs on the session's own model. Work too judged for ${AGENT_MODEL} stays in the main session, and a spec ${AGENT_MODEL} cannot carry still has a call open.`;
23// What a workflow refused under a reserve is told to do instead, after the reserve's summary
24// oxlint-disable-next-line typescript/no-inferrable-types -- `isolatedDeclarations` demands the annotation this template literal would otherwise infer
25export const RESERVE_REFUSAL_INSTRUCTION: string = `Launch an agent with model "${AGENT_MODEL}" instead, for cleanup or a compute runner whose judgement is settled; otherwise write the unit down as a follow-up and leave it for after the reset.`;
26export const MAX_WAYPOINTS = 3;
27export const MAX_SHOWN_TASKS = 8;
28// Whole minutes as the band writes them, `12m`
29export const MINUTE_FORMATTER: Intl.NumberFormat = new Intl.NumberFormat("en", {
30  style: "unit",
31  unit: "minute",
32  unitDisplay: "narrow",
33});
34export const WARD_WINDOW_MS: number = Temporal.Duration.from({ minutes: 30 }).total("milliseconds");
35export const NO_WAYPOINTS_ANSWER = "NONE";
36// oxlint-disable-next-line typescript/no-inferrable-types -- `isolatedDeclarations` demands the annotation this template literal would otherwise infer
37export const WAYPOINTS_QUESTION: string = `Leave the conversation as it is and answer one side question. List the next steps worth taking from here, at most ${MAX_WAYPOINTS}, most useful first: each one short imperative line the person could send you as their next prompt, with no numbering, no markup and nothing else. When the work is finished or waits on the person, answer ${NO_WAYPOINTS_ANSWER}.`;
38export const WARM_QUESTION = "Answer with the one word OK.";
39export const HANDOFF_QUESTION =
40  "Write a handoff of this session for a fresh conversation that will carry on the work with no other context. Write it as the prompt that conversation starts with: the goal, what is done, what is next in order, the files, commands and decisions that matter with their reasons, and any open question. Be complete but compact, plain markdown, nothing before or after it.";
41export const VEIL_SECTION_ID = "genshin-mods-veil";
42export const VEIL_SYSTEM_SECTION =
43  "Recording mode is on: the screen is being recorded or shared. Never write an email address, a phone number, a money amount, an API key, a token or a password in a reply; write a placeholder such as [email], [phone], [amount] or [secret] instead, even when asked for the value. Tool calls still use the real values.";
44export const RESERVE_SECTION_ID = "genshin-mods-reserve";
45// The wind-down's section ends on this instruction, the same for every window so only the window and its reset time vary
46export const RESERVE_INSTRUCTION =
47  "Until it resets, start no new agent or workflow that writes code or designs; have each running one commit what builds and end on a handoff spec; commit and push the work in hand; write every open item down with what it takes to resume it cold (its paths, what is done, the calls made, the next step); clean up idle servers, shells and monitors; keep only long-running compute going.";
48// The maintenance tier's section ends on this instruction: the window's rest goes on cleanup a haiku agent can do cold
49export const MAINTENANCE_INSTRUCTION =
50  "Until it resets, start no new feature, design or proposal; spend the rest of the window on haiku agents for cleanup: fix the findings of a code review of this window's own recent commits, drain an open sweep ledger, bring the docs and skills in line with the code changed this window, fix CI's typecheck and lint reds, and land the refactors, simplifications and optimisations the compute queue's runs surfaced; write a finding that needs judgement down as a follow-up (the follow-ups plugin's capture skill) rather than deciding it on haiku; keep the compute queue's runners going.";
51// The tools that look something up, the tools that change files, and the shells whose command decides which it is
52export const LOOKUP_TOOLS: readonly string[] = ["Glob", "Grep", "Read", "WebFetch"];
53export const RESET_TOOLS: readonly string[] = ["Agent", "Edit", "NotebookEdit", "Write"];
54export const SHELL_TOOLS: readonly string[] = ["Bash", "PowerShell"];
55// The `export` and `cd` a session chains ahead of its command, each stripped as one leading segment
56// oxlint-disable-next-line typescript/no-inferrable-types -- `isolatedDeclarations` demands the annotation this pattern would otherwise infer
57export const LEADING_SEGMENT_REGEX: RegExp = /^\s*(?:export\s[^&;]*&&|cd\s[^&;]*&&|cd\s[^&;]*;)\s*/u;
58// The commands that only read, a whole first word each so `catalog` is not `cat`. No interpreter is one, since what
59// It runs may write as readily as read; PowerShell's cmdlets are matched in any case, as PowerShell matches them
60// oxlint-disable-next-line typescript/no-inferrable-types -- `isolatedDeclarations` demands the annotation this pattern would otherwise infer
61export const LOOKUP_COMMAND_REGEX: RegExp =
62  /^\s*(?:cat|sed|grep|rg|find|ls|head|tail|awk|wc|get-content|get-childitem|select-string|git\s+(?:show|log|diff)|gh\s+run\s+view)(?:\s|$)/iu;
63// The reads that write as well: sed's in-place edit, find's actions that write, and a redirection into a file, the
64// Stderr and stdout merges and the null device aside
65// oxlint-disable-next-line typescript/no-inferrable-types -- `isolatedDeclarations` demands the annotation this pattern would otherwise infer
66export const WRITING_LOOKUP_REGEX: RegExp =
67  /\bsed\b.*\s(?:-[a-zA-Z]*i|--in-place)|\bfind\b.*\s-(?:delete|exec|execdir|ok|okdir|fprint0?|fprintf|fls)\b|>(?!&|\s*\/dev\/null\b)/iu;
68// Every third lookup in a row, the chain a haiku agent should answer as one bounded question
69export const DELEGATION_NUDGE_EVERY = 3;
70export const DELEGATION_NUDGE =
71  "Third lookup in a row with no decision between them: by the llm-delegation skill's hop rule this chain goes to a haiku agent as one bounded question.";
72// The repository's watcher, which the pulse runs as its child and reads the lines of
73export const MACHINE_WATCHER_SCRIPT = "scripts/src/machine/watch/index.ts";
74// How long after its watcher exits a session starts one again, so a session whose watcher found another's lock held takes
75// Over the watching once that watcher's session ends
76export const MACHINE_WATCHER_RETRY_MILLISECONDS: number = Temporal.Duration.from({ minutes: 1 }).total("milliseconds");
77
src/services/InitialState.ts 17 lines
1import type { PluginState } from "claude-code";
2
3// Every state value's initial, read by each file's atoms: the engine traces a state reference only to an atom made in
4// The file that uses it, so each file makes its own and this is the one place their initials are written
5export const InitialState: PluginState["genshin-mods"] = {
6  commission: { goal: "", openedAt: 0, tasks: [] },
7  enabledMods: { commission: true, pulse: true, resin: true, veil: false, ward: true, waypoints: true },
8  isCommissionExpanded: false,
9  isHandingOff: false,
10  lastCacheRequestAt: 0,
11  lastPrompt: "",
12  lookupStreak: 0,
13  now: 0,
14  reserveWindow: { isAheadOfPace: false, isWindDown: false, name: "", percentage: 0, resetsAt: "" },
15  waypoints: [],
16};
17