@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.10

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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1444 -2
  3. package/dist/chunks/chunk-MSGGFB5Q.ts +6755 -0
  4. package/dist/chunks/chunk-MSGGFB5Q.ts.map +7 -0
  5. package/dist/chunks/conversation-viewer-A7AMRDVY.ts +15 -0
  6. package/dist/chunks/conversation-viewer-A7AMRDVY.ts.map +7 -0
  7. package/dist/index.ts +9874 -0
  8. package/dist/index.ts.map +7 -0
  9. package/package.json +82 -4
  10. package/src/abortable.ts +43 -0
  11. package/src/agent-color.ts +161 -0
  12. package/src/agent-file-toggle.ts +298 -0
  13. package/src/agent-manager.ts +2431 -0
  14. package/src/agent-runner.ts +1703 -0
  15. package/src/agent-source-badge.ts +75 -0
  16. package/src/agent-types.ts +346 -0
  17. package/src/child-context.ts +33 -0
  18. package/src/clock.ts +25 -0
  19. package/src/completion-outbox.ts +144 -0
  20. package/src/context.ts +58 -0
  21. package/src/cross-extension-rpc.ts +200 -0
  22. package/src/custom-agents.ts +441 -0
  23. package/src/default-agents.ts +126 -0
  24. package/src/detached-results.ts +150 -0
  25. package/src/enabled-models.ts +181 -0
  26. package/src/enterprise-local.ts +67 -0
  27. package/src/env.ts +33 -0
  28. package/src/error-message.ts +11 -0
  29. package/src/git-path.ts +66 -0
  30. package/src/group-join.ts +142 -0
  31. package/src/home-paths.ts +27 -0
  32. package/src/index.ts +5047 -0
  33. package/src/invocation-config.ts +158 -0
  34. package/src/memory.ts +179 -0
  35. package/src/mention-clone.ts +200 -0
  36. package/src/mention.ts +141 -0
  37. package/src/model-call.ts +83 -0
  38. package/src/model-resolver.ts +333 -0
  39. package/src/model-scope.ts +71 -0
  40. package/src/model-selection.ts +170 -0
  41. package/src/model-tiers.ts +176 -0
  42. package/src/nested-tools.ts +512 -0
  43. package/src/notification-result.ts +118 -0
  44. package/src/output-file.ts +186 -0
  45. package/src/package-resources.ts +639 -0
  46. package/src/plan-mode-children.ts +176 -0
  47. package/src/process-budget.ts +346 -0
  48. package/src/prompts.ts +161 -0
  49. package/src/quota-admission.ts +121 -0
  50. package/src/resource-loader.ts +65 -0
  51. package/src/schedule-store.ts +153 -0
  52. package/src/schedule.ts +514 -0
  53. package/src/settings.ts +851 -0
  54. package/src/skill-loader.ts +288 -0
  55. package/src/stale-ctx.ts +16 -0
  56. package/src/startup-error.ts +29 -0
  57. package/src/status-note.ts +113 -0
  58. package/src/structured-output.ts +130 -0
  59. package/src/types.ts +487 -0
  60. package/src/ui/agent-mention.ts +219 -0
  61. package/src/ui/agent-row.ts +245 -0
  62. package/src/ui/agent-widget.ts +722 -0
  63. package/src/ui/conversation-viewer.ts +837 -0
  64. package/src/ui/fallback-flag.ts +114 -0
  65. package/src/ui/fleet-list.ts +1020 -0
  66. package/src/ui/fleet-state.ts +154 -0
  67. package/src/ui/notification-view.ts +139 -0
  68. package/src/ui/schedule-menu.ts +105 -0
  69. package/src/ui/select-item.ts +45 -0
  70. package/src/ui/viewer-keys.ts +39 -0
  71. package/src/ui/workflow-card.ts +459 -0
  72. package/src/ui/workflow-dialog.ts +1138 -0
  73. package/src/ui/workflow-menu.ts +193 -0
  74. package/src/usage.ts +167 -0
  75. package/src/workflow/collisions.ts +123 -0
  76. package/src/workflow/entry.ts +47 -0
  77. package/src/workflow/host.ts +398 -0
  78. package/src/workflow/journal.ts +176 -0
  79. package/src/workflow/json-schema.ts +129 -0
  80. package/src/workflow/meta.ts +329 -0
  81. package/src/workflow/progress.ts +554 -0
  82. package/src/workflow/runtime.ts +1249 -0
  83. package/src/workflow/saved.ts +259 -0
  84. package/src/workflow/task.ts +317 -0
  85. package/src/workflow/tool-description.ts +200 -0
  86. package/src/workflow/worker-source.ts +903 -0
  87. package/src/worktree.ts +520 -0
  88. package/src/xml.ts +13 -0
@@ -0,0 +1,121 @@
1
+ /**
2
+ * quota-admission.ts — ask a subscription router whether a dispatch may start.
3
+ *
4
+ * Quota tracking lives in a separate extension (nredd/pi-subscription-router),
5
+ * reached over `pi.events` with the same envelope as `cross-extension-rpc.ts`:
6
+ * emit `router:rpc:admit` `{ requestId, model }`, reply on
7
+ * `router:rpc:admit:reply:<requestId>` as `{ success, data?: { ok, resolvedModel?, resetAt?, wait? } }` (`resolvedModel` labels the admitted physical model).
8
+ *
9
+ * Admission fails open. No router installed, a slow router, a malformed reply
10
+ * or a router error all admit the dispatch: quota is advisory here, and the
11
+ * router still routes (or fails) each request inside the child.
12
+ */
13
+
14
+ import { nanoid } from "nanoid";
15
+ import { type Clock, realClock } from "./clock.js";
16
+ import type { TierAdmission } from "./model-tiers.js";
17
+
18
+ export const ADMIT_CHANNEL = "router:rpc:admit";
19
+
20
+ /**
21
+ * How long to wait for a reply. The router answers from cached state within
22
+ * the same macrotask, so this only bounds the cost when no router is installed.
23
+ */
24
+ const ADMIT_TIMEOUT_MS = 100;
25
+
26
+ /** Minimal `pi.events` surface. */
27
+ export interface AdmissionEvents {
28
+ emit(channel: string, data: unknown): void;
29
+ on(channel: string, handler: (data: unknown) => void): () => void;
30
+ }
31
+
32
+ /** A dispatch the router refused, with the earliest known reset (epoch ms). */
33
+ export interface QuotaBlock {
34
+ model: string;
35
+ resetAt?: number;
36
+ /**
37
+ * False when the router's exhaustion policy says fail now instead of parking.
38
+ * Absent (an older router) means the dispatch may park until `resetAt`.
39
+ */
40
+ wait?: boolean;
41
+ }
42
+
43
+ /** Whether a refused background dispatch may be parked until the block's reset. */
44
+ export function mayPark(block: QuotaBlock): block is QuotaBlock & { resetAt: number } {
45
+ return block.resetAt !== undefined && block.wait !== false;
46
+ }
47
+
48
+ /** `provider/id` for a model, the key the router expects. */
49
+ export function modelRef(model: { provider: string; id: string }): string {
50
+ return `${model.provider}/${model.id}`;
51
+ }
52
+
53
+ /** Resolve to the block when the router refuses `model`, else undefined. */
54
+ export async function checkAdmission(
55
+ events: AdmissionEvents,
56
+ model: string,
57
+ timeoutMs = ADMIT_TIMEOUT_MS,
58
+ clock: Clock = realClock,
59
+ signal?: AbortSignal,
60
+ ): Promise<QuotaBlock | undefined> {
61
+ return (await admissionOutcome(events, model, timeoutMs, clock, signal)).block;
62
+ }
63
+
64
+ /** Retain the physical admission label and whether the router supplied a signal. */
65
+ export function admissionOutcome(
66
+ events: AdmissionEvents,
67
+ model: string,
68
+ timeoutMs = ADMIT_TIMEOUT_MS,
69
+ clock: Clock = realClock,
70
+ signal?: AbortSignal,
71
+ ): Promise<TierAdmission> {
72
+ if (signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
73
+ const requestId = nanoid();
74
+ return new Promise((resolve, reject) => {
75
+ // Every step is idempotent and a promise settles once, so no `done` latch is needed.
76
+ const cleanup = () => {
77
+ timer.cancel();
78
+ unsubscribe();
79
+ signal?.removeEventListener("abort", abort);
80
+ };
81
+ const abort = () => {
82
+ cleanup();
83
+ reject(new DOMException("Admission cancelled", "AbortError"));
84
+ };
85
+ const finish = (outcome: TierAdmission) => {
86
+ cleanup();
87
+ resolve(outcome);
88
+ };
89
+ const unsubscribe = events.on(`${ADMIT_CHANNEL}:reply:${requestId}`, raw => {
90
+ const reply = raw as { success?: unknown; data?: { ok?: unknown; resolvedModel?: unknown; resetAt?: unknown; wait?: unknown } } | undefined;
91
+ if (reply?.success !== true || typeof reply.data?.ok !== "boolean") return finish({ quotaSignal: false });
92
+ if (reply.data.ok) return finish({ quotaSignal: true, resolvedModel: typeof reply.data.resolvedModel === "string" ? reply.data.resolvedModel : undefined });
93
+ const resetAt = reply.data.resetAt;
94
+ const wait = reply.data.wait;
95
+ finish({ quotaSignal: true, block: {
96
+ model,
97
+ resetAt: typeof resetAt === "number" && Number.isFinite(resetAt) ? resetAt : undefined,
98
+ ...(typeof wait === "boolean" ? { wait } : {}),
99
+ } });
100
+ });
101
+ const timer = clock.setTimeout(() => finish({ quotaSignal: false }), timeoutMs);
102
+ signal?.addEventListener("abort", abort, { once: true });
103
+ events.emit(ADMIT_CHANNEL, { requestId, model });
104
+ });
105
+ }
106
+
107
+ /** One-line reason for a refused dispatch. */
108
+ export function describeBlock(block: QuotaBlock): string {
109
+ const when = block.resetAt === undefined ? "an unknown time" : new Date(block.resetAt).toISOString();
110
+ return `Subscription quota for ${block.model} is exhausted; it resets at ${when}.`;
111
+ }
112
+
113
+ /** Delay past a reported reset before a parked dispatch starts, so usage has refilled. */
114
+ export const QUOTA_RESTART_GRACE_MS = 60_000;
115
+
116
+ /**
117
+ * Delay before re-admitting a parked dispatch whose reset passed while pi was
118
+ * closed. The router warms its usage cache on session_start; asking before that
119
+ * finishes would always fail open.
120
+ */
121
+ export const PARKED_RESUME_DELAY_MS = 10_000;
@@ -0,0 +1,65 @@
1
+ /** Normalize explicit settings paths before Pi's real package manager resolves them. */
2
+ import { DefaultPackageManager, DefaultResourceLoader, SettingsManager } from "@earendil-works/pi-coding-agent";
3
+ import { normalizeHomePath } from "./home-paths.js";
4
+
5
+ type ResourceLoaderOptions = ConstructorParameters<typeof DefaultResourceLoader>[0];
6
+ type ResourceSettings = ReturnType<SettingsManager["getGlobalSettings"]>;
7
+
8
+ const RESOURCE_FIELDS = ["extensions", "skills", "prompts", "themes"] as const;
9
+
10
+ /** Keep filter modifiers and non-home paths intact; only replace leading home references. */
11
+ function expandSetting(entry: string, homeDir: string, modifiers = true): string {
12
+ const prefix = modifiers && /^[!+-]/.test(entry) ? entry[0] : "";
13
+ const path = entry.slice(prefix.length);
14
+ const trimmed = path.trim();
15
+ if (trimmed !== "~" && !trimmed.startsWith("~/") && !(process.platform === "win32" && trimmed.startsWith("~\\"))) return entry;
16
+ return prefix + normalizeHomePath(trimmed, homeDir);
17
+ }
18
+
19
+ /** Return copies so loading resources never changes persisted settings or their source objects. */
20
+ export function normalizeResourceSettings(settings: ResourceSettings, homeDir: string): ResourceSettings {
21
+ const normalized = { ...settings };
22
+ for (const field of RESOURCE_FIELDS) {
23
+ if (settings[field]) normalized[field] = settings[field].map(entry => expandSetting(entry, homeDir));
24
+ }
25
+ if (settings.packages) {
26
+ normalized.packages = settings.packages.map(pkg => {
27
+ if (typeof pkg === "string") return expandSetting(pkg, homeDir, false);
28
+ const copy = { ...pkg, source: expandSetting(pkg.source, homeDir, false) };
29
+ for (const field of RESOURCE_FIELDS) {
30
+ if (pkg[field]) copy[field] = pkg[field].map(entry => expandSetting(entry, homeDir));
31
+ }
32
+ return copy;
33
+ });
34
+ }
35
+ return normalized;
36
+ }
37
+
38
+ type PackageManagerOptions = ConstructorParameters<typeof DefaultPackageManager>[0];
39
+
40
+ /** Wrap settings readers once so Pi receives injected-home resource paths. */
41
+ function normalizeHomeResourceSettings(settingsManager: SettingsManager, homeDir: string): SettingsManager {
42
+ const globalSettings = settingsManager.getGlobalSettings.bind(settingsManager);
43
+ const projectSettings = settingsManager.getProjectSettings.bind(settingsManager);
44
+ // Wrap the public readers, not a cached snapshot: reload and project-trust
45
+ // decisions continue to be owned by Pi, and every read receives fresh copies.
46
+ Object.assign(settingsManager, {
47
+ getGlobalSettings: () => normalizeResourceSettings(globalSettings(), homeDir),
48
+ getProjectSettings: () => normalizeResourceSettings(projectSettings(), homeDir),
49
+ });
50
+ return settingsManager;
51
+ }
52
+
53
+ /** Build Pi's package manager with injected-home settings normalization. */
54
+ export function createHomePackageManager(options: PackageManagerOptions, homeDir?: string): DefaultPackageManager {
55
+ if (homeDir === undefined) return new DefaultPackageManager(options);
56
+ // `homeDir` also redirects Pi's automatic `<home>/.agents/skills` root (nredd/pi#13).
57
+ return new DefaultPackageManager({ ...options, homeDir, settingsManager: normalizeHomeResourceSettings(options.settingsManager, homeDir) });
58
+ }
59
+
60
+ /** Use the real loader/manager while preventing ambient-home expansion of explicit settings. */
61
+ export function createHomeResourceLoader(options: ResourceLoaderOptions, homeDir?: string): DefaultResourceLoader {
62
+ if (homeDir === undefined) return new DefaultResourceLoader(options);
63
+ const settingsManager = options.settingsManager ?? SettingsManager.create(options.cwd, options.agentDir);
64
+ return new DefaultResourceLoader({ ...options, homeDir, settingsManager: normalizeHomeResourceSettings(settingsManager, homeDir) });
65
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * schedule-store.ts — File-backed store for scheduled subagents.
3
+ *
4
+ * Session-scoped: each pi session owns its own schedules at
5
+ * `<cwd>/.pi/subagent-schedules/<sessionId>.json`. `/new` starts a fresh
6
+ * empty store; `/resume` reloads.
7
+ *
8
+ * Concurrency model lifted from pi-chonky-tasks/src/task-store.ts: every
9
+ * mutation acquires a PID-based exclusion lock, re-reads the latest state
10
+ * from disk, applies the change, atomic-writes via temp+rename, releases.
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import type { ScheduledSubagent, ScheduleStoreData } from "./types.js";
16
+
17
+ const LOCK_RETRY_MS = 50;
18
+ const LOCK_MAX_RETRIES = 100;
19
+
20
+ function isProcessRunning(pid: number): boolean {
21
+ try { process.kill(pid, 0); return true; } catch { return false; }
22
+ }
23
+
24
+ function acquireLock(lockPath: string): void {
25
+ for (let i = 0; i < LOCK_MAX_RETRIES; i++) {
26
+ try {
27
+ writeFileSync(lockPath, `${process.pid}`, { flag: "wx" });
28
+ return;
29
+ } catch (e: any) {
30
+ if (e.code === "EEXIST") {
31
+ try {
32
+ const pid = parseInt(readFileSync(lockPath, "utf-8"), 10);
33
+ if (pid && !isProcessRunning(pid)) {
34
+ unlinkSync(lockPath);
35
+ continue;
36
+ }
37
+ } catch { /* ignore — try again */ }
38
+ const start = Date.now();
39
+ while (Date.now() - start < LOCK_RETRY_MS) { /* busy wait */ }
40
+ continue;
41
+ }
42
+ throw e;
43
+ }
44
+ }
45
+ throw new Error(`Failed to acquire schedule lock: ${lockPath}`);
46
+ }
47
+
48
+ function releaseLock(lockPath: string): void {
49
+ try { unlinkSync(lockPath); } catch { /* ignore */ }
50
+ }
51
+
52
+ /** Resolve the storage path for a session-scoped store. */
53
+ export function resolveStorePath(cwd: string, sessionId: string): string {
54
+ return join(cwd, ".pi", "subagent-schedules", `${sessionId}.json`);
55
+ }
56
+
57
+ export class ScheduleStore {
58
+ private filePath: string;
59
+ private lockPath: string;
60
+ private jobs = new Map<string, ScheduledSubagent>();
61
+
62
+ constructor(filePath: string) {
63
+ this.filePath = filePath;
64
+ this.lockPath = filePath + ".lock";
65
+ this.load();
66
+ }
67
+
68
+ /** Create the backing directory lazily — only when we're about to persist. */
69
+ private ensureDir(): void {
70
+ mkdirSync(dirname(this.filePath), { recursive: true });
71
+ }
72
+
73
+ /** Load from disk into the in-memory cache. Silent on parse errors. */
74
+ private load(): void {
75
+ if (!existsSync(this.filePath)) return;
76
+ try {
77
+ const data: ScheduleStoreData = JSON.parse(readFileSync(this.filePath, "utf-8"));
78
+ this.jobs.clear();
79
+ for (const j of data.jobs ?? []) this.jobs.set(j.id, j);
80
+ } catch { /* corrupt — start fresh, next save rewrites */ }
81
+ }
82
+
83
+ /** Atomic write via temp file + rename (POSIX-atomic). */
84
+ private save(): void {
85
+ const data: ScheduleStoreData = { version: 1, jobs: [...this.jobs.values()] };
86
+ const tmp = this.filePath + ".tmp";
87
+ writeFileSync(tmp, JSON.stringify(data, null, 2));
88
+ renameSync(tmp, this.filePath);
89
+ }
90
+
91
+ /** Acquire lock → reload → mutate → save → release. */
92
+ private withLock<T>(fn: () => T): T {
93
+ this.ensureDir();
94
+ acquireLock(this.lockPath);
95
+ try {
96
+ this.load();
97
+ const result = fn();
98
+ this.save();
99
+ return result;
100
+ } finally {
101
+ releaseLock(this.lockPath);
102
+ }
103
+ }
104
+
105
+ /** Read-only — returns a snapshot of the in-memory cache. */
106
+ list(): ScheduledSubagent[] {
107
+ return [...this.jobs.values()];
108
+ }
109
+
110
+ /** Read-only check — uses the cache. */
111
+ hasName(name: string, exceptId?: string): boolean {
112
+ for (const j of this.jobs.values()) {
113
+ if (j.id !== exceptId && j.name === name) return true;
114
+ }
115
+ return false;
116
+ }
117
+
118
+ get(id: string): ScheduledSubagent | undefined {
119
+ return this.jobs.get(id);
120
+ }
121
+
122
+ add(job: ScheduledSubagent): void {
123
+ this.withLock(() => {
124
+ this.jobs.set(job.id, job);
125
+ });
126
+ }
127
+
128
+ update(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined {
129
+ // No-op fast path — an unknown id changes nothing, so don't lock or touch
130
+ // disk (which would otherwise lazily create the backing directory).
131
+ if (!this.jobs.has(id)) return undefined;
132
+ return this.withLock(() => {
133
+ const existing = this.jobs.get(id);
134
+ if (!existing) return undefined;
135
+ const updated = { ...existing, ...patch };
136
+ this.jobs.set(id, updated);
137
+ return updated;
138
+ });
139
+ }
140
+
141
+ remove(id: string): boolean {
142
+ // No-op fast path — see update().
143
+ if (!this.jobs.has(id)) return false;
144
+ return this.withLock(() => this.jobs.delete(id));
145
+ }
146
+
147
+ /** Delete the backing file (used when no jobs remain, optional cleanup). */
148
+ deleteFileIfEmpty(): void {
149
+ if (this.jobs.size === 0 && existsSync(this.filePath)) {
150
+ try { unlinkSync(this.filePath); } catch { /* ignore */ }
151
+ }
152
+ }
153
+ }