pi-crew 0.1.44 → 0.1.45

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 (142) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/agents/analyst.md +11 -11
  3. package/agents/critic.md +11 -11
  4. package/agents/executor.md +11 -11
  5. package/agents/explorer.md +11 -11
  6. package/agents/planner.md +11 -11
  7. package/agents/reviewer.md +11 -11
  8. package/agents/security-reviewer.md +11 -11
  9. package/agents/test-engineer.md +11 -11
  10. package/agents/verifier.md +11 -11
  11. package/agents/writer.md +11 -11
  12. package/docs/refactor-tasks-phase3.md +394 -394
  13. package/docs/refactor-tasks-phase4.md +564 -564
  14. package/docs/refactor-tasks-phase5.md +402 -402
  15. package/docs/refactor-tasks-phase6.md +662 -662
  16. package/docs/research-extension-examples.md +297 -297
  17. package/docs/research-extension-system.md +324 -324
  18. package/docs/research-optimization-plan.md +548 -548
  19. package/docs/research-phase10-distillation.md +198 -198
  20. package/docs/research-phase11-distillation.md +201 -201
  21. package/docs/research-pi-coding-agent.md +357 -357
  22. package/docs/research-source-pi-crew-reference.md +174 -174
  23. package/docs/runtime-flow.md +148 -148
  24. package/docs/source-runtime-refactor-map.md +83 -83
  25. package/index.ts +6 -6
  26. package/package.json +1 -1
  27. package/src/agents/agent-serializer.ts +34 -34
  28. package/src/extension/cross-extension-rpc.ts +82 -82
  29. package/src/extension/register.ts +8 -1
  30. package/src/extension/registration/commands.ts +18 -2
  31. package/src/extension/registration/compaction-guard.ts +125 -125
  32. package/src/extension/registration/subagent-tools.ts +148 -148
  33. package/src/extension/registration/team-tool.ts +26 -8
  34. package/src/extension/run-bundle-schema.ts +89 -89
  35. package/src/extension/run-maintenance.ts +43 -43
  36. package/src/extension/team-tool/cancel.ts +105 -102
  37. package/src/extension/team-tool/context.ts +1 -0
  38. package/src/extension/team-tool/handle-settings.ts +188 -188
  39. package/src/extension/team-tool/inspect.ts +41 -41
  40. package/src/extension/team-tool/lifecycle-actions.ts +79 -79
  41. package/src/extension/team-tool/plan.ts +19 -19
  42. package/src/extension/team-tool/respond.ts +83 -66
  43. package/src/extension/team-tool/run.ts +1 -0
  44. package/src/i18n.ts +184 -184
  45. package/src/observability/exporters/otlp-exporter.ts +77 -77
  46. package/src/prompt/prompt-runtime.ts +72 -72
  47. package/src/runtime/agent-control.ts +63 -63
  48. package/src/runtime/agent-memory.ts +72 -72
  49. package/src/runtime/agent-observability.ts +114 -114
  50. package/src/runtime/async-marker.ts +26 -26
  51. package/src/runtime/attention-events.ts +28 -28
  52. package/src/runtime/background-runner.ts +53 -53
  53. package/src/runtime/child-pi.ts +444 -444
  54. package/src/runtime/completion-guard.ts +190 -190
  55. package/src/runtime/crew-agent-records.ts +8 -0
  56. package/src/runtime/delivery-coordinator.ts +153 -142
  57. package/src/runtime/direct-run.ts +35 -35
  58. package/src/runtime/foreground-control.ts +82 -82
  59. package/src/runtime/green-contract.ts +46 -46
  60. package/src/runtime/group-join.ts +106 -106
  61. package/src/runtime/heartbeat-gradient.ts +28 -28
  62. package/src/runtime/heartbeat-watcher.ts +124 -124
  63. package/src/runtime/live-agent-control.ts +87 -87
  64. package/src/runtime/live-agent-manager.ts +85 -85
  65. package/src/runtime/live-control-realtime.ts +36 -36
  66. package/src/runtime/live-session-runtime.ts +305 -305
  67. package/src/runtime/overflow-recovery.ts +175 -156
  68. package/src/runtime/parallel-research.ts +44 -44
  69. package/src/runtime/pi-json-output.ts +111 -111
  70. package/src/runtime/policy-engine.ts +79 -79
  71. package/src/runtime/progress-event-coalescer.ts +43 -43
  72. package/src/runtime/recovery-recipes.ts +74 -74
  73. package/src/runtime/retry-executor.ts +64 -64
  74. package/src/runtime/role-permission.ts +39 -39
  75. package/src/runtime/session-resources.ts +25 -25
  76. package/src/runtime/session-snapshot.ts +59 -59
  77. package/src/runtime/session-usage.ts +79 -79
  78. package/src/runtime/sidechain-output.ts +29 -29
  79. package/src/runtime/stale-reconciler.ts +199 -179
  80. package/src/runtime/supervisor-contact.ts +59 -59
  81. package/src/runtime/task-display.ts +38 -38
  82. package/src/runtime/task-output-context.ts +127 -127
  83. package/src/runtime/task-runner/live-executor.ts +101 -101
  84. package/src/runtime/task-runner/progress.ts +119 -119
  85. package/src/runtime/task-runner/result-utils.ts +14 -14
  86. package/src/runtime/task-runner/state-helpers.ts +22 -22
  87. package/src/runtime/team-runner.ts +13 -4
  88. package/src/runtime/worker-heartbeat.ts +21 -21
  89. package/src/runtime/worker-startup.ts +57 -57
  90. package/src/state/state-store.ts +43 -0
  91. package/src/state/task-claims.ts +44 -44
  92. package/src/state/types.ts +2 -0
  93. package/src/state/usage.ts +29 -29
  94. package/src/subagents/async-entry.ts +1 -1
  95. package/src/subagents/index.ts +3 -3
  96. package/src/subagents/live/control.ts +1 -1
  97. package/src/subagents/live/manager.ts +1 -1
  98. package/src/subagents/live/realtime.ts +1 -1
  99. package/src/subagents/live/session-runtime.ts +1 -1
  100. package/src/subagents/manager.ts +1 -1
  101. package/src/subagents/spawn.ts +1 -1
  102. package/src/teams/team-serializer.ts +38 -38
  103. package/src/types/diff.d.ts +18 -18
  104. package/src/ui/crew-footer.ts +101 -101
  105. package/src/ui/crew-select-list.ts +111 -111
  106. package/src/ui/crew-widget.ts +5 -1
  107. package/src/ui/dashboard-panes/mailbox-pane.ts +2 -1
  108. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  109. package/src/ui/dynamic-border.ts +25 -25
  110. package/src/ui/layout-primitives.ts +106 -106
  111. package/src/ui/loaders.ts +158 -158
  112. package/src/ui/powerbar-publisher.ts +1 -1
  113. package/src/ui/render-diff.ts +119 -119
  114. package/src/ui/render-scheduler.ts +143 -143
  115. package/src/ui/run-snapshot-cache.ts +56 -37
  116. package/src/ui/snapshot-types.ts +5 -0
  117. package/src/ui/spinner.ts +17 -17
  118. package/src/ui/status-colors.ts +58 -58
  119. package/src/ui/syntax-highlight.ts +116 -116
  120. package/src/utils/atomic-write.ts +33 -33
  121. package/src/utils/completion-dedupe.ts +63 -63
  122. package/src/utils/frontmatter.ts +68 -68
  123. package/src/utils/git.ts +262 -262
  124. package/src/utils/ids.ts +12 -12
  125. package/src/utils/names.ts +27 -27
  126. package/src/utils/redaction.ts +44 -44
  127. package/src/utils/safe-paths.ts +47 -47
  128. package/src/utils/sleep.ts +32 -32
  129. package/src/workflows/validate-workflow.ts +40 -40
  130. package/src/worktree/branch-freshness.ts +45 -45
  131. package/teams/default.team.md +12 -12
  132. package/teams/fast-fix.team.md +11 -11
  133. package/teams/implementation.team.md +18 -18
  134. package/teams/parallel-research.team.md +14 -14
  135. package/teams/research.team.md +11 -11
  136. package/teams/review.team.md +12 -12
  137. package/workflows/default.workflow.md +29 -29
  138. package/workflows/fast-fix.workflow.md +22 -22
  139. package/workflows/implementation.workflow.md +38 -38
  140. package/workflows/parallel-research.workflow.md +46 -46
  141. package/workflows/research.workflow.md +22 -22
  142. package/workflows/review.workflow.md +30 -30
@@ -1,77 +1,77 @@
1
- import { logInternalError } from "../../utils/internal-error.ts";
2
- import type { MetricRegistry } from "../metric-registry.ts";
3
- import type { MetricSnapshot } from "../metrics-primitives.ts";
4
- import type { MetricExporter } from "./adapter.ts";
5
-
6
- export interface OTLPExporterOptions {
7
- endpoint: string;
8
- headers?: Record<string, string>;
9
- intervalMs?: number;
10
- timeoutMs?: number;
11
- }
12
-
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
- }
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 }));
24
- }
25
-
26
- export function convertToOTLP(snapshots: MetricSnapshot[]): unknown {
27
- return {
28
- resourceMetrics: [{
29
- resource: { attributes: [{ key: "service.name", value: { stringValue: "pi-crew" } }] },
30
- scopeMetrics: [{
31
- scope: { name: "pi-crew" },
32
- metrics: snapshots.map((snapshot) => ({ name: snapshot.name, description: snapshot.description, [snapshot.type === "histogram" ? "histogram" : snapshot.type === "gauge" ? "gauge" : "sum"]: { dataPoints: pointValues(snapshot) } })),
33
- }],
34
- }],
35
- };
36
- }
37
-
38
- export class OTLPExporter implements MetricExporter {
39
- name = "otlp";
40
- private timer?: ReturnType<typeof setInterval>;
41
- private readonly opts: OTLPExporterOptions;
42
- private readonly registry: MetricRegistry;
43
-
44
- constructor(opts: OTLPExporterOptions, registry: MetricRegistry) {
45
- this.opts = opts;
46
- this.registry = registry;
47
- }
48
-
49
- start(): void {
50
- this.dispose();
51
- this.timer = setInterval(() => { void this.push(this.registry.snapshot()); }, this.opts.intervalMs ?? 60_000);
52
- this.timer.unref();
53
- }
54
-
55
- async push(snapshots: MetricSnapshot[]): Promise<void> {
56
- try {
57
- const timeoutMs = this.opts.timeoutMs ?? 10_000;
58
- const controller = new AbortController();
59
- const timer = setTimeout(() => controller.abort(), timeoutMs);
60
- try {
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
- }
65
- } finally {
66
- clearTimeout(timer);
67
- }
68
- } catch (error) {
69
- logInternalError("otlp-export", error);
70
- }
71
- }
72
-
73
- dispose(): void {
74
- if (this.timer) clearInterval(this.timer);
75
- this.timer = undefined;
76
- }
77
- }
1
+ import { logInternalError } from "../../utils/internal-error.ts";
2
+ import type { MetricRegistry } from "../metric-registry.ts";
3
+ import type { MetricSnapshot } from "../metrics-primitives.ts";
4
+ import type { MetricExporter } from "./adapter.ts";
5
+
6
+ export interface OTLPExporterOptions {
7
+ endpoint: string;
8
+ headers?: Record<string, string>;
9
+ intervalMs?: number;
10
+ timeoutMs?: number;
11
+ }
12
+
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
+ }
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 }));
24
+ }
25
+
26
+ export function convertToOTLP(snapshots: MetricSnapshot[]): unknown {
27
+ return {
28
+ resourceMetrics: [{
29
+ resource: { attributes: [{ key: "service.name", value: { stringValue: "pi-crew" } }] },
30
+ scopeMetrics: [{
31
+ scope: { name: "pi-crew" },
32
+ metrics: snapshots.map((snapshot) => ({ name: snapshot.name, description: snapshot.description, [snapshot.type === "histogram" ? "histogram" : snapshot.type === "gauge" ? "gauge" : "sum"]: { dataPoints: pointValues(snapshot) } })),
33
+ }],
34
+ }],
35
+ };
36
+ }
37
+
38
+ export class OTLPExporter implements MetricExporter {
39
+ name = "otlp";
40
+ private timer?: ReturnType<typeof setInterval>;
41
+ private readonly opts: OTLPExporterOptions;
42
+ private readonly registry: MetricRegistry;
43
+
44
+ constructor(opts: OTLPExporterOptions, registry: MetricRegistry) {
45
+ this.opts = opts;
46
+ this.registry = registry;
47
+ }
48
+
49
+ start(): void {
50
+ this.dispose();
51
+ this.timer = setInterval(() => { void this.push(this.registry.snapshot()); }, this.opts.intervalMs ?? 60_000);
52
+ this.timer.unref();
53
+ }
54
+
55
+ async push(snapshots: MetricSnapshot[]): Promise<void> {
56
+ try {
57
+ const timeoutMs = this.opts.timeoutMs ?? 10_000;
58
+ const controller = new AbortController();
59
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
60
+ try {
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
+ }
65
+ } finally {
66
+ clearTimeout(timer);
67
+ }
68
+ } catch (error) {
69
+ logInternalError("otlp-export", error);
70
+ }
71
+ }
72
+
73
+ dispose(): void {
74
+ if (this.timer) clearInterval(this.timer);
75
+ this.timer = undefined;
76
+ }
77
+ }
@@ -1,72 +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
- 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
+ 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
+ }