@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 +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 +56 -4
- package/skills/close/SKILL.md +61 -0
- package/skills/firstmate/SKILL.md +129 -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
package/src/index.ts
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* First Mate - configurable coordinator mode for primary Pi sessions.
|
|
3
|
+
*
|
|
4
|
+
* The mode keeps conversation, decisions and quick inspection in the main
|
|
5
|
+
* session, and delegates project execution to workers through an available
|
|
6
|
+
* installed orchestration backend. The behavioral policy lives in
|
|
7
|
+
* `skills/firstmate/SKILL.md`; this extension only owns configuration, the
|
|
8
|
+
* session toggle, worker suppression, status and per-run prompt guidance.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { readFileSync } from "node:fs";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import type {
|
|
14
|
+
ExtensionAPI,
|
|
15
|
+
ExtensionCommandContext,
|
|
16
|
+
ExtensionContext,
|
|
17
|
+
NormalizedBuildSystemPromptOptions,
|
|
18
|
+
} from "@earendil-works/pi-coding-agent";
|
|
19
|
+
import { type ConfiguredDefault, readConfiguredDefault } from "./config.js";
|
|
20
|
+
import { clearBannerState, ensureHerdrBanner, herdrAppHome, writeBannerState } from "./herdr-banner.js";
|
|
21
|
+
import { applySkillAllowlist } from "./skill-allowlist.js";
|
|
22
|
+
import { COORDINATOR_TOOLS_DESCRIPTION, createToolGate } from "./tool-gate.js";
|
|
23
|
+
import { classifyCoreWorker, type WorkerClassification } from "./worker.js";
|
|
24
|
+
|
|
25
|
+
const COMMAND_NAME = "firstmate";
|
|
26
|
+
const CLOSE_COMMAND_NAME = "close";
|
|
27
|
+
const ENTRY_TYPE = "pi-firstmate.mode";
|
|
28
|
+
const TOOL_ENTRY_TYPE = "pi-firstmate.tools";
|
|
29
|
+
const SECTION_KEY = "first_mate";
|
|
30
|
+
const STATUS_KEY = "firstmate";
|
|
31
|
+
const ASK_GUARD_RELEASED_EVENT = "pi-ask:guard:released";
|
|
32
|
+
const ASK_GUARD_PROBE_EVENT = "pi-ask:guard:probe";
|
|
33
|
+
const MODE_PROBE_EVENT = "pi-firstmate:mode:probe";
|
|
34
|
+
const MODE_CHANGED_EVENT = "pi-firstmate:mode:changed";
|
|
35
|
+
const SCHEDULER_TOOLS_CHANGED_EVENT = "pi-schedulers:tools:changed";
|
|
36
|
+
const POLICY_DISPLAY_PATH = "skills/firstmate/SKILL.md";
|
|
37
|
+
const POLICY_URL = new URL("../skills/firstmate/SKILL.md", import.meta.url);
|
|
38
|
+
const CLOSE_SKILL_DISPLAY_PATH = "skills/close/SKILL.md";
|
|
39
|
+
const CLOSE_SKILL_URL = new URL("../skills/close/SKILL.md", import.meta.url);
|
|
40
|
+
const BANNER_ASSETS = new URL("../herdr/firstmate-banner/", import.meta.url);
|
|
41
|
+
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
42
|
+
|
|
43
|
+
const SKILL_REMINDER = "Read the installed First Mate skill before acting.";
|
|
44
|
+
const ON_GUIDELINE =
|
|
45
|
+
`First Mate coordinator mode is active for this session. ${SKILL_REMINDER} Follow the <first_mate> section: keep conversation, decisions, quick inspection and coordination local, and delegate project execution to workers through an available, authorized orchestration backend following its actual instructions. If delegation is unavailable, report the blocker instead of silently doing substantial work locally.`;
|
|
46
|
+
const OFF_GUIDELINE =
|
|
47
|
+
"First Mate coordinator mode is off. Supersede any earlier First Mate coordinator guidance in this session and resume ordinary project and host instructions for project work.";
|
|
48
|
+
|
|
49
|
+
const USAGE =
|
|
50
|
+
"Usage: /firstmate on | off | default | status. With no argument, shows status.";
|
|
51
|
+
const CLOSE_USAGE =
|
|
52
|
+
"Usage: /close. Records the worker close retrospective; the coordinator verifies the record and closes the terminal.";
|
|
53
|
+
const CLOSE_COORDINATOR_NOTE =
|
|
54
|
+
"/close records a worker close retrospective, so it does not start one for a coordinator session. Once a worker's result is verified and it needs no follow-up, send this command to that live worker with AgentSend, wait for its record and final report, then close its terminal.";
|
|
55
|
+
// A coordinator sends the command through the backend's send tool, which wraps
|
|
56
|
+
// the text in an `hc` envelope. Pi dispatches a slash command only when the
|
|
57
|
+
// submitted text starts with `/`, so the wrapped request is recognized here.
|
|
58
|
+
const CLOSE_INPUT_REQUEST = /^(?:\s*<hc\b[^>]*>)?\s*\/close\s*(?:<\/hc>)?\s*$/i;
|
|
59
|
+
|
|
60
|
+
interface ModeResolution {
|
|
61
|
+
effective: boolean;
|
|
62
|
+
worker: WorkerClassification;
|
|
63
|
+
suppressed: boolean;
|
|
64
|
+
uncertain: boolean;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
type BannerStatus =
|
|
68
|
+
| { kind: "off"; detail: string }
|
|
69
|
+
| { kind: "ready"; detail: string }
|
|
70
|
+
| { kind: "unavailable"; detail: string };
|
|
71
|
+
|
|
72
|
+
function stripFrontmatter(markdown: string): string {
|
|
73
|
+
const match = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/.exec(markdown);
|
|
74
|
+
return match ? markdown.slice(match[0].length) : markdown;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function report(
|
|
78
|
+
ctx: ExtensionContext | ExtensionCommandContext,
|
|
79
|
+
message: string,
|
|
80
|
+
level: "info" | "warning" | "error" = "info",
|
|
81
|
+
): void {
|
|
82
|
+
if (ctx.hasUI) {
|
|
83
|
+
ctx.ui.notify(message, level);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
// Non-interactive modes have no dialog UI. Use stderr so print/json output
|
|
87
|
+
// on stdout is never corrupted by extension diagnostics.
|
|
88
|
+
console.error(message);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function errorText(error: unknown): string {
|
|
92
|
+
const line = (error instanceof Error ? error.message : String(error)).split("\n", 1)[0]?.trim();
|
|
93
|
+
return line === undefined || line === "" ? "unknown error" : line;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
97
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Read a persisted tool-name list; `null` is an explicit cleared marker. */
|
|
101
|
+
function readToolNames(value: unknown): string[] | null | undefined {
|
|
102
|
+
if (value === null) return null;
|
|
103
|
+
if (!Array.isArray(value)) return undefined;
|
|
104
|
+
const names: string[] = [];
|
|
105
|
+
for (const item of value) {
|
|
106
|
+
if (typeof item !== "string") return undefined;
|
|
107
|
+
if (!names.includes(item)) names.push(item);
|
|
108
|
+
}
|
|
109
|
+
return names;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function toolSetKey(tools: string[] | null): string | null {
|
|
113
|
+
return tools === null ? null : JSON.stringify([...tools].sort());
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export default function firstMateExtension(pi: ExtensionAPI): void {
|
|
117
|
+
pi.registerFlag("firstmate-worker", {
|
|
118
|
+
type: "boolean",
|
|
119
|
+
default: false,
|
|
120
|
+
description: "Mark this Pi process as a worker; always suppress First Mate coordinator guidance",
|
|
121
|
+
});
|
|
122
|
+
let config: ConfiguredDefault = { kind: "valid", enabled: false, banner: true };
|
|
123
|
+
let override: boolean | null = null;
|
|
124
|
+
let banner: BannerStatus | undefined;
|
|
125
|
+
let guidanceEvidence = false;
|
|
126
|
+
let worker: WorkerClassification | undefined;
|
|
127
|
+
let policyText: string | undefined;
|
|
128
|
+
let policyError: string | undefined;
|
|
129
|
+
let closeWorkflow: string | undefined;
|
|
130
|
+
let closeWorkflowError: string | undefined;
|
|
131
|
+
const toolGate = createToolGate(pi);
|
|
132
|
+
let savedActiveTools: string[] | null = null;
|
|
133
|
+
let savedBaselineKey: string | null = null;
|
|
134
|
+
let offRequestPrepared = false;
|
|
135
|
+
let skillWarningKey: string | null = null;
|
|
136
|
+
// Cached for the synchronous Ask release hook, which receives no context.
|
|
137
|
+
let sessionCtx: ExtensionContext | undefined;
|
|
138
|
+
let schedulerMode = false;
|
|
139
|
+
let modeGeneration = 0;
|
|
140
|
+
let publishedGeneration = -1;
|
|
141
|
+
|
|
142
|
+
// This synchronous query mirrors the existing effective-mode authority,
|
|
143
|
+
// including its explicit-on handling and verified-worker suppression.
|
|
144
|
+
function coordinatorMode(): { effective: boolean; generation: number } {
|
|
145
|
+
const mode = resolveMode();
|
|
146
|
+
const effective = sessionCtx !== undefined && mode.effective;
|
|
147
|
+
if (effective !== schedulerMode) {
|
|
148
|
+
schedulerMode = effective;
|
|
149
|
+
modeGeneration += 1;
|
|
150
|
+
}
|
|
151
|
+
return { effective, generation: modeGeneration };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function publishCoordinatorMode(): void {
|
|
155
|
+
const mode = coordinatorMode();
|
|
156
|
+
if (publishedGeneration === mode.generation) return;
|
|
157
|
+
publishedGeneration = mode.generation;
|
|
158
|
+
pi.events.emit(MODE_CHANGED_EVENT, undefined);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
pi.events.on(MODE_PROBE_EVENT, (request: unknown) => {
|
|
162
|
+
if (!isRecord(request)) return;
|
|
163
|
+
Object.assign(request, { available: true, protocolVersion: 1, ...coordinatorMode() });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
function refreshConfig(): void {
|
|
167
|
+
const settings: unknown = pi.getSettings();
|
|
168
|
+
const previous = config.kind === "valid" ? JSON.stringify(config.coordinatorSkills ?? null) : "invalid";
|
|
169
|
+
config = readConfiguredDefault(settings);
|
|
170
|
+
const current = config.kind === "valid" ? JSON.stringify(config.coordinatorSkills ?? null) : "invalid";
|
|
171
|
+
if (previous !== current) skillWarningKey = null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function coordinatorSkillNames(): string[] | undefined {
|
|
175
|
+
return config.kind === "valid" ? config.coordinatorSkills : undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Narrow this run's model-facing skill advertisement. Pi rebuilds a fresh
|
|
180
|
+
* normalized option list from its resource loader before every run, so the
|
|
181
|
+
* filter never carries into an off, worker or default run. Skill discovery,
|
|
182
|
+
* project-trust precedence and `/skill:<name>` resolution stay Pi's.
|
|
183
|
+
*/
|
|
184
|
+
function applyCoordinatorSkills(
|
|
185
|
+
options: NormalizedBuildSystemPromptOptions,
|
|
186
|
+
ctx: ExtensionContext,
|
|
187
|
+
): void {
|
|
188
|
+
const names = coordinatorSkillNames();
|
|
189
|
+
if (names === undefined) return;
|
|
190
|
+
|
|
191
|
+
const filtered = applySkillAllowlist(options.skills, names);
|
|
192
|
+
options.skills = filtered.skills;
|
|
193
|
+
if (filtered.unknown.length === 0) return;
|
|
194
|
+
|
|
195
|
+
const key = JSON.stringify(filtered.unknown);
|
|
196
|
+
if (key === skillWarningKey) return;
|
|
197
|
+
skillWarningKey = key;
|
|
198
|
+
report(
|
|
199
|
+
ctx,
|
|
200
|
+
`First Mate "pi-firstmate.coordinatorSkills" names skills that are not discovered: ${filtered.unknown.join(", ")}. They are not advertised; coordinator mode and the other advertised skills are unaffected.`,
|
|
201
|
+
"warning",
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function refreshSessionState(ctx: ExtensionContext | ExtensionCommandContext): void {
|
|
206
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
207
|
+
let restored: boolean | null = null;
|
|
208
|
+
let restoredTools: string[] | null = null;
|
|
209
|
+
let sawGuidanceSection = false;
|
|
210
|
+
|
|
211
|
+
// Session-level state: scan every entry, not only the active branch, so
|
|
212
|
+
// tree navigation inside one session does not silently undo the toggle.
|
|
213
|
+
for (const entry of ctx.sessionManager.getEntries()) {
|
|
214
|
+
if (entry.type === "message" && entry.message.role === "system") {
|
|
215
|
+
const sections = entry.message.sections;
|
|
216
|
+
const value = sections?.[SECTION_KEY];
|
|
217
|
+
if (value !== undefined && value !== null) sawGuidanceSection = true;
|
|
218
|
+
}
|
|
219
|
+
if (entry.type !== "custom") continue;
|
|
220
|
+
if (entry.customType === TOOL_ENTRY_TYPE) {
|
|
221
|
+
if (!isRecord(entry.data) || entry.data.sessionId !== sessionId) continue;
|
|
222
|
+
const tools = readToolNames(entry.data.tools);
|
|
223
|
+
if (tools !== undefined) restoredTools = tools;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (entry.customType !== ENTRY_TYPE) continue;
|
|
227
|
+
if (!isRecord(entry.data)) continue;
|
|
228
|
+
const data = entry.data;
|
|
229
|
+
if (data.sessionId !== sessionId) continue;
|
|
230
|
+
if (data.enabled !== true && data.enabled !== false && data.enabled !== null) continue;
|
|
231
|
+
restored = data.enabled;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
override = restored;
|
|
235
|
+
const coordinatorOnly = toolGate.coordinatorOnlyNames();
|
|
236
|
+
savedActiveTools = restoredTools?.filter((name) => !coordinatorOnly.has(name)) ?? null;
|
|
237
|
+
savedBaselineKey = toolSetKey(restoredTools);
|
|
238
|
+
// A persisted First Mate prompt section is direct evidence that earlier
|
|
239
|
+
// coordinator guidance exists in this session, including after reload.
|
|
240
|
+
guidanceEvidence = sawGuidanceSection;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function loadPolicy(): string | undefined {
|
|
244
|
+
if (policyText !== undefined) return policyText;
|
|
245
|
+
try {
|
|
246
|
+
const text = stripFrontmatter(readFileSync(fileURLToPath(POLICY_URL), "utf8")).trim();
|
|
247
|
+
if (text === "") throw new Error("the skill file is empty");
|
|
248
|
+
policyText = text;
|
|
249
|
+
policyError = undefined;
|
|
250
|
+
return policyText;
|
|
251
|
+
} catch (error) {
|
|
252
|
+
policyError = error instanceof Error ? error.message : String(error);
|
|
253
|
+
return undefined;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function loadCloseWorkflow(): string | undefined {
|
|
258
|
+
if (closeWorkflow !== undefined) return closeWorkflow;
|
|
259
|
+
try {
|
|
260
|
+
const text = stripFrontmatter(readFileSync(fileURLToPath(CLOSE_SKILL_URL), "utf8")).trim();
|
|
261
|
+
if (text === "") throw new Error("the skill file is empty");
|
|
262
|
+
closeWorkflow = text;
|
|
263
|
+
closeWorkflowError = undefined;
|
|
264
|
+
return closeWorkflow;
|
|
265
|
+
} catch (error) {
|
|
266
|
+
closeWorkflowError = error instanceof Error ? error.message : String(error);
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function closeRunText(
|
|
272
|
+
ctx: ExtensionContext | ExtensionCommandContext,
|
|
273
|
+
mode: ModeResolution,
|
|
274
|
+
): { text: string } | { error: string } {
|
|
275
|
+
const workflow = loadCloseWorkflow();
|
|
276
|
+
if (workflow === undefined) {
|
|
277
|
+
return {
|
|
278
|
+
error: `The close workflow could not be read from ${CLOSE_SKILL_DISPLAY_PATH}: ${closeWorkflowError}. Nothing was recorded and no run was started.`,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
282
|
+
const role =
|
|
283
|
+
mode.worker.kind === "worker"
|
|
284
|
+
? `verified Core worker for parent task ${mode.worker.task} in parent session ${mode.worker.parentSessionId}; the coordinator still verifies the result and closes this terminal`
|
|
285
|
+
: mode.worker.kind === "explicit-worker"
|
|
286
|
+
? "explicit worker process; the coordinator still verifies the result and closes this terminal"
|
|
287
|
+
: "ordinary session";
|
|
288
|
+
return {
|
|
289
|
+
text: `Run the close retrospective now. Session ${sessionId}; ${role}; repository working directory ${ctx.cwd}.\n\n${workflow}`,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function resolveMode(): ModeResolution {
|
|
294
|
+
const configuredDefault = config.kind === "valid" ? config.enabled : false;
|
|
295
|
+
const requested = override !== null ? override : configuredDefault;
|
|
296
|
+
const classification: WorkerClassification = worker ?? {
|
|
297
|
+
kind: "unknown",
|
|
298
|
+
terminalId: "",
|
|
299
|
+
message: "the Core worker check has not completed",
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
let effective = requested;
|
|
303
|
+
let uncertain = false;
|
|
304
|
+
if (classification.kind === "worker" || classification.kind === "explicit-worker") {
|
|
305
|
+
effective = false;
|
|
306
|
+
} else if (classification.kind === "unknown" && override === null && requested) {
|
|
307
|
+
// Never apply the configured default to a possible worker.
|
|
308
|
+
effective = false;
|
|
309
|
+
uncertain = true;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return {
|
|
313
|
+
effective,
|
|
314
|
+
worker: classification,
|
|
315
|
+
suppressed: (classification.kind === "worker" || classification.kind === "explicit-worker") && requested,
|
|
316
|
+
uncertain,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Restrict the model-facing tools while coordinator mode is effective, and
|
|
322
|
+
* restore the activation state from before the first restriction when it turns
|
|
323
|
+
* off. The baseline is persisted in existing session state so a resumed process
|
|
324
|
+
* can restore the exact pre-gate set before a model request records it again.
|
|
325
|
+
*/
|
|
326
|
+
function saveToolBaseline(ctx: ExtensionContext | ExtensionCommandContext, tools: string[] | null): void {
|
|
327
|
+
const key = toolSetKey(tools);
|
|
328
|
+
if (key === savedBaselineKey) return;
|
|
329
|
+
if (tools === null && savedBaselineKey === null) return;
|
|
330
|
+
pi.appendEntry(TOOL_ENTRY_TYPE, { sessionId: ctx.sessionManager.getSessionId(), tools });
|
|
331
|
+
savedBaselineKey = key;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function clearRestoredToolBaseline(ctx: ExtensionContext | ExtensionCommandContext): void {
|
|
335
|
+
if (resolveMode().effective || savedActiveTools === null) return;
|
|
336
|
+
const active = new Set(pi.getActiveTools());
|
|
337
|
+
if (!savedActiveTools.every((name) => active.has(name))) return;
|
|
338
|
+
savedActiveTools = null;
|
|
339
|
+
saveToolBaseline(ctx, null);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Ask (pi-research) answers this probe on Pi's shared event bus. While it
|
|
344
|
+
* reports an active read-only guard, restoring First Mate's saved tools would
|
|
345
|
+
* widen a restriction another extension is enforcing.
|
|
346
|
+
*/
|
|
347
|
+
function askGuardActive(): boolean {
|
|
348
|
+
const request: { available?: boolean; protocolVersion?: number; active?: boolean } = {};
|
|
349
|
+
pi.events.emit(ASK_GUARD_PROBE_EVENT, request);
|
|
350
|
+
return request.available === true && request.protocolVersion === 1 && request.active === true;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function syncToolGate(ctx: ExtensionContext | ExtensionCommandContext): void {
|
|
354
|
+
publishCoordinatorMode();
|
|
355
|
+
const coordinatorOnly = toolGate.coordinatorOnlyNames();
|
|
356
|
+
const ordinaryTools = (tools: string[]): string[] => tools.filter((name) => !coordinatorOnly.has(name));
|
|
357
|
+
if (savedActiveTools !== null) savedActiveTools = ordinaryTools(savedActiveTools);
|
|
358
|
+
if (!coordinatorMode().effective || askGuardActive()) {
|
|
359
|
+
const active = pi.getActiveTools();
|
|
360
|
+
const kept = ordinaryTools(active);
|
|
361
|
+
if (kept.length !== active.length) pi.setActiveTools(kept);
|
|
362
|
+
}
|
|
363
|
+
if (resolveMode().effective) {
|
|
364
|
+
offRequestPrepared = false;
|
|
365
|
+
const active = pi.getActiveTools();
|
|
366
|
+
// Record everything that is actually active before hiding it. This
|
|
367
|
+
// includes direct tools registered and auto-activated during the run,
|
|
368
|
+
// without adding tools that were never active.
|
|
369
|
+
savedActiveTools = ordinaryTools(savedActiveTools === null ? active : [...new Set([...savedActiveTools, ...active])]);
|
|
370
|
+
saveToolBaseline(ctx, savedActiveTools);
|
|
371
|
+
toolGate.hide();
|
|
372
|
+
// Never widen ASK's read-only set. Only the owning scheduler can make
|
|
373
|
+
// its registration declarable; do not guess a foreign tool name.
|
|
374
|
+
if (coordinatorMode().effective && !askGuardActive()) {
|
|
375
|
+
const available = pi.getAllTools().filter((tool) => coordinatorOnly.has(tool.name) && tool.exposure === "model-only");
|
|
376
|
+
const current = pi.getActiveTools();
|
|
377
|
+
const missing = available.filter((tool) => !current.includes(tool.name));
|
|
378
|
+
if (missing.length > 0) pi.setActiveTools([...current, ...missing.map((tool) => tool.name)]);
|
|
379
|
+
}
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
if (savedActiveTools === null) return;
|
|
383
|
+
|
|
384
|
+
// Another extension's read-only guard is enforcing its own tool set.
|
|
385
|
+
// Restoring here would widen it; the released hook below runs this gate
|
|
386
|
+
// again after that guard restores its captured list.
|
|
387
|
+
if (askGuardActive()) return;
|
|
388
|
+
|
|
389
|
+
const active = pi.getActiveTools();
|
|
390
|
+
const activeSet = new Set(active);
|
|
391
|
+
if (savedActiveTools.some((name) => !activeSet.has(name))) {
|
|
392
|
+
pi.setActiveTools([...new Set([...savedActiveTools, ...active])]);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function classifyWorker(): Promise<WorkerClassification> {
|
|
397
|
+
// An explicit process marker must not depend on hc being installed or live.
|
|
398
|
+
if (pi.getFlag("firstmate-worker") === true) return { kind: "explicit-worker" };
|
|
399
|
+
return classifyCoreWorker(pi);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async function ensureWorkerKnown(): Promise<void> {
|
|
403
|
+
if (worker !== undefined && worker.kind !== "unknown") return;
|
|
404
|
+
worker = await classifyWorker();
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function saveOverride(enabled: boolean | null, ctx: ExtensionCommandContext): void {
|
|
408
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
409
|
+
pi.appendEntry(ENTRY_TYPE, { sessionId, enabled });
|
|
410
|
+
override = enabled;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function syncIndicator(ctx: ExtensionContext | ExtensionCommandContext): void {
|
|
414
|
+
ctx.ui.setStatus(STATUS_KEY, resolveMode().effective ? "First Mate · read skill" : undefined);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Publish the effective mode that the optional Herdr banner reads, and make
|
|
419
|
+
* the mod/layout ready in a verified primary Core session. Workers, non-Core
|
|
420
|
+
* sessions and an inconclusive Core check clear their own state instead of
|
|
421
|
+
* advertising coordinator mode. Banner problems never affect First Mate.
|
|
422
|
+
*/
|
|
423
|
+
function syncBanner(ctx: ExtensionContext | ExtensionCommandContext): void {
|
|
424
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
425
|
+
const mode = resolveMode();
|
|
426
|
+
const clearOwnState = (): void => {
|
|
427
|
+
const terminal = "terminalId" in mode.worker ? mode.worker.terminalId : process.env.HC_TERMINAL_ID?.trim();
|
|
428
|
+
try {
|
|
429
|
+
clearBannerState(herdrAppHome(), sessionId, terminal);
|
|
430
|
+
} catch {
|
|
431
|
+
// Banner cleanup must never disturb mode.
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
if (config.kind === "invalid") {
|
|
435
|
+
clearOwnState();
|
|
436
|
+
banner = { kind: "off", detail: "settings are invalid" };
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (config.bannerProblem !== undefined) {
|
|
440
|
+
clearOwnState();
|
|
441
|
+
banner = { kind: "off", detail: `invalid setting: ${config.bannerProblem}` };
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (!config.banner) {
|
|
445
|
+
clearOwnState();
|
|
446
|
+
banner = { kind: "off", detail: 'disabled by "pi-firstmate.banner"' };
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
if (!SESSION_ID.test(sessionId)) {
|
|
450
|
+
banner = { kind: "unavailable", detail: "the Pi session ID cannot identify a state file" };
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
switch (mode.worker.kind) {
|
|
454
|
+
case "explicit-worker":
|
|
455
|
+
case "worker":
|
|
456
|
+
clearOwnState();
|
|
457
|
+
banner = { kind: "off", detail: "worker sessions never show it" };
|
|
458
|
+
return;
|
|
459
|
+
case "not-core":
|
|
460
|
+
clearOwnState();
|
|
461
|
+
banner = { kind: "off", detail: "this Pi process is not in a Herdr Core terminal" };
|
|
462
|
+
return;
|
|
463
|
+
case "unknown":
|
|
464
|
+
clearOwnState();
|
|
465
|
+
banner = { kind: "off", detail: `the Core worker check failed (${mode.worker.message})` };
|
|
466
|
+
return;
|
|
467
|
+
case "primary": {
|
|
468
|
+
const appHome = herdrAppHome();
|
|
469
|
+
const setup = ensureHerdrBanner(appHome, BANNER_ASSETS);
|
|
470
|
+
try {
|
|
471
|
+
writeBannerState(appHome, {
|
|
472
|
+
sessionId,
|
|
473
|
+
terminal: mode.worker.terminalId,
|
|
474
|
+
effective: mode.effective,
|
|
475
|
+
});
|
|
476
|
+
} catch (error) {
|
|
477
|
+
banner = { kind: "unavailable", detail: `the session state could not be written: ${errorText(error)}` };
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
banner =
|
|
481
|
+
setup.state === "unavailable"
|
|
482
|
+
? { kind: "unavailable", detail: setup.detail }
|
|
483
|
+
: {
|
|
484
|
+
kind: "ready",
|
|
485
|
+
detail: `${setup.detail}, ${mode.effective ? "shown in this session's tab" : "collapsed while this session is off"}`,
|
|
486
|
+
};
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function bannerText(): string {
|
|
493
|
+
if (banner === undefined) return "not checked yet";
|
|
494
|
+
return banner.kind === "ready" ? banner.detail : `${banner.kind}: ${banner.detail}`;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function configuredDefaultText(): string {
|
|
498
|
+
if (config.kind === "invalid") return `off (invalid settings: ${config.message})`;
|
|
499
|
+
return config.enabled
|
|
500
|
+
? `on (settings "pi-firstmate.enabled")`
|
|
501
|
+
: `off (settings "pi-firstmate.enabled" or omitted)`;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function workerText(classification: WorkerClassification): string {
|
|
505
|
+
switch (classification.kind) {
|
|
506
|
+
case "explicit-worker":
|
|
507
|
+
return "explicit worker (--firstmate-worker); coordinator guidance is never applied in workers";
|
|
508
|
+
case "not-core":
|
|
509
|
+
return "not a Core process";
|
|
510
|
+
case "primary":
|
|
511
|
+
return `primary Core session (${classification.terminalId})`;
|
|
512
|
+
case "worker": {
|
|
513
|
+
const parent = classification.parent ? `, parent=${classification.parent}` : "";
|
|
514
|
+
return `verified Core worker pi.task=${classification.task}, pi.session=${classification.parentSessionId}${parent}; coordinator guidance is never applied in workers`;
|
|
515
|
+
}
|
|
516
|
+
case "unknown":
|
|
517
|
+
return `unknown: ${classification.message}`;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function skillsText(ctx: ExtensionCommandContext): string {
|
|
522
|
+
const names = coordinatorSkillNames();
|
|
523
|
+
if (config.kind === "invalid") return "all discovered skills advertised (settings are invalid)";
|
|
524
|
+
if (config.kind === "valid" && config.coordinatorSkillsProblem !== undefined) {
|
|
525
|
+
return `all discovered skills advertised (invalid setting: ${config.coordinatorSkillsProblem})`;
|
|
526
|
+
}
|
|
527
|
+
if (!resolveMode().effective) return "all discovered skills advertised (coordinator mode is off)";
|
|
528
|
+
if (names === undefined) return "all discovered skills advertised (no filter configured)";
|
|
529
|
+
|
|
530
|
+
const discovered = ctx.getSystemPromptOptions().skills ?? [];
|
|
531
|
+
// Pi never advertises a skill with `disable-model-invocation`, so count that
|
|
532
|
+
// rule too instead of reporting a skill as advertised when it cannot be.
|
|
533
|
+
const advertisable = discovered.filter((skill) => !skill.disableModelInvocation);
|
|
534
|
+
const filtered = applySkillAllowlist(advertisable, names);
|
|
535
|
+
const unknown = applySkillAllowlist(discovered, names).unknown;
|
|
536
|
+
const count =
|
|
537
|
+
discovered.length === 0
|
|
538
|
+
? "no skills are discovered"
|
|
539
|
+
: advertisable.length === 0
|
|
540
|
+
? "no discovered skills can be advertised"
|
|
541
|
+
: filtered.skills.length === 0
|
|
542
|
+
? `none of ${advertisable.length} discovered skills advertised`
|
|
543
|
+
: `${filtered.skills.length} of ${advertisable.length} discovered skills advertised`;
|
|
544
|
+
const unknownText = unknown.length === 0 ? "" : `; not discovered: ${unknown.join(", ")}`;
|
|
545
|
+
return `${count} by "pi-firstmate.coordinatorSkills"${unknownText}`;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function statusText(ctx: ExtensionCommandContext): { text: string; level: "info" | "warning" | "error" } {
|
|
549
|
+
const mode = resolveMode();
|
|
550
|
+
const state = mode.suppressed
|
|
551
|
+
? "off (worker suppression)"
|
|
552
|
+
: mode.uncertain
|
|
553
|
+
? "off (worker check failed)"
|
|
554
|
+
: mode.effective
|
|
555
|
+
? "on"
|
|
556
|
+
: "off";
|
|
557
|
+
const policy = loadPolicy();
|
|
558
|
+
const guidance = mode.effective
|
|
559
|
+
? policy
|
|
560
|
+
? `injected from ${POLICY_DISPLAY_PATH}`
|
|
561
|
+
: `not injected: ${policyError ?? "the skill policy is unavailable"}`
|
|
562
|
+
: "not injected";
|
|
563
|
+
|
|
564
|
+
const lines = [
|
|
565
|
+
`First Mate: ${state}`,
|
|
566
|
+
`Configured default: ${configuredDefaultText()}`,
|
|
567
|
+
`Session override: ${override === null ? "none" : override ? "on" : "off"}`,
|
|
568
|
+
`Worker: ${workerText(mode.worker)}`,
|
|
569
|
+
`Tools: ${mode.effective ? `restricted to ${COORDINATOR_TOOLS_DESCRIPTION}` : "normal"}`,
|
|
570
|
+
`Skills: ${skillsText(ctx)}`,
|
|
571
|
+
`Banner: ${bannerText()}`,
|
|
572
|
+
`Guidance: ${guidance}`,
|
|
573
|
+
];
|
|
574
|
+
|
|
575
|
+
const bannerProblem = config.kind === "valid" && config.bannerProblem !== undefined;
|
|
576
|
+
const skillsProblem = config.kind === "valid" && config.coordinatorSkillsProblem !== undefined;
|
|
577
|
+
const level =
|
|
578
|
+
config.kind === "invalid"
|
|
579
|
+
? "error"
|
|
580
|
+
: bannerProblem || skillsProblem || mode.suppressed || mode.uncertain || (mode.effective && !policy)
|
|
581
|
+
? "warning"
|
|
582
|
+
: "info";
|
|
583
|
+
return { text: lines.join("\n"), level };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
pi.registerCommand(COMMAND_NAME, {
|
|
587
|
+
description: "Turn First Mate coordinator mode on or off, or report its status",
|
|
588
|
+
getArgumentCompletions: (prefix) => {
|
|
589
|
+
const trimmed = prefix.trim();
|
|
590
|
+
if (trimmed.includes(" ")) return null;
|
|
591
|
+
const matches = ["on", "off", "status", "default"].filter((value) => value.startsWith(trimmed));
|
|
592
|
+
return matches.length > 0 ? matches.map((value) => ({ value, label: value })) : null;
|
|
593
|
+
},
|
|
594
|
+
handler: async (args, ctx) => {
|
|
595
|
+
refreshConfig();
|
|
596
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
597
|
+
const action = parts[0]?.toLowerCase();
|
|
598
|
+
|
|
599
|
+
if (action === undefined || action === "status") {
|
|
600
|
+
if (parts.length > 1) {
|
|
601
|
+
report(ctx, USAGE, "warning");
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
await ensureWorkerKnown();
|
|
605
|
+
syncToolGate(ctx);
|
|
606
|
+
syncBanner(ctx);
|
|
607
|
+
const status = statusText(ctx);
|
|
608
|
+
report(ctx, status.text, status.level);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
if (parts.length > 1 || (action !== "on" && action !== "off" && action !== "default")) {
|
|
613
|
+
report(ctx, USAGE, "warning");
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
await ensureWorkerKnown();
|
|
618
|
+
|
|
619
|
+
if (action === "on") {
|
|
620
|
+
saveOverride(true, ctx);
|
|
621
|
+
syncToolGate(ctx);
|
|
622
|
+
syncIndicator(ctx);
|
|
623
|
+
syncBanner(ctx);
|
|
624
|
+
const mode = resolveMode();
|
|
625
|
+
if (mode.worker.kind === "explicit-worker") {
|
|
626
|
+
report(
|
|
627
|
+
ctx,
|
|
628
|
+
"First Mate override saved, but coordinator guidance is suppressed by --firstmate-worker. Workers follow their assignment and ordinary project and host instructions.",
|
|
629
|
+
"warning",
|
|
630
|
+
);
|
|
631
|
+
} else if (mode.worker.kind === "worker") {
|
|
632
|
+
report(
|
|
633
|
+
ctx,
|
|
634
|
+
`First Mate override saved, but coordinator guidance is suppressed in this Core worker session (pi.task=${mode.worker.task}). Workers follow their assignment and ordinary project and host instructions.`,
|
|
635
|
+
"warning",
|
|
636
|
+
);
|
|
637
|
+
} else if (mode.worker.kind === "unknown") {
|
|
638
|
+
report(
|
|
639
|
+
ctx,
|
|
640
|
+
`First Mate is on by explicit session override. The Core worker check failed (${mode.worker.message}), so the configured default is not applied to a possible worker; your explicit override still applies.`,
|
|
641
|
+
"warning",
|
|
642
|
+
);
|
|
643
|
+
} else if (!loadPolicy()) {
|
|
644
|
+
report(
|
|
645
|
+
ctx,
|
|
646
|
+
`First Mate is on for this session, but its policy could not be read from ${POLICY_DISPLAY_PATH}: ${policyError}. No coordinator guidance is injected.`,
|
|
647
|
+
"error",
|
|
648
|
+
);
|
|
649
|
+
} else {
|
|
650
|
+
report(
|
|
651
|
+
ctx,
|
|
652
|
+
`First Mate is on for this session. ${SKILL_REMINDER} Conversation, decisions and quick inspection stay local; project execution goes to workers.`,
|
|
653
|
+
"info",
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
if (action === "off") {
|
|
660
|
+
saveOverride(false, ctx);
|
|
661
|
+
syncToolGate(ctx);
|
|
662
|
+
offRequestPrepared = false;
|
|
663
|
+
syncIndicator(ctx);
|
|
664
|
+
syncBanner(ctx);
|
|
665
|
+
report(
|
|
666
|
+
ctx,
|
|
667
|
+
"First Mate is off for this session. Earlier coordinator guidance is superseded; ordinary project and host instructions apply.",
|
|
668
|
+
"info",
|
|
669
|
+
);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
saveOverride(null, ctx);
|
|
674
|
+
syncToolGate(ctx);
|
|
675
|
+
syncIndicator(ctx);
|
|
676
|
+
syncBanner(ctx);
|
|
677
|
+
const mode = resolveMode();
|
|
678
|
+
const state = mode.suppressed
|
|
679
|
+
? "off because this is a verified worker session"
|
|
680
|
+
: mode.uncertain
|
|
681
|
+
? "off because the Core worker check failed"
|
|
682
|
+
: mode.effective
|
|
683
|
+
? "on"
|
|
684
|
+
: "off";
|
|
685
|
+
report(ctx, `First Mate now follows the configured default: ${state}.`, mode.suppressed || mode.uncertain ? "warning" : "info");
|
|
686
|
+
},
|
|
687
|
+
});
|
|
688
|
+
|
|
689
|
+
pi.registerCommand(CLOSE_COMMAND_NAME, {
|
|
690
|
+
description: "Record the worker close retrospective before final handoff",
|
|
691
|
+
handler: async (args, ctx) => {
|
|
692
|
+
refreshConfig();
|
|
693
|
+
await ensureWorkerKnown();
|
|
694
|
+
|
|
695
|
+
if (args.trim() !== "") {
|
|
696
|
+
report(ctx, CLOSE_USAGE, "warning");
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
const mode = resolveMode();
|
|
701
|
+
if (mode.effective) {
|
|
702
|
+
report(ctx, CLOSE_COORDINATOR_NOTE, "warning");
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
const run = closeRunText(ctx, mode);
|
|
707
|
+
if ("error" in run) {
|
|
708
|
+
report(ctx, run.error, "error");
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
pi.sendUserMessage(run.text, { deliverAs: "followUp" });
|
|
713
|
+
report(
|
|
714
|
+
ctx,
|
|
715
|
+
`Close retrospective started for session ${ctx.sessionManager.getSessionId()}. It records findings only: no skills, code, tasks or terminals are changed.`,
|
|
716
|
+
"info",
|
|
717
|
+
);
|
|
718
|
+
},
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
// A coordinator triggers this lifecycle with the backend's send tool. The
|
|
722
|
+
// wrapped request would otherwise reach the model as plain text and be
|
|
723
|
+
// improvised, so replace it with the same workflow the command starts.
|
|
724
|
+
pi.on("input", async (event, ctx) => {
|
|
725
|
+
if (!CLOSE_INPUT_REQUEST.test(event.text)) return undefined;
|
|
726
|
+
refreshConfig();
|
|
727
|
+
await ensureWorkerKnown();
|
|
728
|
+
const mode = resolveMode();
|
|
729
|
+
if (mode.effective) {
|
|
730
|
+
report(ctx, CLOSE_COORDINATOR_NOTE, "warning");
|
|
731
|
+
return { action: "handled" };
|
|
732
|
+
}
|
|
733
|
+
const run = closeRunText(ctx, mode);
|
|
734
|
+
if ("error" in run) {
|
|
735
|
+
report(ctx, run.error, "error");
|
|
736
|
+
return { action: "handled" };
|
|
737
|
+
}
|
|
738
|
+
return { action: "transform", text: run.text };
|
|
739
|
+
});
|
|
740
|
+
|
|
741
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
742
|
+
sessionCtx = ctx;
|
|
743
|
+
refreshConfig();
|
|
744
|
+
refreshSessionState(ctx);
|
|
745
|
+
worker = await classifyWorker();
|
|
746
|
+
loadPolicy();
|
|
747
|
+
|
|
748
|
+
const mode = resolveMode();
|
|
749
|
+
syncIndicator(ctx);
|
|
750
|
+
offRequestPrepared = false;
|
|
751
|
+
syncToolGate(ctx);
|
|
752
|
+
syncBanner(ctx);
|
|
753
|
+
|
|
754
|
+
if (config.kind === "invalid") {
|
|
755
|
+
report(
|
|
756
|
+
ctx,
|
|
757
|
+
`First Mate settings problem: ${config.message}. The configured default is treated as off; fix settings.json or use /firstmate on explicitly.`,
|
|
758
|
+
"error",
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
if (config.kind === "valid" && config.bannerProblem !== undefined) {
|
|
762
|
+
report(
|
|
763
|
+
ctx,
|
|
764
|
+
`First Mate banner setting problem: ${config.bannerProblem}. The banner is off; coordinator mode is unaffected.`,
|
|
765
|
+
"warning",
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
if (config.kind === "valid" && config.coordinatorSkillsProblem !== undefined) {
|
|
769
|
+
report(
|
|
770
|
+
ctx,
|
|
771
|
+
`First Mate skills setting problem: ${config.coordinatorSkillsProblem}. Skill advertisement stays unfiltered; coordinator mode is unaffected.`,
|
|
772
|
+
"warning",
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
if (mode.uncertain && mode.worker.kind === "unknown") {
|
|
776
|
+
report(
|
|
777
|
+
ctx,
|
|
778
|
+
`First Mate could not verify whether this Core session is a task worker (${mode.worker.message}). Coordinator guidance from the configured default is not applied; use /firstmate on if this is a coordinator session.`,
|
|
779
|
+
"warning",
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
if (mode.effective && !loadPolicy()) {
|
|
783
|
+
report(
|
|
784
|
+
ctx,
|
|
785
|
+
`First Mate is on, but its policy could not be read from ${POLICY_DISPLAY_PATH}: ${policyError}. No coordinator guidance will be injected.`,
|
|
786
|
+
"error",
|
|
787
|
+
);
|
|
788
|
+
} else if (mode.effective) {
|
|
789
|
+
report(
|
|
790
|
+
ctx,
|
|
791
|
+
`First Mate is on for this session. ${SKILL_REMINDER} Conversation, decisions and quick inspection stay local; project execution goes to workers.`,
|
|
792
|
+
"info",
|
|
793
|
+
);
|
|
794
|
+
}
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
798
|
+
syncToolGate(ctx);
|
|
799
|
+
const mode = resolveMode();
|
|
800
|
+
offRequestPrepared = !mode.effective && savedActiveTools !== null;
|
|
801
|
+
const options = event.systemPromptOptions;
|
|
802
|
+
|
|
803
|
+
if (mode.effective) {
|
|
804
|
+
applyCoordinatorSkills(options, ctx);
|
|
805
|
+
const policy = loadPolicy();
|
|
806
|
+
if (policy !== undefined) {
|
|
807
|
+
options.sections[SECTION_KEY] = policy;
|
|
808
|
+
guidanceEvidence = true;
|
|
809
|
+
if (!options.promptGuidelines.includes(ON_GUIDELINE)) {
|
|
810
|
+
options.promptGuidelines.push(ON_GUIDELINE);
|
|
811
|
+
}
|
|
812
|
+
} else {
|
|
813
|
+
delete options.sections[SECTION_KEY];
|
|
814
|
+
}
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
delete options.sections[SECTION_KEY];
|
|
819
|
+
if (guidanceEvidence && !options.promptGuidelines.includes(OFF_GUIDELINE)) {
|
|
820
|
+
options.promptGuidelines.push(OFF_GUIDELINE);
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
|
|
824
|
+
// `turn_end` runs after a turn's tool calls and before Pi snapshots the next
|
|
825
|
+
// request's tool declarations in `prepareNextTurnWithContext`. Hiding here
|
|
826
|
+
// covers direct tools registered during a multi-turn run, such as a slow MCP
|
|
827
|
+
// connection that registers after `before_agent_start`.
|
|
828
|
+
pi.on("turn_end", (event, ctx) => {
|
|
829
|
+
syncToolGate(ctx);
|
|
830
|
+
const completed =
|
|
831
|
+
event.message.role === "assistant" &&
|
|
832
|
+
event.message.stopReason !== "error" &&
|
|
833
|
+
event.message.stopReason !== "aborted";
|
|
834
|
+
if (!resolveMode().effective && offRequestPrepared && completed) {
|
|
835
|
+
clearRestoredToolBaseline(ctx);
|
|
836
|
+
offRequestPrepared = false;
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
|
|
840
|
+
pi.on("tool_call", (event) => {
|
|
841
|
+
if (!resolveMode().effective) return undefined;
|
|
842
|
+
if (toolGate.permits(event.toolName)) return undefined;
|
|
843
|
+
return { block: true, reason: toolGate.reason(event.toolName) };
|
|
844
|
+
});
|
|
845
|
+
|
|
846
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
847
|
+
sessionCtx = undefined;
|
|
848
|
+
publishCoordinatorMode();
|
|
849
|
+
const coordinatorOnly = toolGate.coordinatorOnlyNames();
|
|
850
|
+
if (savedActiveTools !== null) {
|
|
851
|
+
try {
|
|
852
|
+
pi.setActiveTools([...new Set([...savedActiveTools, ...pi.getActiveTools()])].filter((name) => !coordinatorOnly.has(name)));
|
|
853
|
+
} catch {
|
|
854
|
+
// Shutdown cleanup is best-effort.
|
|
855
|
+
}
|
|
856
|
+
savedActiveTools = null;
|
|
857
|
+
savedBaselineKey = null;
|
|
858
|
+
}
|
|
859
|
+
offRequestPrepared = false;
|
|
860
|
+
sessionCtx = undefined;
|
|
861
|
+
override = null;
|
|
862
|
+
guidanceEvidence = false;
|
|
863
|
+
worker = undefined;
|
|
864
|
+
skillWarningKey = null;
|
|
865
|
+
try {
|
|
866
|
+
clearBannerState(herdrAppHome(), ctx.sessionManager.getSessionId());
|
|
867
|
+
} catch {
|
|
868
|
+
// Shutdown is best-effort; a stale file is hidden by the mod's live check.
|
|
869
|
+
}
|
|
870
|
+
banner = undefined;
|
|
871
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
872
|
+
});
|
|
873
|
+
|
|
874
|
+
pi.events.on(SCHEDULER_TOOLS_CHANGED_EVENT, () => {
|
|
875
|
+
if (sessionCtx) syncToolGate(sessionCtx);
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
// Ask publishes this event synchronously after restoring the tool list it
|
|
879
|
+
// captured before its read-only mode. Running the full gate (not only the
|
|
880
|
+
// hide step) lets coordinator mode record that restored list as its baseline
|
|
881
|
+
// before narrowing again, and lets a deferred off-mode restore finish.
|
|
882
|
+
pi.events.on(ASK_GUARD_RELEASED_EVENT, () => {
|
|
883
|
+
if (!sessionCtx) return;
|
|
884
|
+
syncToolGate(sessionCtx);
|
|
885
|
+
});
|
|
886
|
+
}
|