@abhishek944/pi-firstmate 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abhishek Tatikella
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,188 @@
1
- # Temporary Holding Version
1
+ # pi-firstmate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A standalone Pi package with an extension and bundled First Mate skill. Turn a primary session into a coordinator: keep conversation, decisions and quick inspection local, and delegate project execution through your installed orchestration backend. While the mode is on, the extension also restricts the coordinator's tools to a fixed inspection set plus installed orchestration, tracking, monitoring and decision tools.
4
+
5
+ ## Install
6
+
7
+ Requires Pi 1.4.0 or a compatible version with structured prompt sections and `pi.getSettings()`, and Node.js 22.19 or newer.
8
+
9
+ For a local checkout:
10
+
11
+ ```sh
12
+ cd /path/to/pi-firstmate
13
+ npm install --ignore-scripts
14
+ npm run build
15
+ pi install /path/to/pi-firstmate
16
+ ```
17
+
18
+ Run Pi from any project directory. Use `/reload` or restart Pi after installation or changes. The explicit package manifest loads `dist/index.js` and `skills/firstmate/SKILL.md`; do not separately copy the skill into a global skills directory or register the source extension again.
19
+
20
+ First Mate does not install an orchestration backend. Install and authorize pi-herdr or another backend separately if you want delegation. No Herdr, pi-tasks or user-global workflow skill dependency is required to load or enable this package.
21
+
22
+ ## Commands
23
+
24
+ | Command | Effect |
25
+ | --- | --- |
26
+ | `/firstmate` or `/firstmate status` | Show effective mode, default, override, worker classification, tool availability, skill advertisement and guidance availability. |
27
+ | `/firstmate on` | Enable coordinator guidance for this session. |
28
+ | `/firstmate off` | Disable it and supersede earlier coordinator guidance. |
29
+ | `/firstmate default` | Clear the session override and follow settings. |
30
+ | `/close` | Record the worker close retrospective in `improvements.md` in the worker's canonical task directory; changes nothing and never closes a terminal. |
31
+
32
+ Overrides survive reload and resume of the same session. Navigating branches does not roll them back. Forks have a new session ID and do not inherit the override. Commands never write your settings.
33
+
34
+ ## Worker close retrospective
35
+
36
+ When a worker's assignment is complete, the coordinator verifies the result and decides whether the worker needs anything further. Only when it does not, the coordinator sends the real `/close` command to that still-live worker with the orchestration backend's send tool (`AgentSend`), waits for the resulting run, reads the `improvements.md` record, and then closes the worker terminal with the backend's close tool (`AgentClose`).
37
+
38
+ - Records stay local in the canonical task artifact directory: `<parentTaskDir>/<sessionId>/<workId>/<taskId>/improvements.md` for a delegated worker, or `var/<sessionId>/<workId>/<taskId>/improvements.md` in a root session. Without a work or task record, the file is `var/<sessionId>/improvements.md`. `var/` is not committed.
39
+ - Nothing is applied. No skills, code, settings, tasks, terminals or monitors are changed, and no commits, deployments or follow-up tasks are created.
40
+ - Repeated runs merge into the existing file instead of duplicating findings, and blocked or interrupted work is recorded honestly instead of as complete.
41
+ - A worker is closed once its result is verified and no concrete follow-up remains. Keeping one longer needs a named dependency, such as a specific pending review or decision; an outstanding verification belongs in the handoff instead of keeping the author available, and retained workers are reassessed after review, decision and integration milestones. A worker that is still active, blocked awaiting input or not owned by this coordinator is never closed.
42
+ - The command itself never closes a terminal and never runs automatically on a final or interim worker report. The coordinator owns both the decision and the close, so the retrospective cannot run before verification or while a named dependency is genuinely pending.
43
+
44
+ `/close` runs the same bundled `close` skill workflow in any session. A model cannot type slash commands, which is why the coordinator sends the command through the backend. A typed `/close` is dispatched by Pi as a command; the backend-wrapped request (`<hc …>/close</hc>`) is recognized by the worker's `input` hook and rewritten into the same workflow run, so it is not sent to the model as plain text to improvise. In a coordinator session the command reports this lifecycle instead of starting a coordinator retrospective, because the coordinator has no project-edit tools.
45
+
46
+ ## Default configuration
47
+
48
+ Merge this section into `~/.pi/agent/settings.json` (or your custom Pi agent directory):
49
+
50
+ ```json
51
+ {
52
+ "pi-firstmate": {
53
+ "enabled": false,
54
+ "banner": true
55
+ }
56
+ }
57
+ ```
58
+
59
+ The default is off when omitted. Set `enabled` to `true` for default-on primary sessions. A trusted project's `.pi/settings.json` may override it through Pi's normal settings merge. See [config.example.json](config.example.json).
60
+
61
+ Only booleans are accepted for `enabled` and `banner`. A malformed section or `enabled` reports a diagnostic and treats the configured default as off; an explicit session override still applies. A malformed `banner` disables only the banner and reports it; a valid `enabled` keeps working. A malformed `coordinatorSkills` disables only that filter and reports it. Other settings keys are untouched.
62
+
63
+ ### Coordinator skill advertisement
64
+
65
+ `coordinatorSkills` is an optional array of exact skill names. While First Mate is effectively on in a primary coordinator session, Pi advertises only the discovered skills with those names (`[]` advertises none); omitting the key keeps every discovered skill advertised. For example:
66
+
67
+ ```json
68
+ {
69
+ "pi-firstmate": {
70
+ "enabled": true,
71
+ "coordinatorSkills": ["implement", "model-routing-policy", "herdr"]
72
+ }
73
+ }
74
+ ```
75
+
76
+ Names are matched exactly against the skills Pi already discovered. User, package, explicit and trusted-project locations keep their normal precedence and collision rules, so the list cannot add, load, reorder or trust a skill; a configured name that is not currently discovered is ignored. `/firstmate status` reports the advertised count and names any configured skill the session did not discover, and the first effective run with a new unknown-name set adds one warning.
77
+
78
+ The filter changes only that run's model-facing `<skills>` advertisement. It does not delete or disable skills, change permissions or tool restrictions, or erase instructions already in the conversation. Off sessions, `--firstmate-worker` processes and verified Core workers advertise every discovered skill. Settings are read when the session starts, when you run `/firstmate`, and after `/reload`; a changed filter applies from the next run.
79
+
80
+ Pi resolves `/skill:name` from its complete discovered list, so an explicit `/skill:name` still loads a skill that is filtered out of the advertisement; filtering only removes automatic model routing to it. `enableSkillCommands` controls whether skill commands appear in interactive command discovery, but manually entered `/skill:name` commands still work. The bundled First Mate policy is injected separately as the `first_mate` prompt section, so filtering never removes coordinator guidance. A malformed value (a non-array, a non-string entry, or an empty name) disables only this filter with a diagnostic instead of hiding every skill.
81
+
82
+ ## Herdr banner
83
+
84
+ In a primary Herdr Core session, `banner` (default `true`) adds a warm amber strip above that session's tab panes while First Mate is effectively on. The strip is a native layout block, not a pane header: pane content, headers and buttons, terminals, themes, other tabs and worker sessions are unchanged. It also carries a reminder to read the installed First Mate skill. `/firstmate off` collapses it to zero height; switching to a tab or space without a First Mate session also hides it.
85
+
86
+ On session start in a verified primary Core session, the extension:
87
+
88
+ - installs or updates `~/.config/herdr-app/mods/firstmate-banner/` from this package. Only changed files are replaced, and the previous copy is kept under `~/.config/herdr-app/data/firstmate-banner/backups/`;
89
+ - adds one `firstmate-banner` block to the shown personal layout, immediately above the block that contains the active tab. The layout file is backed up there first. Herdr's shipped `main`, `terminals` and `win98` layouts are never edited; clone one (`layout.clone`) and switch to it if you want the banner there;
90
+ - writes `~/.config/herdr-app/data/firstmate-banner/<session-id>.json` with the effective mode and Core terminal address, and removes it on shutdown. Worker, non-Core and inconclusive-Core sessions never advertise coordinator mode.
91
+
92
+ The state stays local: no network call, daemon, polling loop or new IPC service. Herdr hot-reloads mods, but run `/reload` in Pi after installing or updating this package so the extension installs the strip; `/firstmate status` then reports a `Banner:` line. Pi must be running in a Herdr Core terminal and report agent status, which it normally does. If the banner is unavailable, the status line names the reason (for example a shipped layout or a missing Herdr app home). Set `banner` to `false` to stop the integration.
93
+
94
+ ## Delegation and worker isolation
95
+
96
+ While on, substantial investigation, project edits, builds, migrations, reviews and permitted checks go to workers. A quick check that grows should become delegated work. Saying "implement this" keeps coordinator mode on; use `/firstmate off` to leave it.
97
+
98
+ The bundled skill makes reading the installed First Mate skill mandatory whenever the mode is on. The extension reinforces that at activation with a notification, an always-present prompt guideline and a compact `First Mate · read skill` status line while coordinator mode is effective.
99
+
100
+ Use the available backend's actual instructions, tools, permissions, monitoring and result lifecycle. With pi-herdr, follow its bundled `herdr` skill and Agent tools. With another installed backend, follow that backend's own instructions. Host/project tracking, artifact and model-routing rules still apply when installed or required; this package adds no mandatory global workflow skills.
101
+
102
+ If delegation is unavailable or fails, the coordinator should report the concrete blocker and safe options instead of silently executing substantial work itself. First Mate adds no orchestrator, adapter registry, task store, model selection or automatic model fallback; its tool-call gate is limited to the coordinator allowlist below.
103
+
104
+ ### Coordinator tool allowlist
105
+
106
+ While coordinator mode is effective, the model can use only `read`, `grep`, `find`, `ls` and tools registered by an installed pi-tasks, pi-loop-monitor, pi-decisions, pi-herdr or pi-schedulers package. The extension derives that set from the packages' actual registrations, so their task, decision, monitor, loop and Agent tools keep their normal schemas and behavior; `MonitorCreate` is not argument-filtered. Other active tools are hidden from the model and re-filtered before each request, including direct tools registered during a multi-turn run such as a slow MCP connection. Direct or nested calls to them are rejected at Pi's `tool_call` boundary with an actionable delegation message, including nested calls made through codemode or another tool.
107
+
108
+ Off mode, an explicit `--firstmate-worker` process and verified Core workers keep ordinary tools. `/firstmate off` and `/firstmate default` restore the active-tool set that existed before the restriction, without enabling unrelated inactive tools. The baseline is stored in existing session state under this session's identity, so turning the mode off after resuming a saved session restores the original set even when the restricted declarations were the last ones recorded. A fork does not inherit another session's baseline.
109
+
110
+ When pi-research (`/ask`) owns its read-only guard, First Mate keeps that restriction intact. It answers the existing `pi-ask:guard:probe` event while deciding whether to restore its saved tools, and it re-runs the full gate synchronously on the existing `pi-ask:guard:released` event. A coordinator therefore records the restored tool list as its baseline before narrowing again, and an off-mode restore waits until the read-only mode ends instead of widening it. This cooperation uses only the pi-ask guard events; extensions that do not participate in that protocol cannot be inferred.
111
+
112
+ This is Pi tool-call enforcement, not an OS sandbox. Allowed tools can still start or control processes, and permissions, trust, user authorization and `/ask` or `/btw` limits still apply. Do not describe it as absolute prevention through every allowed command or monitor.
113
+
114
+ Shell, codemode and project-edit tools are intentionally unavailable to a coordinator; this is not a missing permission or a broken installation. A blocked call reports the restriction and points to checking the installed delegation backend, not to enabling the tool.
115
+
116
+ ### Optional scheduler creation
117
+
118
+ An installed pi-schedulers package owns `SchedulerCreate`, including its schema,
119
+ preview, mandatory human Create/Cancel dialog and transactional definition save.
120
+ First Mate only controls its exposure from the actual package-owned registration;
121
+ it does not implement scheduling or guess a foreign tool name. Use it only when
122
+ the human explicitly asks for scheduled work, never proactively or from inferred
123
+ permission. Each creation, including duplicates, needs its own human confirmation.
124
+
125
+ The scheduler registers hidden by default. While `resolveMode().effective` is
126
+ true, First Mate allows the scheduler-owned registration to become model-only
127
+ and activates it, without widening `/ask`'s read-only guard. The synchronous
128
+ `pi-firstmate:mode:probe` event answers `available`, `protocolVersion: 1`,
129
+ `effective`, and a `generation` that changes on effective-mode transitions.
130
+ `pi-firstmate:mode:changed` asks consumers to re-probe; the owning scheduler
131
+ publishes `pi-schedulers:tools:changed` after changing its registration so late
132
+ registration is handled in either extension load order. The existing explicit
133
+ `/firstmate on` behavior after an inconclusive Core lookup is unchanged; actual
134
+ worker suppression remains authoritative.
135
+
136
+ Off, shutdown, reload and resume restoration never add coordinator-only scheduler
137
+ tools to the ordinary baseline, and unrelated active/inactive choices remain
138
+ unchanged. Without First Mate the registration stays hidden. The scheduler
139
+ rechecks the authoritative effective generation at execute entry, after the human
140
+ answers, and before initiating its definition write/commit. Off/on while a dialog
141
+ is open invalidates it; no model approval flag bypasses the human dialog. Once a
142
+ filesystem commit has been initiated it cannot be revoked atomically by a later
143
+ mode change. No rollback/recovery infrastructure is added. Scheduled workers keep
144
+ normal configured tools/MCP and First Mate suppression; this integration does not
145
+ turn creation back on in those workers. Reload Pi after updating both packages
146
+ when it is safe to do so; installation of native mods is separate.
147
+
148
+ ### Other worker launchers
149
+
150
+ Pass this package's one boolean flag to child Pi processes that load it:
151
+
152
+ ```sh
153
+ pi --firstmate-worker
154
+ ```
155
+
156
+ The flag defaults to false. When present, it always suppresses coordinator guidance, even with default-on settings or a saved `/firstmate on` override. It also skips optional Core detection, so it works without `hc`. This is a per-process CLI marker, not an inherited global mode environment variable. Ensure your launcher's actual child command passes it; First Mate does not modify launchers. When adding an initial prompt, separate it with `--`, for example `pi --firstmate-worker -- "worker assignment"`. Pi 1.4.0 can otherwise consume a following positional prompt as an extension flag value.
157
+
158
+ ### Optional pi-herdr/Core detection
159
+
160
+ Without the explicit flag, a process with `HC_TERMINAL_ID` can use `hc get <terminalId> --json` to check the labels written by pi-herdr. Both `pi.task` and `pi.session` identify a worker. `HC_TERMINAL_ID` alone does not: primary Core sessions have it too. Non-Core sessions need neither `hc` nor Herdr installed.
161
+
162
+ A failed or partial Core lookup suppresses default-on and reports a diagnostic. An explicit `/firstmate on` may enable that unclassified session if you know it is a coordinator; verified workers remain suppressed.
163
+
164
+ Unknown third-party launcher workers cannot be reliably recognized automatically. Use `--firstmate-worker`, especially when workers share default-on configuration. This package does not claim universal launcher compatibility.
165
+
166
+ ## Boundaries
167
+
168
+ First Mate is coordinator guidance plus the tool-call allowlist and the optional skill-advertisement filter above. It is not a security sandbox or a guarantee that a model complies, and it does not grant permissions. Project trust, user authorization, specialized workflows and `/ask` or `/btw` restrictions remain intact. Workers follow their assignment and ordinary instructions, not coordinator delegation guidance. Filtered skills remain installed and available to explicit `/skill:name` commands; the filter is not a permission, trust or sandbox boundary.
169
+
170
+ The extension injects its bundled skill as a structured `first_mate` section before each user or custom-message run, including monitor wakes. Turning it off removes that section and, when earlier guidance was observed, adds a superseding guideline. An unreadable policy reports a diagnostic instead of pretending guidance was installed.
171
+
172
+ ## Development
173
+
174
+ ```sh
175
+ npm install --ignore-scripts
176
+ npm run lint
177
+ npm run typecheck
178
+ npm run build
179
+ npm pack --dry-run
180
+ ```
181
+
182
+ The host Pi package is a peer dependency and a pinned development dependency for current API declarations; it is not bundled as a runtime dependency. `src/index.ts` and generated `dist/index.js` both resolve the same bundled policy relative to their module, independently of the working directory. No unit-test runner is included.
183
+
184
+ For user-owned live verification, enable the mode in a primary session, confirm `/firstmate status` reports the restricted `Tools:` line and an ordinary tool is unavailable, request a small project change, inspect actual worker results, then disable it and confirm ordinary execution returns. Check your launcher's child processes with `--firstmate-worker` before enabling a shared default.
185
+
186
+ ## License
187
+
188
+ [MIT](LICENSE).
@@ -0,0 +1,6 @@
1
+ {
2
+ "pi-firstmate": {
3
+ "enabled": false,
4
+ "banner": true
5
+ }
6
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Validation for the `pi-firstmate` section of Pi's effective settings.
3
+ *
4
+ * Pi owns settings loading, project trust and global/project merging, so the
5
+ * extension reads the merged object from `pi.getSettings()` and validates only
6
+ * the section it owns. Unknown sibling keys are ignored for forward compatibility.
7
+ */
8
+ export declare const FIRST_MATE_SETTINGS_KEY = "pi-firstmate";
9
+ export type ConfiguredDefault = {
10
+ kind: "valid";
11
+ enabled: boolean;
12
+ banner: boolean;
13
+ bannerProblem?: string;
14
+ /** Exact skill names to advertise while coordinator mode is effective; `undefined` advertises every discovered skill. */
15
+ coordinatorSkills?: string[];
16
+ coordinatorSkillsProblem?: string;
17
+ } | {
18
+ kind: "invalid";
19
+ message: string;
20
+ };
21
+ /**
22
+ * Resolve the configured default.
23
+ *
24
+ * A missing section, a missing `enabled`, or an empty section means `false`.
25
+ * A malformed section or `enabled` is reported instead of silently enabling
26
+ * coordinator mode. A malformed optional `banner` disables only the banner and
27
+ * keeps the valid `enabled` value; the problem is carried as a diagnostic.
28
+ * A malformed optional `coordinatorSkills` disables only that filter, so an
29
+ * invalid value advertises every discovered skill instead of hiding all of
30
+ * them.
31
+ */
32
+ export declare function readConfiguredDefault(settings: unknown): ConfiguredDefault;
package/dist/config.js ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Validation for the `pi-firstmate` section of Pi's effective settings.
3
+ *
4
+ * Pi owns settings loading, project trust and global/project merging, so the
5
+ * extension reads the merged object from `pi.getSettings()` and validates only
6
+ * the section it owns. Unknown sibling keys are ignored for forward compatibility.
7
+ */
8
+ export const FIRST_MATE_SETTINGS_KEY = "pi-firstmate";
9
+ const DEFAULT_OFF = { kind: "valid", enabled: false, banner: true };
10
+ function describeValue(value) {
11
+ if (value === null)
12
+ return "null";
13
+ if (Array.isArray(value))
14
+ return "an array";
15
+ if (typeof value === "string")
16
+ return "a string";
17
+ if (typeof value === "number")
18
+ return "a number";
19
+ if (typeof value === "boolean")
20
+ return "a boolean";
21
+ return typeof value;
22
+ }
23
+ /**
24
+ * Resolve the configured default.
25
+ *
26
+ * A missing section, a missing `enabled`, or an empty section means `false`.
27
+ * A malformed section or `enabled` is reported instead of silently enabling
28
+ * coordinator mode. A malformed optional `banner` disables only the banner and
29
+ * keeps the valid `enabled` value; the problem is carried as a diagnostic.
30
+ * A malformed optional `coordinatorSkills` disables only that filter, so an
31
+ * invalid value advertises every discovered skill instead of hiding all of
32
+ * them.
33
+ */
34
+ export function readConfiguredDefault(settings) {
35
+ if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
36
+ return { kind: "invalid", message: "Pi returned settings that are not an object" };
37
+ }
38
+ const section = settings[FIRST_MATE_SETTINGS_KEY];
39
+ if (section === undefined)
40
+ return DEFAULT_OFF;
41
+ if (typeof section !== "object" || section === null || Array.isArray(section)) {
42
+ return {
43
+ kind: "invalid",
44
+ message: `expected "${FIRST_MATE_SETTINGS_KEY}" to be an object such as {"enabled": false}, found ${describeValue(section)}`,
45
+ };
46
+ }
47
+ const enabled = section.enabled;
48
+ if (enabled !== undefined && typeof enabled !== "boolean") {
49
+ return {
50
+ kind: "invalid",
51
+ message: `expected "${FIRST_MATE_SETTINGS_KEY}.enabled" to be true or false, found ${describeValue(enabled)}`,
52
+ };
53
+ }
54
+ const banner = section.banner;
55
+ const bannerProblem = banner !== undefined && typeof banner !== "boolean"
56
+ ? `expected "${FIRST_MATE_SETTINGS_KEY}.banner" to be true or false, found ${describeValue(banner)}`
57
+ : undefined;
58
+ const skills = readCoordinatorSkills(section.coordinatorSkills);
59
+ return {
60
+ kind: "valid",
61
+ enabled: enabled ?? false,
62
+ banner: banner === undefined ? true : typeof banner === "boolean" ? banner : false,
63
+ ...(bannerProblem === undefined ? {} : { bannerProblem }),
64
+ ...(skills.names === undefined ? {} : { coordinatorSkills: skills.names }),
65
+ ...(skills.problem === undefined ? {} : { coordinatorSkillsProblem: skills.problem }),
66
+ };
67
+ }
68
+ /**
69
+ * Read the optional exact-name allowlist. An invalid value disables only this
70
+ * filter: coordinator mode keeps advertising every discovered skill rather than
71
+ * silently hiding all of them. Duplicate names are collapsed in order.
72
+ */
73
+ function readCoordinatorSkills(value) {
74
+ if (value === undefined)
75
+ return {};
76
+ if (!Array.isArray(value)) {
77
+ return {
78
+ problem: `expected "${FIRST_MATE_SETTINGS_KEY}.coordinatorSkills" to be an array of exact skill names, found ${describeValue(value)}`,
79
+ };
80
+ }
81
+ const names = [];
82
+ for (const item of value) {
83
+ if (typeof item !== "string") {
84
+ return {
85
+ problem: `expected every "${FIRST_MATE_SETTINGS_KEY}.coordinatorSkills" entry to be a skill name string, found ${describeValue(item)}`,
86
+ };
87
+ }
88
+ if (item.trim() === "") {
89
+ return {
90
+ problem: `expected every "${FIRST_MATE_SETTINGS_KEY}.coordinatorSkills" entry to be a nonempty skill name, found an empty name`,
91
+ };
92
+ }
93
+ if (!names.includes(item))
94
+ names.push(item);
95
+ }
96
+ return { names };
97
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Optional native Herdr banner for First Mate.
3
+ *
4
+ * A personal Herdr layout gets one extra block above the block that contains
5
+ * the shown tab. That block loads `mods/firstmate-banner`, which reads the
6
+ * small per-session state files written here and shows the strip only for the
7
+ * active tab's live First Mate session.
8
+ *
9
+ * Everything in this module is best-effort. First Mate's mode, guidance and
10
+ * status keep working when Herdr is absent, the shown layout is shipped, or a
11
+ * file cannot be written.
12
+ */
13
+ export declare const BANNER_MOD = "firstmate-banner";
14
+ export declare const BANNER_NODE_ID = "firstmate-banner";
15
+ export interface BannerSetup {
16
+ /** installed: this call wrote something. present: everything already matched. */
17
+ state: "installed" | "present" | "unavailable";
18
+ detail: string;
19
+ }
20
+ export interface BannerState {
21
+ sessionId: string;
22
+ terminal: string;
23
+ effective: boolean;
24
+ }
25
+ /**
26
+ * The Herdr app home, matching the app's own lookup: `HERDR_APP_HOME`, else
27
+ * `XDG_CONFIG_HOME/herdr-app`, else `~/.config/herdr-app`.
28
+ */
29
+ export declare function herdrAppHome(env?: NodeJS.ProcessEnv): string;
30
+ /**
31
+ * Make the installed mod and the shown personal layout ready for the banner.
32
+ * Callers treat `unavailable` as a diagnostic, never as a First Mate failure.
33
+ */
34
+ export declare function ensureHerdrBanner(appHome: string, assets: URL): BannerSetup;
35
+ /**
36
+ * Publish this session's effective mode for the banner mod. The file is
37
+ * replaced atomically; a file left by an earlier Pi session in the same
38
+ * terminal is removed so it cannot override this one.
39
+ */
40
+ export declare function writeBannerState(appHome: string, state: BannerState): void;
41
+ /** Best-effort shutdown cleanup; the banner disappears as soon as this file is gone. */
42
+ export declare function clearBannerState(appHome: string, sessionId: string, terminal?: string): void;
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Optional native Herdr banner for First Mate.
3
+ *
4
+ * A personal Herdr layout gets one extra block above the block that contains
5
+ * the shown tab. That block loads `mods/firstmate-banner`, which reads the
6
+ * small per-session state files written here and shows the strip only for the
7
+ * active tab's live First Mate session.
8
+ *
9
+ * Everything in this module is best-effort. First Mate's mode, guidance and
10
+ * status keep working when Herdr is absent, the shown layout is shipped, or a
11
+ * file cannot be written.
12
+ */
13
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { isAbsolute, join, resolve } from "node:path";
16
+ export const BANNER_MOD = "firstmate-banner";
17
+ export const BANNER_NODE_ID = "firstmate-banner";
18
+ const SHIPPED_LAYOUTS = new Set(["main", "terminals", "win98"]);
19
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
20
+ const TERMINAL_ID = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?t[0-9a-z]+$/;
21
+ const LAYOUT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
22
+ const ASSET_NAMES = ["main.js", "mod.json", "README.md"];
23
+ function isRecord(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ function errorText(error) {
27
+ const line = (error instanceof Error ? error.message : String(error)).split("\n", 1)[0]?.trim();
28
+ return line === undefined || line === "" ? "unknown error" : line;
29
+ }
30
+ /**
31
+ * The Herdr app home, matching the app's own lookup: `HERDR_APP_HOME`, else
32
+ * `XDG_CONFIG_HOME/herdr-app`, else `~/.config/herdr-app`.
33
+ */
34
+ export function herdrAppHome(env = process.env) {
35
+ const custom = env.HERDR_APP_HOME?.trim();
36
+ if (custom !== undefined && custom !== "")
37
+ return resolve(custom);
38
+ const config = env.XDG_CONFIG_HOME?.trim();
39
+ const base = config !== undefined && config !== "" && isAbsolute(config) ? config : join(homedir(), ".config");
40
+ return join(base, "herdr-app");
41
+ }
42
+ function bannerDataDir(appHome) {
43
+ return join(appHome, "data", BANNER_MOD);
44
+ }
45
+ function writeAtomic(path, data) {
46
+ const temporary = `${path}.firstmate-${process.pid}-${Date.now()}.tmp`;
47
+ writeFileSync(temporary, data);
48
+ try {
49
+ renameSync(temporary, path);
50
+ }
51
+ catch (error) {
52
+ rmSync(temporary, { force: true });
53
+ throw error;
54
+ }
55
+ }
56
+ /** Keep the previous installed copy next to the recovery notes, not in the live mod folder. */
57
+ function backup(path, name, backupDir) {
58
+ mkdirSync(backupDir, { recursive: true });
59
+ copyFileSync(path, join(backupDir, `${Date.now()}-${name}`));
60
+ }
61
+ /** Install or update only the files this package owns; never duplicate identical content. */
62
+ function installAssets(appHome, assets, backupDir) {
63
+ const directory = join(appHome, "mods", BANNER_MOD);
64
+ mkdirSync(directory, { recursive: true });
65
+ for (const [name, data] of assets) {
66
+ const target = join(directory, name);
67
+ if (existsSync(target) && readFileSync(target).equals(data))
68
+ continue;
69
+ if (existsSync(target))
70
+ backup(target, name, backupDir);
71
+ writeAtomic(target, data);
72
+ }
73
+ }
74
+ /** The layout the running window shows, from the app's shared state. */
75
+ function shownLayout(appHome) {
76
+ try {
77
+ const parsed = JSON.parse(readFileSync(join(appHome, "shared.json"), "utf8"));
78
+ if (!isRecord(parsed) || typeof parsed.layout !== "string" || !LAYOUT_NAME.test(parsed.layout))
79
+ return undefined;
80
+ return parsed.layout;
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
86
+ function findNode(node, id) {
87
+ if (!isRecord(node))
88
+ return undefined;
89
+ if (node.id === id)
90
+ return node;
91
+ for (const child of Array.isArray(node.children) ? node.children : []) {
92
+ const found = findNode(child, id);
93
+ if (found !== undefined)
94
+ return found;
95
+ }
96
+ return undefined;
97
+ }
98
+ /** The root-to-block path of the layout node that shows the active tab. */
99
+ function pathToActiveTab(node, trail = []) {
100
+ if (!isRecord(node))
101
+ return undefined;
102
+ const path = [...trail, node];
103
+ if (isRecord(node.content) && node.content.tab === "active")
104
+ return path;
105
+ for (const child of Array.isArray(node.children) ? node.children : []) {
106
+ const found = pathToActiveTab(child, path);
107
+ if (found !== undefined)
108
+ return found;
109
+ }
110
+ return undefined;
111
+ }
112
+ /**
113
+ * Insert directly before the child of the nearest `column` ancestor that
114
+ * contains the active tab. In the shipped main layout that is `work.children`
115
+ * before `work-body`; the tab block, pane frame and side panels are untouched.
116
+ */
117
+ function insertionSpot(root) {
118
+ const path = pathToActiveTab(root);
119
+ if (path === undefined || path.length < 2)
120
+ return undefined;
121
+ for (let index = path.length - 1; index >= 1; index -= 1) {
122
+ const parent = path[index - 1];
123
+ const child = path[index];
124
+ if (parent === undefined || child === undefined || parent.type !== "column" || !Array.isArray(parent.children))
125
+ continue;
126
+ const at = parent.children.indexOf(child);
127
+ if (at >= 0)
128
+ return { children: parent.children, index: at };
129
+ }
130
+ return undefined;
131
+ }
132
+ function installLayoutNode(appHome, layoutName, backupDir) {
133
+ const path = join(appHome, "layouts", `${layoutName}.json`);
134
+ const original = readFileSync(path, "utf8");
135
+ const tree = JSON.parse(original);
136
+ if (!isRecord(tree))
137
+ throw new Error(`layout "${layoutName}" is not a layout object`);
138
+ if (findNode(tree, BANNER_NODE_ID) !== undefined)
139
+ return "present";
140
+ const spot = insertionSpot(tree);
141
+ if (spot === undefined) {
142
+ throw new Error(`layout "${layoutName}" has no column above its active-tab block, so there is nowhere to place the banner`);
143
+ }
144
+ spot.children.splice(spot.index, 0, {
145
+ id: BANNER_NODE_ID,
146
+ type: "block",
147
+ size: { px: 0 },
148
+ content: { mod: BANNER_MOD },
149
+ });
150
+ backup(path, `${layoutName}.json`, backupDir);
151
+ writeAtomic(path, `${JSON.stringify(tree, null, 2)}\n`);
152
+ return "installed";
153
+ }
154
+ /**
155
+ * Make the installed mod and the shown personal layout ready for the banner.
156
+ * Callers treat `unavailable` as a diagnostic, never as a First Mate failure.
157
+ */
158
+ export function ensureHerdrBanner(appHome, assets) {
159
+ try {
160
+ if (!existsSync(appHome) || !statSync(appHome).isDirectory()) {
161
+ return { state: "unavailable", detail: `the Herdr app home ${appHome} does not exist` };
162
+ }
163
+ const contents = new Map();
164
+ for (const name of ASSET_NAMES) {
165
+ try {
166
+ contents.set(name, readFileSync(new URL(name, assets)));
167
+ }
168
+ catch {
169
+ return { state: "unavailable", detail: `the packaged banner asset ${name} is missing` };
170
+ }
171
+ }
172
+ const backupDir = join(bannerDataDir(appHome), "backups");
173
+ const modDir = join(appHome, "mods", BANNER_MOD);
174
+ const hadMod = existsSync(join(modDir, "main.js"));
175
+ installAssets(appHome, contents, backupDir);
176
+ const layoutName = shownLayout(appHome);
177
+ if (layoutName === undefined) {
178
+ return { state: "unavailable", detail: "the Herdr window has no shown layout yet" };
179
+ }
180
+ if (SHIPPED_LAYOUTS.has(layoutName)) {
181
+ return {
182
+ state: "unavailable",
183
+ detail: `the shown layout "${layoutName}" is shipped by Herdr; switch to a personal layout to show the banner`,
184
+ };
185
+ }
186
+ if (!existsSync(join(appHome, "layouts", `${layoutName}.json`))) {
187
+ return { state: "unavailable", detail: `the shown layout file ${layoutName}.json is missing` };
188
+ }
189
+ const layout = installLayoutNode(appHome, layoutName, backupDir);
190
+ if (layout === "present" && hadMod)
191
+ return { state: "present", detail: `present in Herdr layout "${layoutName}"` };
192
+ return { state: "installed", detail: `installed in Herdr layout "${layoutName}"` };
193
+ }
194
+ catch (error) {
195
+ return { state: "unavailable", detail: errorText(error) };
196
+ }
197
+ }
198
+ /**
199
+ * Publish this session's effective mode for the banner mod. The file is
200
+ * replaced atomically; a file left by an earlier Pi session in the same
201
+ * terminal is removed so it cannot override this one.
202
+ */
203
+ export function writeBannerState(appHome, state) {
204
+ if (!SESSION_ID.test(state.sessionId))
205
+ throw new Error("invalid Pi session ID");
206
+ if (!TERMINAL_ID.test(state.terminal))
207
+ throw new Error("invalid Core terminal address");
208
+ const directory = bannerDataDir(appHome);
209
+ mkdirSync(directory, { recursive: true });
210
+ for (const name of readdirSync(directory)) {
211
+ if (!name.endsWith(".json"))
212
+ continue;
213
+ const path = join(directory, name);
214
+ try {
215
+ const value = JSON.parse(readFileSync(path, "utf8"));
216
+ if (isRecord(value) && value.terminal === state.terminal && value.sessionId !== state.sessionId)
217
+ rmSync(path, { force: true });
218
+ }
219
+ catch {
220
+ // A damaged foreign file is ignored; it can never match the banner.
221
+ }
222
+ }
223
+ writeAtomic(join(directory, `${state.sessionId}.json`), `${JSON.stringify({
224
+ version: 1,
225
+ sessionId: state.sessionId,
226
+ terminal: state.terminal,
227
+ effective: state.effective,
228
+ updatedAt: Date.now(),
229
+ })}\n`);
230
+ }
231
+ /** Best-effort shutdown cleanup; the banner disappears as soon as this file is gone. */
232
+ export function clearBannerState(appHome, sessionId, terminal) {
233
+ if (!SESSION_ID.test(sessionId))
234
+ return;
235
+ const directory = bannerDataDir(appHome);
236
+ try {
237
+ rmSync(join(directory, `${sessionId}.json`), { force: true });
238
+ }
239
+ catch {
240
+ // Nothing useful to do on shutdown.
241
+ }
242
+ if (terminal === undefined || !TERMINAL_ID.test(terminal))
243
+ return;
244
+ // A primary session that crashed leaves a state file behind. If this
245
+ // terminal now runs a session that must not advertise (for example a
246
+ // worker), remove that leftover too so it cannot win by being older.
247
+ try {
248
+ for (const name of readdirSync(directory)) {
249
+ if (!name.endsWith(".json"))
250
+ continue;
251
+ const path = join(directory, name);
252
+ try {
253
+ const value = JSON.parse(readFileSync(path, "utf8"));
254
+ if (isRecord(value) && value.terminal === terminal && value.sessionId !== sessionId)
255
+ rmSync(path, { force: true });
256
+ }
257
+ catch {
258
+ // Ignore a damaged foreign file.
259
+ }
260
+ }
261
+ }
262
+ catch {
263
+ // The directory may not exist yet.
264
+ }
265
+ }