pi-crew 0.1.41 → 0.1.44

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 (191) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +51 -0
  3. package/agents/analyst.md +11 -11
  4. package/agents/critic.md +11 -11
  5. package/agents/executor.md +11 -11
  6. package/agents/explorer.md +11 -11
  7. package/agents/planner.md +11 -11
  8. package/agents/reviewer.md +11 -11
  9. package/agents/security-reviewer.md +11 -11
  10. package/agents/test-engineer.md +11 -11
  11. package/agents/verifier.md +11 -11
  12. package/agents/writer.md +11 -11
  13. package/docs/refactor-tasks-phase3.md +394 -394
  14. package/docs/refactor-tasks-phase4.md +564 -564
  15. package/docs/refactor-tasks-phase5.md +402 -402
  16. package/docs/refactor-tasks-phase6.md +662 -662
  17. package/docs/research-extension-examples.md +297 -297
  18. package/docs/research-extension-system.md +324 -324
  19. package/docs/research-optimization-plan.md +548 -548
  20. package/docs/research-phase10-distillation.md +199 -0
  21. package/docs/research-phase11-distillation.md +201 -0
  22. package/docs/research-pi-coding-agent.md +357 -357
  23. package/docs/research-source-pi-crew-reference.md +174 -174
  24. package/docs/runtime-flow.md +148 -148
  25. package/docs/source-runtime-refactor-map.md +83 -83
  26. package/index.ts +6 -6
  27. package/package.json +1 -1
  28. package/src/agents/agent-serializer.ts +34 -34
  29. package/src/agents/discover-agents.ts +5 -4
  30. package/src/config/config.ts +28 -4
  31. package/src/extension/cross-extension-rpc.ts +82 -82
  32. package/src/extension/management.ts +37 -8
  33. package/src/extension/notification-router.ts +2 -2
  34. package/src/extension/register.ts +130 -8
  35. package/src/extension/registration/commands.ts +11 -9
  36. package/src/extension/registration/compaction-guard.ts +125 -125
  37. package/src/extension/registration/subagent-tools.ts +28 -19
  38. package/src/extension/registration/team-tool.ts +2 -1
  39. package/src/extension/result-watcher.ts +4 -4
  40. package/src/extension/run-bundle-schema.ts +8 -4
  41. package/src/extension/run-import.ts +4 -0
  42. package/src/extension/run-index.ts +23 -1
  43. package/src/extension/run-maintenance.ts +43 -24
  44. package/src/extension/team-tool/api.ts +2 -2
  45. package/src/extension/team-tool/cancel.ts +76 -4
  46. package/src/extension/team-tool/context.ts +1 -0
  47. package/src/extension/team-tool/doctor.ts +8 -1
  48. package/src/extension/team-tool/handle-settings.ts +188 -0
  49. package/src/extension/team-tool/inspect.ts +41 -41
  50. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  51. package/src/extension/team-tool/plan.ts +19 -19
  52. package/src/extension/team-tool/respond.ts +67 -0
  53. package/src/extension/team-tool/run.ts +6 -4
  54. package/src/extension/team-tool/status.ts +99 -93
  55. package/src/extension/team-tool-types.ts +4 -0
  56. package/src/extension/team-tool.ts +5 -1
  57. package/src/i18n.ts +184 -0
  58. package/src/observability/correlation.ts +2 -2
  59. package/src/observability/event-to-metric.ts +10 -3
  60. package/src/observability/exporters/adapter.ts +7 -1
  61. package/src/observability/exporters/otlp-exporter.ts +14 -2
  62. package/src/observability/exporters/prometheus-exporter.ts +9 -2
  63. package/src/observability/metric-registry.ts +18 -3
  64. package/src/observability/metric-retention.ts +11 -3
  65. package/src/observability/metric-sink.ts +9 -4
  66. package/src/observability/metrics-primitives.ts +4 -3
  67. package/src/prompt/prompt-runtime.ts +72 -68
  68. package/src/runtime/agent-control.ts +63 -63
  69. package/src/runtime/agent-memory.ts +72 -72
  70. package/src/runtime/agent-observability.ts +114 -114
  71. package/src/runtime/async-marker.ts +26 -26
  72. package/src/runtime/attention-events.ts +28 -23
  73. package/src/runtime/background-runner.ts +53 -53
  74. package/src/runtime/child-pi.ts +4 -4
  75. package/src/runtime/completion-guard.ts +95 -4
  76. package/src/runtime/concurrency.ts +1 -1
  77. package/src/runtime/crash-recovery.ts +32 -1
  78. package/src/runtime/crew-agent-runtime.ts +59 -58
  79. package/src/runtime/deadletter.ts +14 -4
  80. package/src/runtime/delivery-coordinator.ts +143 -0
  81. package/src/runtime/direct-run.ts +35 -35
  82. package/src/runtime/foreground-control.ts +82 -82
  83. package/src/runtime/green-contract.ts +46 -46
  84. package/src/runtime/group-join.ts +106 -106
  85. package/src/runtime/heartbeat-gradient.ts +28 -28
  86. package/src/runtime/heartbeat-watcher.ts +48 -4
  87. package/src/runtime/live-agent-control.ts +87 -87
  88. package/src/runtime/live-agent-manager.ts +85 -85
  89. package/src/runtime/live-control-realtime.ts +36 -36
  90. package/src/runtime/live-session-runtime.ts +305 -305
  91. package/src/runtime/manifest-cache.ts +2 -2
  92. package/src/runtime/model-fallback.ts +272 -261
  93. package/src/runtime/overflow-recovery.ts +157 -0
  94. package/src/runtime/parallel-research.ts +44 -44
  95. package/src/runtime/parallel-utils.ts +1 -1
  96. package/src/runtime/pi-json-output.ts +111 -111
  97. package/src/runtime/policy-engine.ts +79 -78
  98. package/src/runtime/post-exit-stdio-guard.ts +2 -2
  99. package/src/runtime/process-status.ts +56 -56
  100. package/src/runtime/progress-event-coalescer.ts +43 -43
  101. package/src/runtime/recovery-recipes.ts +74 -74
  102. package/src/runtime/retry-executor.ts +5 -0
  103. package/src/runtime/role-permission.ts +39 -39
  104. package/src/runtime/runtime-resolver.ts +1 -1
  105. package/src/runtime/session-resources.ts +25 -0
  106. package/src/runtime/session-snapshot.ts +59 -0
  107. package/src/runtime/session-usage.ts +79 -79
  108. package/src/runtime/sidechain-output.ts +29 -29
  109. package/src/runtime/stale-reconciler.ts +179 -0
  110. package/src/runtime/subagent-manager.ts +3 -3
  111. package/src/runtime/supervisor-contact.ts +59 -0
  112. package/src/runtime/task-display.ts +38 -38
  113. package/src/runtime/task-output-context.ts +127 -127
  114. package/src/runtime/task-runner/live-executor.ts +101 -101
  115. package/src/runtime/task-runner/progress.ts +119 -111
  116. package/src/runtime/task-runner/result-utils.ts +14 -14
  117. package/src/runtime/task-runner/state-helpers.ts +22 -22
  118. package/src/runtime/task-runner.ts +14 -0
  119. package/src/runtime/team-runner.ts +9 -10
  120. package/src/runtime/worker-heartbeat.ts +21 -21
  121. package/src/runtime/worker-startup.ts +57 -57
  122. package/src/schema/config-schema.ts +2 -1
  123. package/src/schema/team-tool-schema.ts +115 -109
  124. package/src/state/artifact-store.ts +4 -2
  125. package/src/state/atomic-write.ts +12 -4
  126. package/src/state/contracts.ts +109 -105
  127. package/src/state/event-log.ts +3 -4
  128. package/src/state/jsonl-writer.ts +4 -1
  129. package/src/state/locks.ts +9 -1
  130. package/src/state/task-claims.ts +44 -42
  131. package/src/state/usage.ts +29 -29
  132. package/src/subagents/async-entry.ts +1 -1
  133. package/src/subagents/index.ts +3 -3
  134. package/src/subagents/live/control.ts +1 -1
  135. package/src/subagents/live/manager.ts +1 -1
  136. package/src/subagents/live/realtime.ts +1 -1
  137. package/src/subagents/live/session-runtime.ts +1 -1
  138. package/src/subagents/manager.ts +1 -1
  139. package/src/subagents/spawn.ts +1 -1
  140. package/src/teams/discover-teams.ts +2 -2
  141. package/src/teams/team-serializer.ts +38 -38
  142. package/src/types/diff.d.ts +18 -18
  143. package/src/ui/crew-footer.ts +101 -101
  144. package/src/ui/crew-select-list.ts +111 -111
  145. package/src/ui/crew-widget.ts +5 -4
  146. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  147. package/src/ui/dynamic-border.ts +25 -25
  148. package/src/ui/layout-primitives.ts +106 -106
  149. package/src/ui/live-run-sidebar.ts +1 -1
  150. package/src/ui/loaders.ts +158 -158
  151. package/src/ui/mascot.ts +3 -2
  152. package/src/ui/powerbar-publisher.ts +7 -6
  153. package/src/ui/render-diff.ts +119 -119
  154. package/src/ui/render-scheduler.ts +54 -14
  155. package/src/ui/run-dashboard.ts +39 -11
  156. package/src/ui/run-snapshot-cache.ts +336 -36
  157. package/src/ui/spinner.ts +17 -17
  158. package/src/ui/status-colors.ts +58 -54
  159. package/src/ui/syntax-highlight.ts +116 -116
  160. package/src/ui/theme-adapter.ts +1 -1
  161. package/src/ui/transcript-viewer.ts +7 -2
  162. package/src/utils/atomic-write.ts +33 -0
  163. package/src/utils/completion-dedupe.ts +63 -63
  164. package/src/utils/file-coalescer.ts +5 -3
  165. package/src/utils/frontmatter.ts +68 -36
  166. package/src/utils/git.ts +262 -262
  167. package/src/utils/ids.ts +12 -12
  168. package/src/utils/internal-error.ts +1 -1
  169. package/src/utils/names.ts +27 -26
  170. package/src/utils/paths.ts +1 -1
  171. package/src/utils/redaction.ts +44 -41
  172. package/src/utils/safe-paths.ts +47 -34
  173. package/src/utils/sleep.ts +2 -2
  174. package/src/utils/timings.ts +2 -0
  175. package/src/utils/visual.ts +9 -1
  176. package/src/workflows/discover-workflows.ts +4 -1
  177. package/src/workflows/validate-workflow.ts +40 -40
  178. package/src/worktree/branch-freshness.ts +45 -45
  179. package/src/worktree/worktree-manager.ts +6 -1
  180. package/teams/default.team.md +12 -12
  181. package/teams/fast-fix.team.md +11 -11
  182. package/teams/implementation.team.md +18 -18
  183. package/teams/parallel-research.team.md +14 -14
  184. package/teams/research.team.md +11 -11
  185. package/teams/review.team.md +12 -12
  186. package/workflows/default.workflow.md +29 -29
  187. package/workflows/fast-fix.workflow.md +22 -22
  188. package/workflows/implementation.workflow.md +38 -38
  189. package/workflows/parallel-research.workflow.md +46 -46
  190. package/workflows/research.workflow.md +22 -22
  191. package/workflows/review.workflow.md +30 -30
@@ -11,6 +11,15 @@ export interface OTLPExporterOptions {
11
11
  }
12
12
 
13
13
  function pointValues(snapshot: MetricSnapshot): unknown[] {
14
+ if (snapshot.type === "histogram") {
15
+ return snapshot.values.map((value) => ({
16
+ attributes: Object.entries(value.labels).map(([key, item]) => ({ key, value: { stringValue: String(item) } })),
17
+ count: "count" in value ? value.count : undefined,
18
+ sum: "sum" in value ? value.sum : undefined,
19
+ bucketCounts: "counts" in value ? value.counts : undefined,
20
+ explicitBounds: "buckets" in value ? value.buckets : undefined,
21
+ }));
22
+ }
14
23
  return snapshot.values.map((value) => ({ attributes: Object.entries(value.labels).map(([key, item]) => ({ key, value: { stringValue: String(item) } })), asDouble: "value" in value ? value.value : undefined, count: "count" in value ? value.count : undefined, sum: "sum" in value ? value.sum : undefined }));
15
24
  }
16
25
 
@@ -40,7 +49,7 @@ export class OTLPExporter implements MetricExporter {
40
49
  start(): void {
41
50
  this.dispose();
42
51
  this.timer = setInterval(() => { void this.push(this.registry.snapshot()); }, this.opts.intervalMs ?? 60_000);
43
- this.timer.unref?.();
52
+ this.timer.unref();
44
53
  }
45
54
 
46
55
  async push(snapshots: MetricSnapshot[]): Promise<void> {
@@ -49,7 +58,10 @@ export class OTLPExporter implements MetricExporter {
49
58
  const controller = new AbortController();
50
59
  const timer = setTimeout(() => controller.abort(), timeoutMs);
51
60
  try {
52
- await fetch(this.opts.endpoint, { method: "POST", headers: { "content-type": "application/json", ...(this.opts.headers ?? {}) }, body: JSON.stringify(convertToOTLP(snapshots)), signal: controller.signal });
61
+ const response = await fetch(this.opts.endpoint, { method: "POST", headers: { "content-type": "application/json", ...(this.opts.headers ?? {}) }, body: JSON.stringify(convertToOTLP(snapshots)), signal: controller.signal });
62
+ if (!response.ok) {
63
+ logInternalError("otlp-export-http", new Error(`HTTP ${response.status}: ${response.statusText}`), `endpoint=${this.opts.endpoint}`);
64
+ }
53
65
  } finally {
54
66
  clearTimeout(timer);
55
67
  }
@@ -1,7 +1,7 @@
1
1
  import type { HistogramPoint, MetricLabels, MetricPoint, MetricSnapshot } from "../metrics-primitives.ts";
2
2
 
3
3
  function prometheusName(name: string): string {
4
- return name.replace(/\./g, "_");
4
+ return name.replace(/[^a-zA-Z0-9_:]/g, "_").replace(/^[0-9]/, "_$&");
5
5
  }
6
6
 
7
7
  function escapeLabel(value: string): string {
@@ -22,6 +22,13 @@ function isHistogramPoint(value: MetricPoint | HistogramPoint): value is Histogr
22
22
  return "buckets" in value && "counts" in value;
23
23
  }
24
24
 
25
+ function formatPrometheusValue(num: number): string {
26
+ if (Number.isNaN(num)) return "Nan";
27
+ if (num === Number.POSITIVE_INFINITY) return "+Inf";
28
+ if (num === Number.NEGATIVE_INFINITY) return "-Inf";
29
+ return String(num);
30
+ }
31
+
25
32
  export function formatPrometheus(snapshots: MetricSnapshot[]): string {
26
33
  const lines: string[] = [];
27
34
  for (const snapshot of snapshots) {
@@ -39,7 +46,7 @@ export function formatPrometheus(snapshots: MetricSnapshot[]): string {
39
46
  lines.push(`${name}_sum${labelsText(value.labels)} ${value.sum}`);
40
47
  lines.push(`${name}_count${labelsText(value.labels)} ${value.count}`);
41
48
  } else {
42
- lines.push(`${name}${labelsText(value.labels)} ${value.value}`);
49
+ lines.push(`${name}${labelsText(value.labels)} ${formatPrometheusValue(value.value)}`);
43
50
  }
44
51
  }
45
52
  }
@@ -35,21 +35,36 @@ export class MetricRegistry {
35
35
 
36
36
  counter(name: string, description: string): Counter {
37
37
  const existing = this.metrics.get(name);
38
- if (existing instanceof Counter) return existing;
38
+ if (existing instanceof Counter) {
39
+ if (existing.description !== description) {
40
+ process.stderr.write(`[pi-crew] metric-registry: counter '${name}' description changed; using original: '${existing.description}'\n`);
41
+ }
42
+ return existing;
43
+ }
39
44
  if (existing) throw new Error(`Metric '${name}' is not a counter.`);
40
45
  return this.registerCounter(name, description);
41
46
  }
42
47
 
43
48
  gauge(name: string, description: string): Gauge {
44
49
  const existing = this.metrics.get(name);
45
- if (existing instanceof Gauge) return existing;
50
+ if (existing instanceof Gauge) {
51
+ if (existing.description !== description) {
52
+ process.stderr.write(`[pi-crew] metric-registry: gauge '${name}' description changed; using original: '${existing.description}'\n`);
53
+ }
54
+ return existing;
55
+ }
46
56
  if (existing) throw new Error(`Metric '${name}' is not a gauge.`);
47
57
  return this.registerGauge(name, description);
48
58
  }
49
59
 
50
60
  histogram(name: string, description: string, buckets?: number[]): Histogram {
51
61
  const existing = this.metrics.get(name);
52
- if (existing instanceof Histogram) return existing;
62
+ if (existing instanceof Histogram) {
63
+ if (existing.description !== description) {
64
+ process.stderr.write(`[pi-crew] metric-registry: histogram '${name}' description changed; using original: '${existing.description}'\n`);
65
+ }
66
+ return existing;
67
+ }
53
68
  if (existing) throw new Error(`Metric '${name}' is not a histogram.`);
54
69
  return this.registerHistogram(name, description, buckets);
55
70
  }
@@ -10,6 +10,7 @@ export class TimeWindowedCounter {
10
10
  private events: WindowEvent[] = [];
11
11
  private readonly windowMs: number;
12
12
  private readonly now: () => number;
13
+ private static readonly MAX_EVENTS = 100_000;
13
14
 
14
15
  constructor(windowMs = 3_600_000, now: () => number = () => Date.now()) {
15
16
  this.windowMs = windowMs;
@@ -18,14 +19,17 @@ export class TimeWindowedCounter {
18
19
 
19
20
  inc(labels: MetricLabels = {}, delta = 1): void {
20
21
  if (!Number.isFinite(delta)) return;
22
+ // Cap the event array to prevent unbounded memory growth.
23
+ if (this.events.length >= TimeWindowedCounter.MAX_EVENTS) this.prune();
21
24
  this.events.push({ timestamp: this.now(), labels: { ...labels }, delta });
22
25
  this.prune();
23
26
  }
24
27
 
25
28
  count(labels: MetricLabels = {}, durationMs = this.windowMs): number {
26
- this.prune();
29
+ const now = this.now();
30
+ this.pruneAt(now);
27
31
  const key = labelKey(labels);
28
- const cutoff = this.now() - durationMs;
32
+ const cutoff = now - durationMs;
29
33
  return this.events.filter((event) => event.timestamp >= cutoff && labelKey(event.labels) === key).reduce((sum, event) => sum + event.delta, 0);
30
34
  }
31
35
 
@@ -40,7 +44,11 @@ export class TimeWindowedCounter {
40
44
  }
41
45
 
42
46
  private prune(): void {
43
- const cutoff = this.now() - this.windowMs;
47
+ this.pruneAt(this.now());
48
+ }
49
+
50
+ private pruneAt(now: number): void {
51
+ const cutoff = now - this.windowMs;
44
52
  this.events = this.events.filter((event) => event.timestamp >= cutoff);
45
53
  }
46
54
  }
@@ -36,16 +36,21 @@ export function createMetricFileSink(opts: MetricFileSinkOptions): MetricSink {
36
36
  const retentionDays = opts.retentionDays ?? 7;
37
37
  const writeSnapshot = (snapshots: MetricSnapshot[]): void => {
38
38
  try {
39
- const date = new Date().toISOString().slice(0, 10);
39
+ const now = new Date();
40
+ const date = now.toISOString().slice(0, 10);
40
41
  fs.mkdirSync(dir, { recursive: true });
41
42
  rotateOldFiles(dir, retentionDays);
42
- const redacted = redactSecrets(snapshots) as MetricSnapshot[];
43
- fs.appendFileSync(path.join(dir, `${date}.jsonl`), `${JSON.stringify({ exportedAt: new Date().toISOString(), snapshots: redacted })}\n`, "utf-8");
43
+ const redacted = redactSecrets(snapshots);
44
+ if (!Array.isArray(redacted)) {
45
+ logInternalError("metric-sink.type", new Error("redactSecrets did not return an array"), `got=${typeof redacted}`);
46
+ return;
47
+ }
48
+ fs.appendFileSync(path.join(dir, `${date}.jsonl`), `${JSON.stringify({ exportedAt: now.toISOString(), snapshots: redacted as MetricSnapshot[] })}\n`, "utf-8");
44
49
  } catch (error) {
45
50
  logInternalError("metric-sink.write", error);
46
51
  }
47
52
  };
48
53
  const timer = setInterval(() => writeSnapshot(opts.registry.snapshot()), opts.intervalMs ?? 60_000);
49
- timer.unref?.();
54
+ timer.unref();
50
55
  return { writeSnapshot, dispose: () => clearInterval(timer) };
51
56
  }
@@ -66,7 +66,7 @@ export class Counter extends Metric {
66
66
  private values = new Map<string, StoredValue>();
67
67
 
68
68
  inc(labels: MetricLabels = {}, delta = 1): void {
69
- if (!Number.isFinite(delta)) return;
69
+ if (!Number.isFinite(delta) || delta < 0) return;
70
70
  const key = labelKey(labels);
71
71
  const current = this.values.get(key) ?? { labels: normalizeLabels(labels), value: 0 };
72
72
  this.values.set(key, { labels: current.labels, value: current.value + delta });
@@ -116,12 +116,13 @@ export class Histogram extends Metric {
116
116
  observe(labels: MetricLabels = {}, value: number): void {
117
117
  if (!Number.isFinite(value)) return;
118
118
  const key = labelKey(labels);
119
- const current = this.observations.get(key) ?? { labels: normalizeLabels(labels), counts: new Array(this.buckets.length + 1).fill(0) as number[], sum: 0, count: 0 };
119
+ const existing = this.observations.get(key);
120
+ const current = existing ?? { labels: normalizeLabels(labels), counts: new Array(this.buckets.length + 1).fill(0) as number[], sum: 0, count: 0 };
120
121
  const bucketIndex = this.buckets.findIndex((bucket) => value <= bucket);
121
122
  current.counts[bucketIndex === -1 ? this.buckets.length : bucketIndex] = (current.counts[bucketIndex === -1 ? this.buckets.length : bucketIndex] ?? 0) + 1;
122
123
  current.sum += value;
123
124
  current.count += 1;
124
- this.observations.set(key, current);
125
+ if (!existing) this.observations.set(key, current);
125
126
  }
126
127
 
127
128
  quantile(labels: MetricLabels = {}, q: number): number {
@@ -1,68 +1,72 @@
1
- import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
-
3
- export const PI_TEAMS_INHERIT_PROJECT_CONTEXT_ENV = "PI_TEAMS_INHERIT_PROJECT_CONTEXT";
4
- export const PI_TEAMS_INHERIT_SKILLS_ENV = "PI_TEAMS_INHERIT_SKILLS";
5
- export const PI_CREW_INHERIT_PROJECT_CONTEXT_ENV = "PI_CREW_INHERIT_PROJECT_CONTEXT";
6
- export const PI_CREW_INHERIT_SKILLS_ENV = "PI_CREW_INHERIT_SKILLS";
7
-
8
- const PROJECT_CONTEXT_HEADER = "\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n";
9
- const SKILLS_HEADER = "\n\nThe following skills provide specialized instructions for specific tasks.";
10
- const DATE_HEADER = "\nCurrent date:";
11
-
12
- function readBooleanEnv(name: string): boolean | undefined {
13
- const value = process.env[name];
14
- if (value === undefined) return undefined;
15
- return value !== "0";
16
- }
17
-
18
- function readBooleanEnvAny(...names: string[]): boolean | undefined {
19
- for (const name of names) {
20
- const value = readBooleanEnv(name);
21
- if (value !== undefined) return value;
22
- }
23
- return undefined;
24
- }
25
-
26
- function findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[]): number {
27
- let endIndex = prompt.length;
28
- for (const header of nextHeaders) {
29
- const index = prompt.indexOf(header, startIndex);
30
- if (index !== -1 && index < endIndex) endIndex = index;
31
- }
32
- return endIndex;
33
- }
34
-
35
- export function stripProjectContext(prompt: string): string {
36
- const startIndex = prompt.indexOf(PROJECT_CONTEXT_HEADER);
37
- if (startIndex === -1) return prompt;
38
- const endIndex = findSectionEnd(prompt, startIndex + PROJECT_CONTEXT_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);
39
- return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;
40
- }
41
-
42
- export function stripInheritedSkills(prompt: string): string {
43
- const startIndex = prompt.indexOf(SKILLS_HEADER);
44
- if (startIndex === -1) return prompt;
45
- const endIndex = findSectionEnd(prompt, startIndex + SKILLS_HEADER.length, [DATE_HEADER]);
46
- return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;
47
- }
48
-
49
- export function rewriteTeamWorkerPrompt(prompt: string, options: { inheritProjectContext: boolean; inheritSkills: boolean }): string {
50
- let rewritten = prompt;
51
- if (!options.inheritProjectContext) rewritten = stripProjectContext(rewritten);
52
- if (!options.inheritSkills) rewritten = stripInheritedSkills(rewritten);
53
- return rewritten;
54
- }
55
-
56
- export default function registerPiTeamsPromptRuntime(pi: ExtensionAPI): void {
57
- pi.on("before_agent_start", (event) => {
58
- const inheritProjectContext = readBooleanEnvAny(PI_CREW_INHERIT_PROJECT_CONTEXT_ENV, PI_TEAMS_INHERIT_PROJECT_CONTEXT_ENV);
59
- const inheritSkills = readBooleanEnvAny(PI_CREW_INHERIT_SKILLS_ENV, PI_TEAMS_INHERIT_SKILLS_ENV);
60
- if (inheritProjectContext === undefined && inheritSkills === undefined) return;
61
- const rewritten = rewriteTeamWorkerPrompt(event.systemPrompt, {
62
- inheritProjectContext: inheritProjectContext ?? true,
63
- inheritSkills: inheritSkills ?? true,
64
- });
65
- if (rewritten === event.systemPrompt) return;
66
- return { systemPrompt: rewritten };
67
- });
68
- }
1
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+
3
+ export const PI_TEAMS_INHERIT_PROJECT_CONTEXT_ENV = "PI_TEAMS_INHERIT_PROJECT_CONTEXT";
4
+ export const PI_TEAMS_INHERIT_SKILLS_ENV = "PI_TEAMS_INHERIT_SKILLS";
5
+ export const PI_CREW_INHERIT_PROJECT_CONTEXT_ENV = "PI_CREW_INHERIT_PROJECT_CONTEXT";
6
+ export const PI_CREW_INHERIT_SKILLS_ENV = "PI_CREW_INHERIT_SKILLS";
7
+
8
+ const PROJECT_CONTEXT_HEADER = "\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n";
9
+ const SKILLS_HEADER = "\n\nThe following skills provide specialized instructions for specific tasks.";
10
+ const DATE_HEADER = "\nCurrent date:";
11
+
12
+ function readBooleanEnv(name: string): boolean | undefined {
13
+ const value = process.env[name];
14
+ if (value === undefined) return undefined;
15
+ const normalized = value.trim().toLowerCase();
16
+ if (normalized === "1" || normalized === "true" || normalized === "yes") return true;
17
+ if (normalized === "0" || normalized === "false" || normalized === "no") return false;
18
+ // Ambiguous value treat as undefined so callers apply their default.
19
+ return undefined;
20
+ }
21
+
22
+ function readBooleanEnvAny(...names: string[]): boolean | undefined {
23
+ for (const name of names) {
24
+ const value = readBooleanEnv(name);
25
+ if (value !== undefined) return value;
26
+ }
27
+ return undefined;
28
+ }
29
+
30
+ function findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[]): number {
31
+ let endIndex = prompt.length;
32
+ for (const header of nextHeaders) {
33
+ const index = prompt.indexOf(header, startIndex);
34
+ if (index !== -1 && index < endIndex) endIndex = index;
35
+ }
36
+ return endIndex;
37
+ }
38
+
39
+ export function stripProjectContext(prompt: string): string {
40
+ const startIndex = prompt.indexOf(PROJECT_CONTEXT_HEADER);
41
+ if (startIndex === -1) return prompt;
42
+ const endIndex = findSectionEnd(prompt, startIndex + PROJECT_CONTEXT_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);
43
+ return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;
44
+ }
45
+
46
+ export function stripInheritedSkills(prompt: string): string {
47
+ const startIndex = prompt.indexOf(SKILLS_HEADER);
48
+ if (startIndex === -1) return prompt;
49
+ const endIndex = findSectionEnd(prompt, startIndex + SKILLS_HEADER.length, [DATE_HEADER]);
50
+ return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;
51
+ }
52
+
53
+ export function rewriteTeamWorkerPrompt(prompt: string, options: { inheritProjectContext: boolean; inheritSkills: boolean }): string {
54
+ let rewritten = prompt;
55
+ if (!options.inheritProjectContext) rewritten = stripProjectContext(rewritten);
56
+ if (!options.inheritSkills) rewritten = stripInheritedSkills(rewritten);
57
+ return rewritten;
58
+ }
59
+
60
+ export default function registerPiTeamsPromptRuntime(pi: ExtensionAPI): void {
61
+ pi.on("before_agent_start", (event) => {
62
+ const inheritProjectContext = readBooleanEnvAny(PI_CREW_INHERIT_PROJECT_CONTEXT_ENV, PI_TEAMS_INHERIT_PROJECT_CONTEXT_ENV);
63
+ const inheritSkills = readBooleanEnvAny(PI_CREW_INHERIT_SKILLS_ENV, PI_TEAMS_INHERIT_SKILLS_ENV);
64
+ if (inheritProjectContext === undefined && inheritSkills === undefined) return;
65
+ const rewritten = rewriteTeamWorkerPrompt(event.systemPrompt, {
66
+ inheritProjectContext: inheritProjectContext ?? true,
67
+ inheritSkills: inheritSkills ?? true,
68
+ });
69
+ if (rewritten === event.systemPrompt) return;
70
+ return { systemPrompt: rewritten };
71
+ });
72
+ }
@@ -1,63 +1,63 @@
1
- import type { PiTeamsConfig } from "../config/config.ts";
2
- import type { TeamRunManifest } from "../state/types.ts";
3
- import { appendTaskAttentionEvent } from "./attention-events.ts";
4
- import type { CrewAgentRecord } from "./crew-agent-runtime.ts";
5
- import { upsertCrewAgent } from "./crew-agent-records.ts";
6
-
7
- export interface CrewControlConfig {
8
- enabled: boolean;
9
- needsAttentionAfterMs: number;
10
- }
11
-
12
- const DEFAULT_NEEDS_ATTENTION_MS = 60_000;
13
-
14
- function positiveInt(value: unknown): number | undefined {
15
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
16
- }
17
-
18
- export function resolveCrewControlConfig(config: PiTeamsConfig | undefined): CrewControlConfig {
19
- const raw = config as PiTeamsConfig & { control?: { enabled?: unknown; needsAttentionAfterMs?: unknown } } | undefined;
20
- return {
21
- enabled: raw?.control?.enabled === false ? false : true,
22
- needsAttentionAfterMs: positiveInt(raw?.control?.needsAttentionAfterMs) ?? DEFAULT_NEEDS_ATTENTION_MS,
23
- };
24
- }
25
-
26
- export function activityAgeMs(agent: CrewAgentRecord, now = Date.now()): number | undefined {
27
- const timestamp = agent.progress?.lastActivityAt ?? agent.startedAt;
28
- if (!timestamp) return undefined;
29
- const ms = now - new Date(timestamp).getTime();
30
- return Number.isFinite(ms) ? Math.max(0, ms) : undefined;
31
- }
32
-
33
- export function formatActivityAge(agent: CrewAgentRecord, now = Date.now()): string | undefined {
34
- const age = activityAgeMs(agent, now);
35
- if (age === undefined) return undefined;
36
- if (age < 1000) return "active now";
37
- const seconds = Math.floor(age / 1000);
38
- if (seconds < 60) return agent.progress?.activityState === "needs_attention" ? `no activity for ${seconds}s` : `active ${seconds}s ago`;
39
- const minutes = Math.floor(seconds / 60);
40
- return agent.progress?.activityState === "needs_attention" ? `no activity for ${minutes}m` : `active ${minutes}m ago`;
41
- }
42
-
43
- export function applyAttentionState(manifest: TeamRunManifest, agent: CrewAgentRecord, config: CrewControlConfig, now = Date.now()): CrewAgentRecord {
44
- if (!config.enabled || agent.status !== "running") return agent;
45
- const age = activityAgeMs(agent, now);
46
- if (age === undefined || age <= config.needsAttentionAfterMs) return agent;
47
- if (agent.progress?.activityState === "needs_attention") return agent;
48
- const updated: CrewAgentRecord = {
49
- ...agent,
50
- progress: {
51
- ...(agent.progress ?? { recentTools: [], recentOutput: [], toolCount: agent.toolUses ?? 0 }),
52
- activityState: "needs_attention",
53
- },
54
- };
55
- upsertCrewAgent(manifest, updated);
56
- appendTaskAttentionEvent({
57
- manifest,
58
- taskId: agent.taskId,
59
- message: `${agent.agent} needs attention (no observed activity for ${Math.floor(age / 1000)}s).`,
60
- data: { activityState: "needs_attention", reason: "idle", elapsedMs: age, taskId: agent.taskId, agentName: agent.agent, suggestedAction: "Check worker status, wait, steer, or cancel if needed." },
61
- });
62
- return updated;
63
- }
1
+ import type { PiTeamsConfig } from "../config/config.ts";
2
+ import type { TeamRunManifest } from "../state/types.ts";
3
+ import { appendTaskAttentionEvent } from "./attention-events.ts";
4
+ import type { CrewAgentRecord } from "./crew-agent-runtime.ts";
5
+ import { upsertCrewAgent } from "./crew-agent-records.ts";
6
+
7
+ export interface CrewControlConfig {
8
+ enabled: boolean;
9
+ needsAttentionAfterMs: number;
10
+ }
11
+
12
+ const DEFAULT_NEEDS_ATTENTION_MS = 60_000;
13
+
14
+ function positiveInt(value: unknown): number | undefined {
15
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
16
+ }
17
+
18
+ export function resolveCrewControlConfig(config: PiTeamsConfig | undefined): CrewControlConfig {
19
+ const raw = config as PiTeamsConfig & { control?: { enabled?: unknown; needsAttentionAfterMs?: unknown } } | undefined;
20
+ return {
21
+ enabled: raw?.control?.enabled === false ? false : true,
22
+ needsAttentionAfterMs: positiveInt(raw?.control?.needsAttentionAfterMs) ?? DEFAULT_NEEDS_ATTENTION_MS,
23
+ };
24
+ }
25
+
26
+ export function activityAgeMs(agent: CrewAgentRecord, now = Date.now()): number | undefined {
27
+ const timestamp = agent.progress?.lastActivityAt ?? agent.startedAt;
28
+ if (!timestamp) return undefined;
29
+ const ms = now - new Date(timestamp).getTime();
30
+ return Number.isFinite(ms) ? Math.max(0, ms) : undefined;
31
+ }
32
+
33
+ export function formatActivityAge(agent: CrewAgentRecord, now = Date.now()): string | undefined {
34
+ const age = activityAgeMs(agent, now);
35
+ if (age === undefined) return undefined;
36
+ if (age < 1000) return "active now";
37
+ const seconds = Math.floor(age / 1000);
38
+ if (seconds < 60) return agent.progress?.activityState === "needs_attention" ? `no activity for ${seconds}s` : `active ${seconds}s ago`;
39
+ const minutes = Math.floor(seconds / 60);
40
+ return agent.progress?.activityState === "needs_attention" ? `no activity for ${minutes}m` : `active ${minutes}m ago`;
41
+ }
42
+
43
+ export function applyAttentionState(manifest: TeamRunManifest, agent: CrewAgentRecord, config: CrewControlConfig, now = Date.now()): CrewAgentRecord {
44
+ if (!config.enabled || agent.status !== "running") return agent;
45
+ const age = activityAgeMs(agent, now);
46
+ if (age === undefined || age <= config.needsAttentionAfterMs) return agent;
47
+ if (agent.progress?.activityState === "needs_attention") return agent;
48
+ const updated: CrewAgentRecord = {
49
+ ...agent,
50
+ progress: {
51
+ ...(agent.progress ?? { recentTools: [], recentOutput: [], toolCount: agent.toolUses ?? 0 }),
52
+ activityState: "needs_attention",
53
+ },
54
+ };
55
+ upsertCrewAgent(manifest, updated);
56
+ appendTaskAttentionEvent({
57
+ manifest,
58
+ taskId: agent.taskId,
59
+ message: `${agent.agent} needs attention (no observed activity for ${Math.floor(age / 1000)}s).`,
60
+ data: { activityState: "needs_attention", reason: "idle", elapsedMs: age, taskId: agent.taskId, agentName: agent.agent, suggestedAction: "Check worker status, wait, steer, or cancel if needed." },
61
+ });
62
+ return updated;
63
+ }
@@ -1,72 +1,72 @@
1
- import * as fs from "node:fs";
2
- import * as os from "node:os";
3
- import * as path from "node:path";
4
-
5
- export type AgentMemoryScope = "user" | "project" | "local";
6
- const MAX_MEMORY_LINES = 200;
7
-
8
- export function isUnsafeMemoryName(name: string): boolean {
9
- return !name || name.length > 128 || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
10
- }
11
-
12
- export function isSymlink(filePath: string): boolean {
13
- try {
14
- return fs.lstatSync(filePath).isSymbolicLink();
15
- } catch {
16
- return false;
17
- }
18
- }
19
-
20
- export function safeReadMemoryFile(filePath: string): string | undefined {
21
- if (!fs.existsSync(filePath) || isSymlink(filePath)) return undefined;
22
- try {
23
- return fs.readFileSync(filePath, "utf-8");
24
- } catch {
25
- return undefined;
26
- }
27
- }
28
-
29
- export function resolveMemoryDir(agentName: string, scope: AgentMemoryScope, cwd: string): string {
30
- if (isUnsafeMemoryName(agentName)) throw new Error(`Unsafe agent name for memory directory: ${agentName}`);
31
- if (scope === "user") return path.join(os.homedir(), ".pi", "agent-memory", agentName);
32
- if (scope === "project") return path.join(cwd, ".pi", "agent-memory", agentName);
33
- return path.join(cwd, ".pi", "agent-memory-local", agentName);
34
- }
35
-
36
- export function ensureMemoryDir(memoryDir: string): void {
37
- if (fs.existsSync(memoryDir)) {
38
- if (isSymlink(memoryDir)) throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
39
- return;
40
- }
41
- fs.mkdirSync(memoryDir, { recursive: true });
42
- }
43
-
44
- export function readMemoryIndex(memoryDir: string): string | undefined {
45
- if (isSymlink(memoryDir)) return undefined;
46
- const content = safeReadMemoryFile(path.join(memoryDir, "MEMORY.md"));
47
- if (content === undefined) return undefined;
48
- const lines = content.split(/\r?\n/);
49
- return lines.length > MAX_MEMORY_LINES ? `${lines.slice(0, MAX_MEMORY_LINES).join("\n")}\n... (truncated at 200 lines)` : content;
50
- }
51
-
52
- export function buildMemoryBlock(agentName: string, scope: AgentMemoryScope, cwd: string, writable: boolean): string {
53
- const memoryDir = resolveMemoryDir(agentName, scope, cwd);
54
- if (writable) ensureMemoryDir(memoryDir);
55
- const existing = readMemoryIndex(memoryDir);
56
- const mode = writable ? "read-write" : "read-only";
57
- return [
58
- `# Agent Memory (${mode})`,
59
- `Memory scope: ${scope}`,
60
- `Memory directory: ${memoryDir}`,
61
- writable ? "Use this persistent directory to maintain useful long-term notes for this agent." : "You may reference existing memory, but do not create or modify memory files.",
62
- "",
63
- existing ? `## Current MEMORY.md\n${existing}` : "No MEMORY.md exists yet.",
64
- writable ? [
65
- "",
66
- "## Memory Instructions",
67
- "- Keep MEMORY.md concise (under 200 lines); store details in separate linked files.",
68
- "- Reject stale memories; update or remove outdated notes.",
69
- "- Use safe relative filenames inside the memory directory only.",
70
- ].join("\n") : "",
71
- ].filter(Boolean).join("\n");
72
- }
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+
5
+ export type AgentMemoryScope = "user" | "project" | "local";
6
+ const MAX_MEMORY_LINES = 200;
7
+
8
+ export function isUnsafeMemoryName(name: string): boolean {
9
+ return !name || name.length > 128 || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
10
+ }
11
+
12
+ export function isSymlink(filePath: string): boolean {
13
+ try {
14
+ return fs.lstatSync(filePath).isSymbolicLink();
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ export function safeReadMemoryFile(filePath: string): string | undefined {
21
+ if (!fs.existsSync(filePath) || isSymlink(filePath)) return undefined;
22
+ try {
23
+ return fs.readFileSync(filePath, "utf-8");
24
+ } catch {
25
+ return undefined;
26
+ }
27
+ }
28
+
29
+ export function resolveMemoryDir(agentName: string, scope: AgentMemoryScope, cwd: string): string {
30
+ if (isUnsafeMemoryName(agentName)) throw new Error(`Unsafe agent name for memory directory: ${agentName}`);
31
+ if (scope === "user") return path.join(os.homedir(), ".pi", "agent-memory", agentName);
32
+ if (scope === "project") return path.join(cwd, ".pi", "agent-memory", agentName);
33
+ return path.join(cwd, ".pi", "agent-memory-local", agentName);
34
+ }
35
+
36
+ export function ensureMemoryDir(memoryDir: string): void {
37
+ if (fs.existsSync(memoryDir)) {
38
+ if (isSymlink(memoryDir)) throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
39
+ return;
40
+ }
41
+ fs.mkdirSync(memoryDir, { recursive: true });
42
+ }
43
+
44
+ export function readMemoryIndex(memoryDir: string): string | undefined {
45
+ if (isSymlink(memoryDir)) return undefined;
46
+ const content = safeReadMemoryFile(path.join(memoryDir, "MEMORY.md"));
47
+ if (content === undefined) return undefined;
48
+ const lines = content.split(/\r?\n/);
49
+ return lines.length > MAX_MEMORY_LINES ? `${lines.slice(0, MAX_MEMORY_LINES).join("\n")}\n... (truncated at 200 lines)` : content;
50
+ }
51
+
52
+ export function buildMemoryBlock(agentName: string, scope: AgentMemoryScope, cwd: string, writable: boolean): string {
53
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
54
+ if (writable) ensureMemoryDir(memoryDir);
55
+ const existing = readMemoryIndex(memoryDir);
56
+ const mode = writable ? "read-write" : "read-only";
57
+ return [
58
+ `# Agent Memory (${mode})`,
59
+ `Memory scope: ${scope}`,
60
+ `Memory directory: ${memoryDir}`,
61
+ writable ? "Use this persistent directory to maintain useful long-term notes for this agent." : "You may reference existing memory, but do not create or modify memory files.",
62
+ "",
63
+ existing ? `## Current MEMORY.md\n${existing}` : "No MEMORY.md exists yet.",
64
+ writable ? [
65
+ "",
66
+ "## Memory Instructions",
67
+ "- Keep MEMORY.md concise (under 200 lines); store details in separate linked files.",
68
+ "- Reject stale memories; update or remove outdated notes.",
69
+ "- Use safe relative filenames inside the memory directory only.",
70
+ ].join("\n") : "",
71
+ ].filter(Boolean).join("\n");
72
+ }