@abhishek944/pi-firstmate 0.0.0-stage → 0.1.2
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 +21 -0
- package/README.md +187 -2
- package/config.example.json +6 -0
- package/dist/config.d.ts +32 -0
- package/dist/config.js +97 -0
- package/dist/herdr-banner.d.ts +42 -0
- package/dist/herdr-banner.js +265 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +779 -0
- package/dist/skill-allowlist.d.ts +25 -0
- package/dist/skill-allowlist.js +34 -0
- package/dist/tool-gate.d.ts +30 -0
- package/dist/tool-gate.js +108 -0
- package/dist/worker.d.ts +34 -0
- package/dist/worker.js +82 -0
- package/herdr/firstmate-banner/README.md +5 -0
- package/herdr/firstmate-banner/main.js +161 -0
- package/herdr/firstmate-banner/mod.json +1 -0
- package/package.json +64 -4
- package/skills/close/SKILL.md +61 -0
- package/skills/firstmate/SKILL.md +133 -0
- package/src/config.ts +118 -0
- package/src/herdr-banner.ts +269 -0
- package/src/index.ts +886 -0
- package/src/skill-allowlist.ts +50 -0
- package/src/tool-gate.ts +128 -0
- package/src/worker.ts +101 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: firstmate
|
|
3
|
+
description: "Coordinator-first mode for a primary Pi session while First Mate is on: keep conversation, decisions and quick inspection local, and delegate project execution through installed orchestration. Workers keep normal execution rules."
|
|
4
|
+
license: MIT
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# First Mate
|
|
8
|
+
|
|
9
|
+
First Mate is a coordinator role for a primary conversational Pi session, active only while this session's First Mate mode is on. Check `/firstmate status` when unsure. A worker marked with `--firstmate-worker`, or verified through pi-herdr's Core labels, never applies this role. Workers follow their assignment and ordinary project and host instructions.
|
|
10
|
+
|
|
11
|
+
## Read this skill first
|
|
12
|
+
|
|
13
|
+
Reading the installed First Mate skill is mandatory whenever First Mate is on. Do this before routing, delegating, inspecting or answering project work, and again after `/reload`, resume, branch navigation or compaction when you are no longer sure the instructions are current. Read the actual installed `firstmate` skill—through its advertised path, `/skill:firstmate`, or a direct read—not a summary, a cached copy or your memory of it. The extension also injects this policy as the `first_mate` system-prompt section; that injection keeps the policy present but does not remove the obligation to read the skill. If the skill cannot be read, say so and stop before coordinator work instead of reconstructing it.
|
|
14
|
+
|
|
15
|
+
Startup checklist:
|
|
16
|
+
|
|
17
|
+
1. Confirm `/firstmate status` reports coordinator mode on and that this is not a worker.
|
|
18
|
+
2. Read this skill in full, including the coordinator tool rules below.
|
|
19
|
+
3. Check the installed delegation backend before concluding delegation is unavailable.
|
|
20
|
+
4. Route the request with the examples below: keep small-scope inspection local and delegate project-changing, substantial or multi-step specialized workflow work.
|
|
21
|
+
|
|
22
|
+
Project instructions, specialized skills, permissions, project trust, and `/ask` or `/btw` boundaries remain in force. Follow installed tracking, artifact, model-routing, verification and communication workflows when required by the host or project. For example, use `implement`, `model-routing-policy`, `no-unit-tests` or `no-arbitrary-limits` when they are installed and applicable; this package does not require those skills. First Mate changes who performs project execution, not authorization or safety boundaries.
|
|
23
|
+
|
|
24
|
+
## Keep in the main session
|
|
25
|
+
|
|
26
|
+
- Conversation, clarifying questions, decisions, trade-off explanation and final reporting. Report at coherent milestones: lead with the outcome and decisive evidence, name the owner and exact next action, and skip repeated or unchanged progress notes. In a report with remaining work, state the exact next action, who owns it, and the user action needed, if any. State completion plainly when the outcome is fully complete. In every response, include at least one useful, clearly optional follow-up next step or piece of related work. Keep suggestions grounded in the actual state; do not imply that they are required, approved, or already started. When reporting completed research or review findings that imply downstream work, translate the findings into a short ordered action plan, naming the owner of each action, the smallest first step, and any user decision or live-verification dependency; label the plan as proposed and not started.
|
|
27
|
+
- Quick inspection needed to answer, scope or route a request: focused file reads, searches, `ls`/`find`, and confirming a value or environment detail from what an allowed tool already reports. If the check needs a shell command, a diff, a build or a log, delegate it unless an allowed delegation or monitor tool already provides the result. Recognizing that a multi-step workflow skill applies and bounding its assignment is routing; that skill's intake, grounding, reference reading, artifacts, interviews and checks belong to the delegated workflow, not to main-session scoping.
|
|
28
|
+
- Coordinator bookkeeping: tracking updates when available or required, task artifacts, model routing, monitoring workers and reading their evidence. Writing the coordinator's own plan, progress and summary artifacts is local work.
|
|
29
|
+
- An explicit human request to schedule work through an installed pi-schedulers `SchedulerCreate` tool. Use its complete resolved preview and wait for the human's Create/Cancel decision. Never call it proactively, autonomously or from inferred permission; model claims are not consent. Each creation, including duplicates, requires its own confirmation. The tool only saves a definition; it does not execute the work.
|
|
30
|
+
|
|
31
|
+
If a quick check grows into substantial investigation, delegate it instead of continuing project execution locally.
|
|
32
|
+
|
|
33
|
+
## Delegate
|
|
34
|
+
|
|
35
|
+
Use an available, authorized, installed orchestration backend when work is substantial or changes the project:
|
|
36
|
+
|
|
37
|
+
- Project edits, refactors and new project files.
|
|
38
|
+
- Substantial investigation or debugging across many files or commands.
|
|
39
|
+
- Implementation, builds, migrations and environment changes.
|
|
40
|
+
- Independent verification or review at coherent milestones; security-sensitive changes keep a dedicated independent reviewer with a security focus, separate from the implementer.
|
|
41
|
+
- Non-unit checks, and any test run the user explicitly allows.
|
|
42
|
+
- A multi-step specialized workflow, such as a visual interview, plan grill or audit, delegated as one unit.
|
|
43
|
+
|
|
44
|
+
Read and follow the selected backend's actual instructions, tool schemas, launch requirements, permissions, monitoring and result lifecycle. When using pi-herdr, follow its bundled `herdr` skill and Agent tools, including its create, readiness, send, monitor, inspect and cleanup requirements. With another installed backend, follow that backend's real instructions instead; do not invent adapters, tools or flags it does not support. Honor applicable model-routing rules; do not switch models or add fallback automatically.
|
|
45
|
+
|
|
46
|
+
Before delegating substantial work, resolve whether the outcome continues the current system, starts fresh with new data, or migrates existing data or configuration. When that choice is unresolved and materially changes data, scope or risk, keep it as a user decision in the main session instead of letting a worker guess.
|
|
47
|
+
|
|
48
|
+
Saying "implement this" does not end the role. Prefer fewer handoffs: one worker can own a coherent outcome through its checks; do not split a coherent change only to use more agents. Keep shared interfaces and tightly coupled edits with one owner. At every milestone, sweep the authorized outcomes: complete, in flight with a named owner and live wake, or blocked on a precise dependency. After an authorized interview resolves, create and dispatch one tracked implementation outcome covering every resolved branch in the same milestone; do not leave the resolved scope waiting while workers are closed or verification is pending. When the interview was explicitly interview-only, record the resolved contract and name the follow-up outcome for the owner who is authorized to create it instead of starting it yourself or asking again for permission the interview already granted.
|
|
49
|
+
|
|
50
|
+
Reuse an approval to carry its exact bounded outcome end to end. When the user has already authorized a specific result, keep it moving through the authorized review, execution, checks, verification and final report needed to finish that same result; a milestone is a progress checkpoint, not a new permission gate. Do not hand the same milestone back for another approval or manufacture a decision that was already made. A changed target, added scope, unmet policy gate, or genuinely new authority is a real user or worker decision: name that precise dependency instead of asking the user to reapprove work already granted. This reuse never extends the approval to unrelated work and never relaxes a specialized skill's safety gates, including secret-handoff's per-operation authorization.
|
|
51
|
+
|
|
52
|
+
Coordinator waits need an owner and a wake. A worker-owned outcome stays `blocked` with `dependentOn="another-agent"` while its one continuous Core monitor is subscribed; a worker `done` or `idle` state is a cue to inspect the result, not proof of completion. A coordinator-owned command monitor keeps its task `active` with `owner: self` and uses `onDone` as the wake, not blocked status. A failed external service or tool keeps the task active and is reported with its concrete dependency; it is neither an agent output nor a user decision. Do not poll worker or monitor state on a timer, add one-shot waits, or repeat task updates that only restate waiting. Close a worker only after its output is verified and every named dependency for holding it has resolved.
|
|
53
|
+
|
|
54
|
+
### Multi-step specialized workflows
|
|
55
|
+
|
|
56
|
+
Delegate an installed multi-step workflow skill as one unit, before its preparation begins. When routing selects a skill such as `ui-ux-grill-me` or `grill-me`, assign the whole workflow to one worker conductor. Read only what is needed to recognize that the skill applies and to write the worker's bounded goal, constraints, acceptance criteria and forbidden actions; the worker verifies the skill's prerequisites and reports a blocker if one is missing. The worker discovers the remaining workflow details inside that boundary, and you do not need to solve or pre-validate the workflow's design before assigning it.
|
|
57
|
+
|
|
58
|
+
The main session must not perform the workflow's intake, grounding, detailed reference reading, project investigation, DAG, decision-tree or other artifact setup, screenshots, mockups, interviews or checks before delegating it. Handing over a partially prepared workflow is the same error as running it locally.
|
|
59
|
+
|
|
60
|
+
In a specialized skill, `parent`, `conductor` or a similar role name means the owner of that workflow, normally the delegated worker, not this conversational coordinator. Reading the skill does not make the main session its parent, and its preparation steps are not coordinator bookkeeping.
|
|
61
|
+
|
|
62
|
+
Keep the surrounding coordination local: clarification, human decisions, required tracking, dispatch, monitoring and accepting evidence. Read each worker's complete result and original artifacts before accepting the workflow.
|
|
63
|
+
|
|
64
|
+
### Worker close retrospective
|
|
65
|
+
|
|
66
|
+
Only you can decide that a worker needs nothing further, so you own both the trigger and the queue. A worker is the temporary owner of one assignment, not a reservation for later work. Once its assignment is complete, you have verified its result, and no concrete follow-up remains, send the real `/close` command to that still-live worker with the backend's send tool (`AgentSend`), wait for that run to finish, and read the `improvements.md` record it reports from its own session/work/task artifact path. Then close the worker terminal with the backend's close tool (`AgentClose`).
|
|
67
|
+
|
|
68
|
+
Hold a worker open only for a named, real dependency you can state in one clause: a specific pending review result, a human decision, or an integration step that will actually consume its output. "It may be needed later", keeping the author available in case something breaks, and other hypothetical follow-ups are not dependencies. When the only reason to keep a worker is an outstanding verification that does not need that worker, record it in your handoff or summary and close the worker instead.
|
|
69
|
+
|
|
70
|
+
Reassess at every milestone. After each review result, human decision, and integration or verification step, recheck every worker you are still holding: close the ones whose dependency resolved or turned out not to exist, and keep the rest only with their named reason. Letting idle workers accumulate across milestones is the failure this rule prevents.
|
|
71
|
+
|
|
72
|
+
The worker recognizes both a typed `/close` command and the backend-wrapped request (`<hc …>/close</hc>`), and both start the same bundled workflow; the wrapped form is not left for the worker to improvise. Do not send `/close` before verification, at an interim report, while a named dependency is genuinely pending, or as a substitute for closing. The command changes nothing and never closes a terminal; a repeat run merges into the existing record, which is a single `improvements.md` directly in the worker's canonical task directory. If a worker cannot run it, report that limitation instead of claiming a retrospective exists. Closing follows the backend's normal lifecycle, including any required timing export and import. It never authorizes sending `/close`, interrupting or closing a worker that is still executing an accepted assignment, is blocked awaiting input, or belongs to a terminal or session this coordinator does not own.
|
|
73
|
+
|
|
74
|
+
Read the whole record before condensing it. Keep one line per finding from every section in `status.md`, tracking or your summary, preserve each Speed entry's stated cost or its `not measured` note, and keep the skill, documentation or codebase routing instead of restating a process finding as a correctness defect.
|
|
75
|
+
|
|
76
|
+
## Standard routing examples
|
|
77
|
+
|
|
78
|
+
Keep small-scope inspection in the main session:
|
|
79
|
+
|
|
80
|
+
- "What does this function do?" or "where is this value set?"—read the relevant files and answer locally.
|
|
81
|
+
- "Which file defines this symbol?" or "what is in this directory?"—use `grep`, `find` or `ls` locally.
|
|
82
|
+
- Confirm `/firstmate status`, read a worker's result, or update coordinator tracking and artifacts—local coordination work.
|
|
83
|
+
- Review the shape of a proposed one-file change—reading and reasoning are local, but the edit itself still goes to a worker because coordinator mode has no edit or write tools.
|
|
84
|
+
|
|
85
|
+
Delegate tasks that change the project or span several areas:
|
|
86
|
+
|
|
87
|
+
- Debugging that crosses several files, commands or logs.
|
|
88
|
+
- Project edits, refactors, new files, builds, typechecks, migrations and environment changes.
|
|
89
|
+
- Independent review or verification of a change.
|
|
90
|
+
- Non-unit checks, and any test run the user explicitly allows.
|
|
91
|
+
- A quick check that grows into substantial investigation.
|
|
92
|
+
|
|
93
|
+
Delegate a multi-step specialized workflow as a whole, before it starts:
|
|
94
|
+
|
|
95
|
+
- "Set up a UI/UX interview for this screen" or "grill me on this plan"—select the installed `ui-ux-grill-me` or `grill-me` skill and give one worker conductor the bounded goal, constraints, acceptance criteria and forbidden actions. Keep only clarification, human decisions, tracking, dispatch, monitoring and evidence acceptance local. Do not capture the baseline, read the workflow references, produce its options or mockups, create its DAG or decision tree, or open its first question in the main session.
|
|
96
|
+
|
|
97
|
+
## Boundaries
|
|
98
|
+
|
|
99
|
+
- Do not silently implement a delegated task in the main session. If no working backend is available, or delegation is blocked or fails, report the concrete blocker, any partial resources and safe options. Ask how to proceed rather than silently performing substantial work locally.
|
|
100
|
+
- Inspect the worker's actual changed files, output and checks before accepting work. A worker's claim, idle status or process exit is not verification. Delegate substantive review and execution checks instead of doing them locally.
|
|
101
|
+
- Do not add First Mate-specific orchestration, worker registries, schedulers, worktrees or timing limits. Use existing capabilities. The package already enforces the coordinator tool allowlist described below; do not duplicate it in prompts or invent additional restrictions.
|
|
102
|
+
- Do not bypass permissions, trust, side-conversation boundaries or model routing because work is delegated. Reusing an existing authorization completes only the exact approved outcome; it does not authorize another target, provider, environment, or scope.
|
|
103
|
+
- In a worker session, ignore coordinator guidance from this skill and execute the assignment under ordinary project and host instructions.
|
|
104
|
+
|
|
105
|
+
## Coordinator tool availability
|
|
106
|
+
|
|
107
|
+
When First Mate is effectively on in a primary session, the extension restricts the model to `read`, `grep`, `find`, `ls` and every tool registered by an installed pi-tasks, pi-loop-monitor, pi-decisions, pi-herdr or pi-schedulers package. Other registered tools are removed from the model-facing set and re-filtered before each request, including tools registered during a multi-turn run, and direct or nested calls to them are rejected at Pi's `tool_call` boundary with a delegation explanation. The allowlist is derived from the packages' actual installed registrations, not from tool annotations, so their orchestration, tracking, decision and monitor tools stay usable unchanged. In particular, `MonitorCreate` keeps its normal arguments and behavior.
|
|
108
|
+
|
|
109
|
+
Scheduler creation is a coordinator-only optional capability. The scheduler package owns its registration, schema, confirmation and storage; First Mate controls only its exposure through the authoritative effective mode. Absent/off/suppressed First Mate keeps it hidden. Without UI, or after cancellation, abort or an effective-mode change while the confirmation is open, nothing is saved. It does not grant project trust/authentication or create a worktree during authoring. Scheduled workers keep normal configured tools/extensions/MCP with First Mate suppressed and cannot recursively use coordinator-only creation. Never route a scheduling request through a worker to bypass this human gate.
|
|
110
|
+
|
|
111
|
+
### Missing shell and codemode are intentional
|
|
112
|
+
|
|
113
|
+
`bash`, `edit`, `write` and `codemode` are intentionally unavailable to a coordinator; calls to them are blocked even though they work in ordinary sessions. This is the coordinator restriction, not a broken package, missing permission or configuration error. Do not ask the user to enable those tools, and do not try to bypass the allowlist with another tool.
|
|
114
|
+
|
|
115
|
+
When a shell or codemode call is blocked, treat it as a routing signal:
|
|
116
|
+
|
|
117
|
+
1. Check that an authorized delegation backend is actually installed and ready—use `/firstmate status`, the backend's own status or list tools (with pi-herdr, its Agent tools), or its documented checks.
|
|
118
|
+
2. Delegate the work through that backend.
|
|
119
|
+
3. If the backend is unavailable or fails, report the concrete blocker and safe options and ask how to proceed. Do not silently do substantial work locally; use `/firstmate off` only if the user chooses to leave coordinator mode.
|
|
120
|
+
|
|
121
|
+
Off mode, a `--firstmate-worker` process and verified Core workers keep ordinary tool availability. Turning coordinator mode off restores the active-tool set from before the restriction without activating unrelated tools. The baseline is recorded in existing session state under this session's identity, so `/firstmate 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.
|
|
122
|
+
|
|
123
|
+
This is Pi tool-call enforcement, not an OS sandbox. It cannot make an allowed tool harmless: an allowed monitor or agent tool can still start or control processes, and project trust, permissions, user authorization and `/ask` or `/btw` boundaries still apply. Do not claim absolute prevention through explicitly allowed tools.
|
|
124
|
+
|
|
125
|
+
## Mode and configuration
|
|
126
|
+
|
|
127
|
+
- `/firstmate on` and `/firstmate off` set a session-only override; `/firstmate default` clears it; `/firstmate status` reports effective state, configured default and worker suppression.
|
|
128
|
+
- The configured default is settings.json `"pi-firstmate": { "enabled": false }`; omitting it means off. A trusted project `.pi/settings.json` can override it.
|
|
129
|
+
- The optional `pi-firstmate.coordinatorSkills` list narrows the host's model-facing skill advertisement while coordinator mode is on: exact discovered names only, `[]` advertises none, omitted advertises all. It is routing only—it does not remove skills, permissions or already loaded instructions, and `/skill:name` still resolves from the complete discovery list. Do not describe a filtered skill as deleted or unavailable; use `/skill:name` when an explicit load is needed.
|
|
130
|
+
- `--firstmate-worker` always suppresses coordinator mode regardless of default or session override, and skips optional Core detection. Other launchers should pass this flag to child Pi processes that load this extension, especially with a shared default-on configuration.
|
|
131
|
+
- Without that explicit flag, optional pi-herdr/Core detection verifies workers through both `pi.task` and `pi.session` labels. `HC_TERMINAL_ID` alone is not a worker marker. Unknown third-party launchers are not automatically recognized.
|
|
132
|
+
- A failed Core lookup suppresses default-on with a diagnostic. An explicit `/firstmate on` can still enable an unclassified session; only use it when this is the coordinator. Verified or explicitly marked workers stay suppressed.
|
|
133
|
+
- The coordinator tool allowlist is enforced by the extension, not only by this skill. Off sessions, explicit `--firstmate-worker` processes and verified Core workers have ordinary tool availability.
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
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
|
+
|
|
9
|
+
export const FIRST_MATE_SETTINGS_KEY = "pi-firstmate";
|
|
10
|
+
|
|
11
|
+
export type ConfiguredDefault =
|
|
12
|
+
| {
|
|
13
|
+
kind: "valid";
|
|
14
|
+
enabled: boolean;
|
|
15
|
+
banner: boolean;
|
|
16
|
+
bannerProblem?: string;
|
|
17
|
+
/** Exact skill names to advertise while coordinator mode is effective; `undefined` advertises every discovered skill. */
|
|
18
|
+
coordinatorSkills?: string[];
|
|
19
|
+
coordinatorSkillsProblem?: string;
|
|
20
|
+
}
|
|
21
|
+
| { kind: "invalid"; message: string };
|
|
22
|
+
|
|
23
|
+
const DEFAULT_OFF: ConfiguredDefault = { kind: "valid", enabled: false, banner: true };
|
|
24
|
+
|
|
25
|
+
function describeValue(value: unknown): string {
|
|
26
|
+
if (value === null) return "null";
|
|
27
|
+
if (Array.isArray(value)) return "an array";
|
|
28
|
+
if (typeof value === "string") return "a string";
|
|
29
|
+
if (typeof value === "number") return "a number";
|
|
30
|
+
if (typeof value === "boolean") return "a boolean";
|
|
31
|
+
return typeof value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Resolve the configured default.
|
|
36
|
+
*
|
|
37
|
+
* A missing section, a missing `enabled`, or an empty section means `false`.
|
|
38
|
+
* A malformed section or `enabled` is reported instead of silently enabling
|
|
39
|
+
* coordinator mode. A malformed optional `banner` disables only the banner and
|
|
40
|
+
* keeps the valid `enabled` value; the problem is carried as a diagnostic.
|
|
41
|
+
* A malformed optional `coordinatorSkills` disables only that filter, so an
|
|
42
|
+
* invalid value advertises every discovered skill instead of hiding all of
|
|
43
|
+
* them.
|
|
44
|
+
*/
|
|
45
|
+
export function readConfiguredDefault(settings: unknown): ConfiguredDefault {
|
|
46
|
+
if (typeof settings !== "object" || settings === null || Array.isArray(settings)) {
|
|
47
|
+
return { kind: "invalid", message: "Pi returned settings that are not an object" };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const section = (settings as Record<string, unknown>)[FIRST_MATE_SETTINGS_KEY];
|
|
51
|
+
if (section === undefined) return DEFAULT_OFF;
|
|
52
|
+
if (typeof section !== "object" || section === null || Array.isArray(section)) {
|
|
53
|
+
return {
|
|
54
|
+
kind: "invalid",
|
|
55
|
+
message: `expected "${FIRST_MATE_SETTINGS_KEY}" to be an object such as {"enabled": false}, found ${describeValue(section)}`,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const enabled = (section as Record<string, unknown>).enabled;
|
|
60
|
+
if (enabled !== undefined && typeof enabled !== "boolean") {
|
|
61
|
+
return {
|
|
62
|
+
kind: "invalid",
|
|
63
|
+
message: `expected "${FIRST_MATE_SETTINGS_KEY}.enabled" to be true or false, found ${describeValue(enabled)}`,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const banner = (section as Record<string, unknown>).banner;
|
|
68
|
+
const bannerProblem =
|
|
69
|
+
banner !== undefined && typeof banner !== "boolean"
|
|
70
|
+
? `expected "${FIRST_MATE_SETTINGS_KEY}.banner" to be true or false, found ${describeValue(banner)}`
|
|
71
|
+
: undefined;
|
|
72
|
+
|
|
73
|
+
const skills = readCoordinatorSkills((section as Record<string, unknown>).coordinatorSkills);
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
kind: "valid",
|
|
77
|
+
enabled: enabled ?? false,
|
|
78
|
+
banner: banner === undefined ? true : typeof banner === "boolean" ? banner : false,
|
|
79
|
+
...(bannerProblem === undefined ? {} : { bannerProblem }),
|
|
80
|
+
...(skills.names === undefined ? {} : { coordinatorSkills: skills.names }),
|
|
81
|
+
...(skills.problem === undefined ? {} : { coordinatorSkillsProblem: skills.problem }),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface CoordinatorSkillsSetting {
|
|
86
|
+
names?: string[];
|
|
87
|
+
problem?: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Read the optional exact-name allowlist. An invalid value disables only this
|
|
92
|
+
* filter: coordinator mode keeps advertising every discovered skill rather than
|
|
93
|
+
* silently hiding all of them. Duplicate names are collapsed in order.
|
|
94
|
+
*/
|
|
95
|
+
function readCoordinatorSkills(value: unknown): CoordinatorSkillsSetting {
|
|
96
|
+
if (value === undefined) return {};
|
|
97
|
+
if (!Array.isArray(value)) {
|
|
98
|
+
return {
|
|
99
|
+
problem: `expected "${FIRST_MATE_SETTINGS_KEY}.coordinatorSkills" to be an array of exact skill names, found ${describeValue(value)}`,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const names: string[] = [];
|
|
104
|
+
for (const item of value) {
|
|
105
|
+
if (typeof item !== "string") {
|
|
106
|
+
return {
|
|
107
|
+
problem: `expected every "${FIRST_MATE_SETTINGS_KEY}.coordinatorSkills" entry to be a skill name string, found ${describeValue(item)}`,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
if (item.trim() === "") {
|
|
111
|
+
return {
|
|
112
|
+
problem: `expected every "${FIRST_MATE_SETTINGS_KEY}.coordinatorSkills" entry to be a nonempty skill name, found an empty name`,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
if (!names.includes(item)) names.push(item);
|
|
116
|
+
}
|
|
117
|
+
return { names };
|
|
118
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
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
|
+
|
|
14
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
17
|
+
|
|
18
|
+
export const BANNER_MOD = "firstmate-banner";
|
|
19
|
+
export const BANNER_NODE_ID = "firstmate-banner";
|
|
20
|
+
|
|
21
|
+
const SHIPPED_LAYOUTS = new Set(["main", "terminals", "win98"]);
|
|
22
|
+
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
23
|
+
const TERMINAL_ID = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?t[0-9a-z]+$/;
|
|
24
|
+
const LAYOUT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
25
|
+
const ASSET_NAMES = ["main.js", "mod.json", "README.md"] as const;
|
|
26
|
+
|
|
27
|
+
type Json = Record<string, unknown>;
|
|
28
|
+
|
|
29
|
+
export interface BannerSetup {
|
|
30
|
+
/** installed: this call wrote something. present: everything already matched. */
|
|
31
|
+
state: "installed" | "present" | "unavailable";
|
|
32
|
+
detail: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface BannerState {
|
|
36
|
+
sessionId: string;
|
|
37
|
+
terminal: string;
|
|
38
|
+
effective: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isRecord(value: unknown): value is Json {
|
|
42
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function errorText(error: unknown): string {
|
|
46
|
+
const line = (error instanceof Error ? error.message : String(error)).split("\n", 1)[0]?.trim();
|
|
47
|
+
return line === undefined || line === "" ? "unknown error" : line;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The Herdr app home, matching the app's own lookup: `HERDR_APP_HOME`, else
|
|
52
|
+
* `XDG_CONFIG_HOME/herdr-app`, else `~/.config/herdr-app`.
|
|
53
|
+
*/
|
|
54
|
+
export function herdrAppHome(env: NodeJS.ProcessEnv = process.env): string {
|
|
55
|
+
const custom = env.HERDR_APP_HOME?.trim();
|
|
56
|
+
if (custom !== undefined && custom !== "") return resolve(custom);
|
|
57
|
+
const config = env.XDG_CONFIG_HOME?.trim();
|
|
58
|
+
const base = config !== undefined && config !== "" && isAbsolute(config) ? config : join(homedir(), ".config");
|
|
59
|
+
return join(base, "herdr-app");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function bannerDataDir(appHome: string): string {
|
|
63
|
+
return join(appHome, "data", BANNER_MOD);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function writeAtomic(path: string, data: string | Buffer): void {
|
|
67
|
+
const temporary = `${path}.firstmate-${process.pid}-${Date.now()}.tmp`;
|
|
68
|
+
writeFileSync(temporary, data);
|
|
69
|
+
try {
|
|
70
|
+
renameSync(temporary, path);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
rmSync(temporary, { force: true });
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Keep the previous installed copy next to the recovery notes, not in the live mod folder. */
|
|
78
|
+
function backup(path: string, name: string, backupDir: string): void {
|
|
79
|
+
mkdirSync(backupDir, { recursive: true });
|
|
80
|
+
copyFileSync(path, join(backupDir, `${Date.now()}-${name}`));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Install or update only the files this package owns; never duplicate identical content. */
|
|
84
|
+
function installAssets(appHome: string, assets: Map<string, Buffer>, backupDir: string): void {
|
|
85
|
+
const directory = join(appHome, "mods", BANNER_MOD);
|
|
86
|
+
mkdirSync(directory, { recursive: true });
|
|
87
|
+
for (const [name, data] of assets) {
|
|
88
|
+
const target = join(directory, name);
|
|
89
|
+
if (existsSync(target) && readFileSync(target).equals(data)) continue;
|
|
90
|
+
if (existsSync(target)) backup(target, name, backupDir);
|
|
91
|
+
writeAtomic(target, data);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The layout the running window shows, from the app's shared state. */
|
|
96
|
+
function shownLayout(appHome: string): string | undefined {
|
|
97
|
+
try {
|
|
98
|
+
const parsed: unknown = JSON.parse(readFileSync(join(appHome, "shared.json"), "utf8"));
|
|
99
|
+
if (!isRecord(parsed) || typeof parsed.layout !== "string" || !LAYOUT_NAME.test(parsed.layout)) return undefined;
|
|
100
|
+
return parsed.layout;
|
|
101
|
+
} catch {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function findNode(node: unknown, id: string): Json | undefined {
|
|
107
|
+
if (!isRecord(node)) return undefined;
|
|
108
|
+
if (node.id === id) return node;
|
|
109
|
+
for (const child of Array.isArray(node.children) ? node.children : []) {
|
|
110
|
+
const found = findNode(child, id);
|
|
111
|
+
if (found !== undefined) return found;
|
|
112
|
+
}
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The root-to-block path of the layout node that shows the active tab. */
|
|
117
|
+
function pathToActiveTab(node: unknown, trail: Json[] = []): Json[] | undefined {
|
|
118
|
+
if (!isRecord(node)) return undefined;
|
|
119
|
+
const path = [...trail, node];
|
|
120
|
+
if (isRecord(node.content) && node.content.tab === "active") return path;
|
|
121
|
+
for (const child of Array.isArray(node.children) ? node.children : []) {
|
|
122
|
+
const found = pathToActiveTab(child, path);
|
|
123
|
+
if (found !== undefined) return found;
|
|
124
|
+
}
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Insert directly before the child of the nearest `column` ancestor that
|
|
130
|
+
* contains the active tab. In the shipped main layout that is `work.children`
|
|
131
|
+
* before `work-body`; the tab block, pane frame and side panels are untouched.
|
|
132
|
+
*/
|
|
133
|
+
function insertionSpot(root: Json): { children: unknown[]; index: number } | undefined {
|
|
134
|
+
const path = pathToActiveTab(root);
|
|
135
|
+
if (path === undefined || path.length < 2) return undefined;
|
|
136
|
+
for (let index = path.length - 1; index >= 1; index -= 1) {
|
|
137
|
+
const parent = path[index - 1];
|
|
138
|
+
const child = path[index];
|
|
139
|
+
if (parent === undefined || child === undefined || parent.type !== "column" || !Array.isArray(parent.children)) continue;
|
|
140
|
+
const at = parent.children.indexOf(child);
|
|
141
|
+
if (at >= 0) return { children: parent.children, index: at };
|
|
142
|
+
}
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function installLayoutNode(appHome: string, layoutName: string, backupDir: string): "installed" | "present" {
|
|
147
|
+
const path = join(appHome, "layouts", `${layoutName}.json`);
|
|
148
|
+
const original = readFileSync(path, "utf8");
|
|
149
|
+
const tree: unknown = JSON.parse(original);
|
|
150
|
+
if (!isRecord(tree)) throw new Error(`layout "${layoutName}" is not a layout object`);
|
|
151
|
+
if (findNode(tree, BANNER_NODE_ID) !== undefined) return "present";
|
|
152
|
+
const spot = insertionSpot(tree);
|
|
153
|
+
if (spot === undefined) {
|
|
154
|
+
throw new Error(`layout "${layoutName}" has no column above its active-tab block, so there is nowhere to place the banner`);
|
|
155
|
+
}
|
|
156
|
+
spot.children.splice(spot.index, 0, {
|
|
157
|
+
id: BANNER_NODE_ID,
|
|
158
|
+
type: "block",
|
|
159
|
+
size: { px: 0 },
|
|
160
|
+
content: { mod: BANNER_MOD },
|
|
161
|
+
});
|
|
162
|
+
backup(path, `${layoutName}.json`, backupDir);
|
|
163
|
+
writeAtomic(path, `${JSON.stringify(tree, null, 2)}\n`);
|
|
164
|
+
return "installed";
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Make the installed mod and the shown personal layout ready for the banner.
|
|
169
|
+
* Callers treat `unavailable` as a diagnostic, never as a First Mate failure.
|
|
170
|
+
*/
|
|
171
|
+
export function ensureHerdrBanner(appHome: string, assets: URL): BannerSetup {
|
|
172
|
+
try {
|
|
173
|
+
if (!existsSync(appHome) || !statSync(appHome).isDirectory()) {
|
|
174
|
+
return { state: "unavailable", detail: `the Herdr app home ${appHome} does not exist` };
|
|
175
|
+
}
|
|
176
|
+
const contents = new Map<string, Buffer>();
|
|
177
|
+
for (const name of ASSET_NAMES) {
|
|
178
|
+
try {
|
|
179
|
+
contents.set(name, readFileSync(new URL(name, assets)));
|
|
180
|
+
} catch {
|
|
181
|
+
return { state: "unavailable", detail: `the packaged banner asset ${name} is missing` };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const backupDir = join(bannerDataDir(appHome), "backups");
|
|
185
|
+
const modDir = join(appHome, "mods", BANNER_MOD);
|
|
186
|
+
const hadMod = existsSync(join(modDir, "main.js"));
|
|
187
|
+
installAssets(appHome, contents, backupDir);
|
|
188
|
+
|
|
189
|
+
const layoutName = shownLayout(appHome);
|
|
190
|
+
if (layoutName === undefined) {
|
|
191
|
+
return { state: "unavailable", detail: "the Herdr window has no shown layout yet" };
|
|
192
|
+
}
|
|
193
|
+
if (SHIPPED_LAYOUTS.has(layoutName)) {
|
|
194
|
+
return {
|
|
195
|
+
state: "unavailable",
|
|
196
|
+
detail: `the shown layout "${layoutName}" is shipped by Herdr; switch to a personal layout to show the banner`,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
if (!existsSync(join(appHome, "layouts", `${layoutName}.json`))) {
|
|
200
|
+
return { state: "unavailable", detail: `the shown layout file ${layoutName}.json is missing` };
|
|
201
|
+
}
|
|
202
|
+
const layout = installLayoutNode(appHome, layoutName, backupDir);
|
|
203
|
+
if (layout === "present" && hadMod) return { state: "present", detail: `present in Herdr layout "${layoutName}"` };
|
|
204
|
+
return { state: "installed", detail: `installed in Herdr layout "${layoutName}"` };
|
|
205
|
+
} catch (error) {
|
|
206
|
+
return { state: "unavailable", detail: errorText(error) };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Publish this session's effective mode for the banner mod. The file is
|
|
212
|
+
* replaced atomically; a file left by an earlier Pi session in the same
|
|
213
|
+
* terminal is removed so it cannot override this one.
|
|
214
|
+
*/
|
|
215
|
+
export function writeBannerState(appHome: string, state: BannerState): void {
|
|
216
|
+
if (!SESSION_ID.test(state.sessionId)) throw new Error("invalid Pi session ID");
|
|
217
|
+
if (!TERMINAL_ID.test(state.terminal)) throw new Error("invalid Core terminal address");
|
|
218
|
+
const directory = bannerDataDir(appHome);
|
|
219
|
+
mkdirSync(directory, { recursive: true });
|
|
220
|
+
for (const name of readdirSync(directory)) {
|
|
221
|
+
if (!name.endsWith(".json")) continue;
|
|
222
|
+
const path = join(directory, name);
|
|
223
|
+
try {
|
|
224
|
+
const value: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
225
|
+
if (isRecord(value) && value.terminal === state.terminal && value.sessionId !== state.sessionId) rmSync(path, { force: true });
|
|
226
|
+
} catch {
|
|
227
|
+
// A damaged foreign file is ignored; it can never match the banner.
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
writeAtomic(
|
|
231
|
+
join(directory, `${state.sessionId}.json`),
|
|
232
|
+
`${JSON.stringify({
|
|
233
|
+
version: 1,
|
|
234
|
+
sessionId: state.sessionId,
|
|
235
|
+
terminal: state.terminal,
|
|
236
|
+
effective: state.effective,
|
|
237
|
+
updatedAt: Date.now(),
|
|
238
|
+
})}\n`,
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Best-effort shutdown cleanup; the banner disappears as soon as this file is gone. */
|
|
243
|
+
export function clearBannerState(appHome: string, sessionId: string, terminal?: string): void {
|
|
244
|
+
if (!SESSION_ID.test(sessionId)) return;
|
|
245
|
+
const directory = bannerDataDir(appHome);
|
|
246
|
+
try {
|
|
247
|
+
rmSync(join(directory, `${sessionId}.json`), { force: true });
|
|
248
|
+
} catch {
|
|
249
|
+
// Nothing useful to do on shutdown.
|
|
250
|
+
}
|
|
251
|
+
if (terminal === undefined || !TERMINAL_ID.test(terminal)) return;
|
|
252
|
+
// A primary session that crashed leaves a state file behind. If this
|
|
253
|
+
// terminal now runs a session that must not advertise (for example a
|
|
254
|
+
// worker), remove that leftover too so it cannot win by being older.
|
|
255
|
+
try {
|
|
256
|
+
for (const name of readdirSync(directory)) {
|
|
257
|
+
if (!name.endsWith(".json")) continue;
|
|
258
|
+
const path = join(directory, name);
|
|
259
|
+
try {
|
|
260
|
+
const value: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
261
|
+
if (isRecord(value) && value.terminal === terminal && value.sessionId !== sessionId) rmSync(path, { force: true });
|
|
262
|
+
} catch {
|
|
263
|
+
// Ignore a damaged foreign file.
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
} catch {
|
|
267
|
+
// The directory may not exist yet.
|
|
268
|
+
}
|
|
269
|
+
}
|