pi-daddy 0.50.0 → 0.52.0

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 (97) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +13 -20
  3. package/dist/governance/approval-prompt.d.ts +4 -0
  4. package/dist/governance/approval-prompt.d.ts.map +1 -1
  5. package/dist/governance/approval-prompt.js +4 -5
  6. package/dist/governance/approval-prompt.js.map +1 -1
  7. package/dist/governance/initiative-coordinator.d.ts +5 -0
  8. package/dist/governance/initiative-coordinator.d.ts.map +1 -1
  9. package/dist/governance/initiative-coordinator.js +16 -0
  10. package/dist/governance/initiative-coordinator.js.map +1 -1
  11. package/dist/governance/permission-question.d.ts +4 -0
  12. package/dist/governance/permission-question.d.ts.map +1 -0
  13. package/dist/governance/permission-question.js +102 -0
  14. package/dist/governance/permission-question.js.map +1 -0
  15. package/dist/kernel/chain.d.ts +1 -0
  16. package/dist/kernel/chain.d.ts.map +1 -1
  17. package/dist/kernel/chain.js.map +1 -1
  18. package/dist/kernel/dashboard-observation.d.ts +15 -5
  19. package/dist/kernel/dashboard-observation.d.ts.map +1 -1
  20. package/dist/kernel/dashboard-observation.js.map +1 -1
  21. package/dist/products/activity-summary.d.ts +8 -0
  22. package/dist/products/activity-summary.d.ts.map +1 -0
  23. package/dist/products/activity-summary.js +101 -0
  24. package/dist/products/activity-summary.js.map +1 -0
  25. package/dist/products/activity-timeline.d.ts +4 -1
  26. package/dist/products/activity-timeline.d.ts.map +1 -1
  27. package/dist/products/activity-timeline.js +9 -1
  28. package/dist/products/activity-timeline.js.map +1 -1
  29. package/dist/products/dashboard-activity.d.ts +9 -0
  30. package/dist/products/dashboard-activity.d.ts.map +1 -0
  31. package/dist/products/dashboard-activity.js +119 -0
  32. package/dist/products/dashboard-activity.js.map +1 -0
  33. package/dist/products/dashboard-cli.d.ts +2 -1
  34. package/dist/products/dashboard-cli.d.ts.map +1 -1
  35. package/dist/products/dashboard-cli.js +17 -6
  36. package/dist/products/dashboard-cli.js.map +1 -1
  37. package/dist/products/dashboard-components.d.ts +10 -0
  38. package/dist/products/dashboard-components.d.ts.map +1 -0
  39. package/dist/products/dashboard-components.js +196 -0
  40. package/dist/products/dashboard-components.js.map +1 -0
  41. package/dist/products/dashboard-display-controls.d.ts.map +1 -1
  42. package/dist/products/dashboard-display-controls.js +43 -3
  43. package/dist/products/dashboard-display-controls.js.map +1 -1
  44. package/dist/products/dashboard-layout.d.ts +6 -0
  45. package/dist/products/dashboard-layout.d.ts.map +1 -0
  46. package/dist/products/dashboard-layout.js +61 -0
  47. package/dist/products/dashboard-layout.js.map +1 -0
  48. package/dist/products/dashboard-panels.d.ts +4 -0
  49. package/dist/products/dashboard-panels.d.ts.map +1 -1
  50. package/dist/products/dashboard-panels.js +321 -120
  51. package/dist/products/dashboard-panels.js.map +1 -1
  52. package/dist/products/dashboard-recap.d.ts +4 -0
  53. package/dist/products/dashboard-recap.d.ts.map +1 -0
  54. package/dist/products/dashboard-recap.js +43 -0
  55. package/dist/products/dashboard-recap.js.map +1 -0
  56. package/dist/products/dashboard-screen.d.ts +11 -3
  57. package/dist/products/dashboard-screen.d.ts.map +1 -1
  58. package/dist/products/dashboard-screen.js +224 -62
  59. package/dist/products/dashboard-screen.js.map +1 -1
  60. package/dist/products/dashboard-session-client.d.ts +6 -5
  61. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  62. package/dist/products/dashboard-session-client.js.map +1 -1
  63. package/dist/products/ecosystem-versions.d.ts +2 -0
  64. package/dist/products/ecosystem-versions.d.ts.map +1 -1
  65. package/extensions/activity-timeline.ts +7 -1
  66. package/extensions/approvals.ts +7 -0
  67. package/extensions/dashboard-live.ts +45 -5
  68. package/extensions/dashboard-observation.ts +1 -3
  69. package/extensions/delegate-chain.ts +2 -0
  70. package/extensions/delegation-artifacts.ts +34 -4
  71. package/extensions/delegation-operations.ts +12 -4
  72. package/extensions/delegation.ts +4 -0
  73. package/extensions/ecosystem-versions.ts +25 -3
  74. package/extensions/execute-child.ts +4 -0
  75. package/extensions/initiative-handoff.ts +59 -0
  76. package/extensions/initiative-runtime.ts +39 -1
  77. package/extensions/run-delegation.ts +2 -0
  78. package/extensions/runtime-snapshot.ts +8 -4
  79. package/extensions/session.ts +2 -2
  80. package/package.json +1 -1
  81. package/src/governance/approval-prompt.ts +7 -6
  82. package/src/governance/initiative-coordinator.ts +16 -0
  83. package/src/governance/permission-question.ts +108 -0
  84. package/src/kernel/chain.ts +1 -0
  85. package/src/kernel/dashboard-observation.ts +15 -1
  86. package/src/products/activity-summary.ts +101 -0
  87. package/src/products/activity-timeline.ts +11 -0
  88. package/src/products/dashboard-activity.ts +136 -0
  89. package/src/products/dashboard-cli.ts +29 -7
  90. package/src/products/dashboard-components.ts +219 -0
  91. package/src/products/dashboard-display-controls.ts +37 -3
  92. package/src/products/dashboard-layout.ts +71 -0
  93. package/src/products/dashboard-panels.ts +359 -145
  94. package/src/products/dashboard-recap.ts +48 -0
  95. package/src/products/dashboard-screen.ts +264 -68
  96. package/src/products/dashboard-session-client.ts +7 -1
  97. package/src/products/ecosystem-versions.ts +2 -0
@@ -54,6 +54,7 @@ export interface ChildSpec {
54
54
  operation_id?: string;
55
55
  definitionId?: string;
56
56
  task: string;
57
+ dashboardSummary?: string;
57
58
  agent?: string;
58
59
  tools?: string[];
59
60
  model?: string;
@@ -529,6 +530,7 @@ async function runOneDelegationImplementation(
529
530
  session,
530
531
  plan,
531
532
  agent: spec.agent,
533
+ dashboardSummary: spec.dashboardSummary,
532
534
  childId: ids.childId,
533
535
  executionId: ids.executionId,
534
536
  parentExecutionId: ids.parentExecutionId,
@@ -268,7 +268,7 @@ export function registerRuntimeSnapshot(
268
268
  }
269
269
  if (sequence !== bindSequence || session.reloadLifecycle !== lifecycle) return;
270
270
  lifecycle.runtimeSettlement = runtime;
271
- bindOperationFinals(session, sessionId, cwd, (reference) => {
271
+ bindOperationFinals(session, sessionId, cwd, (reference, description) => {
272
272
  if (
273
273
  bound?.sessionId === sessionId &&
274
274
  bound.cwd === cwd &&
@@ -279,11 +279,15 @@ export function registerRuntimeSnapshot(
279
279
  session.dashboardArtifacts ??= [];
280
280
  if (
281
281
  !session.dashboardArtifacts.some(
282
- (item) =>
283
- item.executionId === reference.executionId && item.manifest.sha256 === reference.manifest.sha256,
282
+ (item) => item.executionId === reference.executionId && item.sha256 === reference.manifest.sha256,
284
283
  )
285
284
  )
286
- session.dashboardArtifacts.push(reference);
285
+ session.dashboardArtifacts.push({
286
+ operationId: reference.operationId,
287
+ executionId: reference.executionId,
288
+ sha256: reference.manifest.sha256,
289
+ ...(description ? { description } : {}),
290
+ });
287
291
  if (session.dashboardArtifacts.length > 16) session.dashboardArtifacts.shift();
288
292
  try {
289
293
  pi.appendEntry?.("pi-daddy:operation-artifact:v1", reference);
@@ -1,6 +1,6 @@
1
1
  import type { InitiativeOperationBinding } from "./initiative-runtime.ts";
2
2
  import type { DashboardSourceSnapshot, DashboardContribution } from "../src/kernel/dashboard-observation.ts";
3
- import type { OperationArtifactRef } from "../src/kernel/operation-artifact.ts";
3
+ import type { DashboardSavedEvidence } from "../src/kernel/dashboard-observation.ts";
4
4
  import type { DashboardOwnerObservation } from "../src/kernel/dashboard-observation.ts";
5
5
  import type { EcosystemVersions } from "../src/products/ecosystem-versions.ts";
6
6
  import type { AutoModeReader } from "../src/kernel/auto-mode.ts";
@@ -152,7 +152,7 @@ export interface GrantsSession extends NativeSessionHost {
152
152
  refreshInitiative?: () => void;
153
153
  ecosystemVersions?: () => EcosystemVersions;
154
154
  dashboardLive?: () => { turn?: DashboardContribution; activity: DashboardContribution[] };
155
- dashboardArtifacts?: OperationArtifactRef[];
155
+ dashboardArtifacts?: DashboardSavedEvidence[];
156
156
  dashboardObservations?: () => Omit<DashboardOwnerObservation, "version" | "resources" | "capture"> | undefined;
157
157
  autoMode?: AutoModeReader;
158
158
  autoModeFailure?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-daddy",
3
- "version": "0.50.0",
3
+ "version": "0.52.0",
4
4
  "description": "Capability governance for pi sub-agents: spawn Agent Skills (SKILL.md) definitions whose allowed-tools becomes a grant that can only narrow going down a delegation tree, enforced by pi's own --tools allowlist, with an append-only ledger.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -14,6 +14,7 @@ import { randomUUID } from "node:crypto";
14
14
  import type { AutoModeReader } from "../kernel/auto-mode.ts";
15
15
  import { approvalKey, offeredScopes, type ApprovalPath, type ApprovalScope } from "../kernel/approval.ts";
16
16
  import type { Capability } from "../kernel/resolve.ts";
17
+ import { selectPermission } from "./permission-question.ts";
17
18
 
18
19
  /** The slice of pi's `ExtensionUIContext` this module needs. */
19
20
  export interface ApprovalUI {
@@ -40,6 +41,10 @@ export interface PromptRequest {
40
41
  path: ApprovalPath;
41
42
  /** Shown to the human for context. Never itself part of a key. */
42
43
  task?: string;
44
+ /** Operator-owned permission store and resolved workspace, for display in the parent UI only. */
45
+ project?: string;
46
+ workspace?: string;
47
+ recheckReason?: string;
43
48
  /** Trusted exact-scope identity; bound requests single-flight only with an identical binding. */
44
49
  bindingKey?: string;
45
50
  signal?: AbortSignal;
@@ -125,7 +130,6 @@ const interrupted = (request: PromptRequest, kind: "expired" | "aborted"): Promp
125
130
  async function selectApproval(
126
131
  options: ApprovalGateOptions,
127
132
  request: PromptRequest,
128
- title: string,
129
133
  labels: string[],
130
134
  ): Promise<string | undefined | PromptOutcome> {
131
135
  const timeout = typeof options.timeoutMs === "function" ? options.timeoutMs() : options.timeoutMs;
@@ -157,7 +161,7 @@ async function selectApproval(
157
161
  subject: request.subject,
158
162
  capability: request.capability,
159
163
  });
160
- const selection = options.ui.select(title, labels, { signal: controller.signal }).then((chosen) => {
164
+ const selection = selectPermission(options.ui, request, labels, controller.signal).then((chosen) => {
161
165
  settled = true;
162
166
  return chosen;
163
167
  });
@@ -263,13 +267,10 @@ export function createApprovalGate(
263
267
  }
264
268
  }
265
269
  const scopes = offeredScopes(request.path);
266
- const title =
267
- `grants: approve ${request.capability} for ${request.subject}?` +
268
- (request.task ? `\n task: ${request.task}` : "");
269
270
 
270
271
  let chosen: string | undefined | PromptOutcome;
271
272
  try {
272
- chosen = await selectApproval(options, request, title, [DENY_LABEL, ...scopes.map((s) => SCOPE_LABELS[s])]);
273
+ chosen = await selectApproval(options, request, [DENY_LABEL, ...scopes.map((s) => SCOPE_LABELS[s])]);
273
274
  } catch (error) {
274
275
  // A governance layer that errors must deny, not permit. This is a dialog malfunction, not a
275
276
  // person's answer — `kind: "error"` keeps it out of "declined".
@@ -325,6 +325,22 @@ export async function acquireInitiativeCoordinator(
325
325
  },
326
326
  };
327
327
  },
328
+ /** Bind a final to the only admitted attempt for this exact selected task revision. */
329
+ async handoffAttempt(identity: InitiativeTaskIdentity, selectedTask: InitiativeTask) {
330
+ if (request.recoveryOnly || identity.initiativeId !== record.initiativeId) return;
331
+ const observation = await this.observe(identity, selectedTask);
332
+ if (
333
+ observation.status !== "observed" ||
334
+ observation.execution !== "settled" ||
335
+ observation.reconciliationRequired
336
+ )
337
+ return;
338
+ const attempts = taskAt(selectedTask)?.attempts.filter((attempt) => attempt.state !== "not-admitted");
339
+ // A task with several admitted operations needs an explicit output choice.
340
+ if (attempts?.length !== 1) return;
341
+ await observation.assertCurrent();
342
+ return { attempt: structuredClone(attempts[0]!), assertCurrent: observation.assertCurrent };
343
+ },
328
344
  async pendingEffects() {
329
345
  const captured = revision;
330
346
  await assertCurrent();
@@ -0,0 +1,108 @@
1
+ import { basename } from "node:path";
2
+ import { stripVTControlCharacters } from "node:util";
3
+ import type { ApprovalUI, PromptRequest } from "./approval-prompt.ts";
4
+
5
+ const DETAILS = "View permission details";
6
+ const BACK = "Back to decision";
7
+ const NEXT = "Next page";
8
+ const PREVIOUS = "Previous page";
9
+
10
+ /** Only these strings belong on the terminal; the original values still identify the grant. */
11
+ function clean(text: string): string {
12
+ return stripVTControlCharacters(text.replace(/\r\n?/g, "\n"))
13
+ .replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069]/gu, " ")
14
+ .replace(/[\u2028\u2029]/gu, "\n");
15
+ }
16
+
17
+ function oneLine(value: string, limit: number): string {
18
+ const chars = [...value.trim().replace(/\s+/gu, " ")];
19
+ return chars.length <= limit
20
+ ? chars.join("")
21
+ : chars
22
+ .slice(0, limit - 1)
23
+ .join("")
24
+ .trimEnd() + "…";
25
+ }
26
+
27
+ function headline(request: PromptRequest): string {
28
+ const actions: Record<string, string> = {
29
+ "tool:bash": "run shell commands",
30
+ "tool:write": "write files",
31
+ "tool:edit": "edit files",
32
+ "tool:delegate": "delegate work to another agent",
33
+ };
34
+ const subject = request.path === "delegate" ? "this delegated agent" : oneLine(clean(request.subject), 80);
35
+ const action = actions[request.capability] ?? `use ${oneLine(clean(request.capability), 90)}`;
36
+ return `Allow ${subject} to ${action}?`;
37
+ }
38
+
39
+ function scopeHint(request: PromptRequest): string {
40
+ if (request.bindingKey) return "Remembered choices apply only to this exact request.";
41
+ return request.path === "delegate"
42
+ ? "A session choice also covers other unnamed delegated agents."
43
+ : "A remembered choice also covers other tasks for this agent.";
44
+ }
45
+
46
+ /** Render the full, untrusted brief in pages so choices stay reachable on a typical terminal. */
47
+ function detailLines(request: PromptRequest): string[] {
48
+ const rows = [
49
+ `Permission: ${clean(request.capability)}`,
50
+ `Agent: ${clean(request.subject)}`,
51
+ ...(request.project ? [`Permission project: ${clean(request.project)}`] : []),
52
+ ...(request.workspace ? [`Requested workspace: ${clean(request.workspace)}`] : []),
53
+ scopeHint(request),
54
+ ...(request.bindingKey ? ["Reuse requires the same task, tools, parent and bound context."] : []),
55
+ "",
56
+ "Requested task",
57
+ clean(request.task ?? "").trim() || "No task description supplied.",
58
+ ];
59
+ return rows
60
+ .join("\n")
61
+ .split("\n")
62
+ .flatMap((line) => {
63
+ const chunks = line.match(/.{1,58}(?:\s+|$)|.{1,58}/gu);
64
+ return chunks ? chunks.map((chunk) => chunk.trimEnd()) : [""];
65
+ });
66
+ }
67
+
68
+ /** Details are informational. The same decision and its original deadline stay in force across pages. */
69
+ export async function selectPermission(
70
+ ui: ApprovalUI,
71
+ request: PromptRequest,
72
+ labels: string[],
73
+ signal: AbortSignal,
74
+ ): Promise<string | undefined> {
75
+ const task = clean(request.task ?? "")
76
+ .split("\n")
77
+ .find((line) => line.trim());
78
+ const title = [
79
+ headline(request),
80
+ ...(task ? [`Requested task: ${oneLine(task, 115)}`] : []),
81
+ ...(request.project
82
+ ? [`Permission project: ${oneLine(clean(basename(request.project) || request.project), 60)}`]
83
+ : []),
84
+ ...(request.capability === "tool:bash" ? ["Shell access can change files and run other commands."] : []),
85
+ ...(request.recheckReason ? [request.recheckReason] : []),
86
+ scopeHint(request),
87
+ ].join("\n");
88
+ const choices = [...labels, DETAILS];
89
+ let lines: string[] | undefined;
90
+ let page = -1;
91
+ while (!signal.aborted) {
92
+ if (page < 0) {
93
+ const choice = await ui.select(title, choices, { signal });
94
+ if (choice !== DETAILS) return choice;
95
+ lines ??= detailLines(request);
96
+ page = 0;
97
+ } else {
98
+ const pages = Math.ceil(lines!.length / 8);
99
+ const title = [`Permission details · ${page + 1}/${pages}`, ...lines!.slice(page * 8, page * 8 + 8)].join("\n");
100
+ const options = [BACK, ...(page + 1 < pages ? [NEXT] : []), ...(page > 0 ? [PREVIOUS] : [])];
101
+ const nav = await ui.select(title, options, { signal });
102
+ if (nav === undefined || !options.includes(nav)) return undefined;
103
+ if (nav === BACK) page = -1;
104
+ else page += nav === NEXT ? 1 : -1;
105
+ }
106
+ }
107
+ return undefined;
108
+ }
@@ -155,6 +155,7 @@ export interface ChainStep {
155
155
  operation_id?: string;
156
156
  definitionId?: string;
157
157
  task: string;
158
+ dashboardSummary?: string;
158
159
  agent?: string;
159
160
  tools?: string[];
160
161
  model?: string;
@@ -46,6 +46,20 @@ export interface DashboardSourceSnapshot extends DashboardSourceUpdate {
46
46
  staleAfterMs: number;
47
47
  availability: "observed" | "closed";
48
48
  }
49
+ /** Session-local display metadata from the same elected child that published the reference. */
50
+ export interface DashboardResultDescription {
51
+ agent?: string;
52
+ summary?: string;
53
+ content: "answer" | "partial" | "record";
54
+ state: "not-started" | "uncertain" | "failed" | "settled" | "unknown";
55
+ observedAt: string;
56
+ }
57
+ export interface DashboardSavedEvidence {
58
+ operationId: string;
59
+ executionId: string;
60
+ sha256: string;
61
+ description?: DashboardResultDescription;
62
+ }
49
63
  export interface DashboardOwnerObservation {
50
64
  version: 1;
51
65
  sessionId: string;
@@ -57,7 +71,7 @@ export interface DashboardOwnerObservation {
57
71
  logicalOwnerId?: string;
58
72
  turn?: DashboardContribution;
59
73
  activity?: DashboardContribution[];
60
- artifacts?: Array<{ operationId: string; executionId: string; sha256: string }>;
74
+ artifacts?: DashboardSavedEvidence[];
61
75
  resources: { scope: "owner-process"; sampledAt: string; rssBytes: number; hostHealth: "unknown" };
62
76
  capture: { transcripts: boolean; diagnostics: boolean };
63
77
  }
@@ -0,0 +1,101 @@
1
+ const privateMarkers = [
2
+ /https?:\/\/|(?:^|[\s("'=])(?:\/|~\/|[A-Z]:[\\/])/i,
3
+ /[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,}/i,
4
+ /\b(?:[\da-f]{32,}|[A-Za-z\d_\-]{36,})\b/i,
5
+ /\b(?:Bearer\s+\S|(?:password|token|api[_ -]?key|secret)\s*[:=]|(?:sk-|ghp_|github_pat_|AKIA)[\w-]{8,})/i,
6
+ ];
7
+
8
+ /** Public display text is a separate field from the task, prompt and reasoning. */
9
+ export function safeDashboardSummary(value: unknown): string | undefined {
10
+ if (typeof value !== "string" || value.length > 160 || /[\p{Cc}\p{Cf}]/u.test(value)) return;
11
+ const line = value.trim().replace(/\s+/g, " ");
12
+ if (!line || privateMarkers.some((pattern) => pattern.test(line))) return;
13
+ return line;
14
+ }
15
+
16
+ export const dashboardSummaryDescription =
17
+ "Give this child a short purpose for the user's dashboard, e.g. 'Check that stale cache entries refresh'. " +
18
+ "Use public task terms only. Omit secrets, paths, IDs, links and private material. Display only.";
19
+
20
+ export function dashboardContentEnabled(env: NodeJS.ProcessEnv): boolean {
21
+ return (
22
+ !["off", "0"].includes(env.PI_DADDY_ACTIVITY_TIMELINE?.trim() ?? "") &&
23
+ !["off", "metadata-only"].includes(env.PI_DADDY_ACTIVITY_CONTENT?.trim() ?? "")
24
+ );
25
+ }
26
+
27
+ /** Only fixed descriptions cross the observation boundary for regular tools. */
28
+ export function toolPurpose(tool: string, args?: unknown): string {
29
+ const params = args && typeof args === "object" ? (args as Record<string, unknown>) : {};
30
+ if (tool === "bash" && typeof params.command === "string" && /^\s*npm\s+(?:test|run\s+test)\s*$/.test(params.command))
31
+ return "Run the project tests";
32
+ if (tool === "read" && typeof params.path === "string" && params.path.length <= 4096) {
33
+ const path = params.path.replaceAll("\\", "/");
34
+ if (/(^|\/)README(?:\.[^/]+)?$/i.test(path)) return "Read the project guide";
35
+ if (/(^|\/)SKILL\.md$/.test(path)) return "Read a skill's instructions";
36
+ if (/(^|\/)(?:tests?|__tests__)\/|(?:\.test|\.spec)\.[^/]+$/i.test(path)) return "Read a test file";
37
+ if (/(^|\/)\.principal\/reports\//.test(path)) return "Read a saved report";
38
+ }
39
+ if (tool === "principal_workflow") {
40
+ switch (params.action) {
41
+ case "prepare":
42
+ return "Prepare the next step";
43
+ case "inspect":
44
+ return "Check the state of a workflow step";
45
+ case "complete":
46
+ return "Record the result of a workflow step";
47
+ }
48
+ }
49
+ switch (tool) {
50
+ case "read":
51
+ return "Read a project file";
52
+ case "grep":
53
+ return "Search file contents";
54
+ case "find":
55
+ return "Find project files";
56
+ case "ls":
57
+ return "List files in a folder";
58
+ case "edit":
59
+ return "Edit a file";
60
+ case "write":
61
+ return "Write a file";
62
+ case "bash":
63
+ return "Run a shell command";
64
+ case "delegate": {
65
+ switch (params.agent) {
66
+ case "review":
67
+ return "Request an independent review";
68
+ case "test-review":
69
+ return "Ask a reviewer to check the tests";
70
+ case "investigate":
71
+ return "Ask a subagent to investigate";
72
+ case "build":
73
+ return "Ask a subagent to implement a change";
74
+ case "plan":
75
+ return "Ask a subagent to prepare a plan";
76
+ default:
77
+ return "Ask a subagent to work on a task";
78
+ }
79
+ }
80
+ case "delegate_all":
81
+ return "Assign tasks to multiple subagents";
82
+ case "delegate_chain":
83
+ return "Assign a sequence of tasks to subagents";
84
+ case "delegate_describe":
85
+ return "Check a subagent's instructions";
86
+ case "principal_workflow":
87
+ return "Manage a workflow step";
88
+ case "codemode":
89
+ return "Run a group of tool calls";
90
+ default:
91
+ return "Use a project tool";
92
+ }
93
+ }
94
+
95
+ export function observedPurpose(tool: string, args: unknown, allowSummary: boolean): string {
96
+ if (tool === "delegate" && allowSummary && args && typeof args === "object") {
97
+ const summary = safeDashboardSummary((args as Record<string, unknown>).dashboardSummary);
98
+ if (summary) return summary;
99
+ }
100
+ return toolPurpose(tool, args);
101
+ }
@@ -1,4 +1,5 @@
1
1
  /** Durable, local-only activity facts. Timeline events never infer skill compliance or provider reasoning. */
2
+ import { safeDashboardSummary } from "./activity-summary.ts";
2
3
  import { createHash, randomUUID } from "node:crypto";
3
4
  import { constants } from "node:fs";
4
5
  import { appendFile, mkdir, open, readFile, realpath, rename, writeFile } from "node:fs/promises";
@@ -52,6 +53,7 @@ export interface ActivityEvent {
52
53
  model?: string;
53
54
  thinking?: string;
54
55
  trigger?: ActivityTrigger;
56
+ dashboardSummary?: string;
55
57
  prompt?: ContentReference;
56
58
  final?: ContentReference;
57
59
  skill?: ActivitySkill;
@@ -75,8 +77,10 @@ export interface TimelineTask {
75
77
  model?: string;
76
78
  thinking?: string;
77
79
  trigger?: ActivityTrigger;
80
+ dashboardSummary?: string;
78
81
  prompt?: ContentReference;
79
82
  final?: ContentReference;
83
+ lastPurpose?: string;
80
84
  skills: TimelineSkill[];
81
85
  agents: Array<{ id: string; parentTaskId?: string; agent: string; state: string }>;
82
86
  }
@@ -146,6 +150,8 @@ function eventOf(value: unknown): ActivityEvent | null {
146
150
  (event.final && !validRef(event.final))
147
151
  )
148
152
  return null;
153
+ if (event.dashboardSummary !== undefined && safeDashboardSummary(event.dashboardSummary) !== event.dashboardSummary)
154
+ return null;
149
155
  if (
150
156
  event.skill &&
151
157
  (!validId(event.skill.name) ||
@@ -192,6 +198,7 @@ export function parseActivityTimeline(text: string): ActivityTimeline {
192
198
  if (event.cwd) task.cwd = event.cwd;
193
199
  }
194
200
  if (event.kind === "task_started") {
201
+ task.dashboardSummary = event.dashboardSummary;
195
202
  task.model = event.model;
196
203
  task.thinking = event.thinking;
197
204
  task.trigger = event.trigger;
@@ -199,6 +206,7 @@ export function parseActivityTimeline(text: string): ActivityTimeline {
199
206
  task.agent = event.agent ?? task.agent;
200
207
  task.parentTaskId = event.parentTaskId ?? task.parentTaskId;
201
208
  }
209
+ if (event.kind === "tool_started") task.lastPurpose = event.dashboardSummary;
202
210
  if (event.kind === "task_finished") {
203
211
  task.endedAt = event.at;
204
212
  task.final = event.final;
@@ -626,13 +634,16 @@ export class ActivityTimelineRecorder {
626
634
  prompt: string,
627
635
  model?: string,
628
636
  thinking?: string,
637
+ dashboardSummary?: string,
629
638
  ): Promise<void> {
630
639
  if (!this.enabled) return;
631
640
  this.taskId = taskId;
641
+ const purpose = this.contentEnabled && safeDashboardSummary(dashboardSummary);
632
642
  await this.append("task_started", {
633
643
  parentTaskId,
634
644
  agentId: taskId,
635
645
  agent,
646
+ ...(purpose ? { dashboardSummary: purpose } : {}),
636
647
  model,
637
648
  thinking,
638
649
  prompt: await this.content(prompt),
@@ -0,0 +1,136 @@
1
+ import type { DashboardContribution } from "../kernel/dashboard-observation.ts";
2
+ import type { TimelineTask } from "./activity-timeline.ts";
3
+ import { safeDashboardSummary, toolPurpose } from "./activity-summary.ts";
4
+ import type { DashboardItem } from "./dashboard-screen.ts";
5
+
6
+ const clean = (value: string) =>
7
+ value
8
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")
9
+ .replace(/[\p{Cc}\p{Cf}]/gu, " ")
10
+ .trim();
11
+
12
+ export function activityTaskTitle(task: TimelineTask): string {
13
+ const lastAction = task.lastEvent?.kind === "tool_started" || task.status !== "active";
14
+ const observed = lastAction
15
+ ? (safeDashboardSummary(task.lastPurpose) ?? (task.lastEvent?.tool ? toolPurpose(task.lastEvent.tool) : undefined))
16
+ : undefined;
17
+ const purpose = safeDashboardSummary(task.dashboardSummary) ?? observed;
18
+ if (purpose) return task.agent ? `${purpose} · ${clean(task.agent)}` : purpose;
19
+ if (task.agent) return `${clean(task.agent)} task`;
20
+ if (task.trigger?.type === "custom") return "Handle an extension request";
21
+ if (task.status === "finished") return "Pi finished its turn";
22
+ return task.status === "active" ? "Pi is working on your request" : "Pi handled your request";
23
+ }
24
+
25
+ /** Ledger entries retain authoritative state and identity. Only the same owner's matching execution may add a title. */
26
+ export function applyOwnerTaskTitles(items: DashboardItem[], tasks: TimelineTask[], rootId: string): DashboardItem[] {
27
+ const known = new Map(tasks.filter((task) => task.rootId === rootId && task.agent).map((task) => [task.id, task]));
28
+ return items.map((item) => {
29
+ const task = known.get(item.key);
30
+ return task && (task.dashboardSummary || task.lastPurpose) ? { ...item, label: activityTaskTitle(task) } : item;
31
+ });
32
+ }
33
+
34
+ interface Story {
35
+ events: DashboardContribution[];
36
+ label: string;
37
+ status: string;
38
+ group?: string;
39
+ calls: number;
40
+ legacy?: boolean;
41
+ }
42
+
43
+ /** Group only matching tool observations within a turn. Preserve failures, interleaving, and original records in Details. */
44
+ export function activityStoryItems(
45
+ events: DashboardContribution[],
46
+ generation: string,
47
+ disconnected: boolean,
48
+ ): DashboardItem[] {
49
+ const stories: Story[] = [];
50
+ const starts = new Map<string, Story>();
51
+ for (const event of events) {
52
+ const raw = clean(event.label);
53
+ const toolEvent = /^(.+): tool (start|end)$/.exec(raw);
54
+ if (!toolEvent) {
55
+ if (raw === "agent_start" || raw === "agent_end") starts.clear();
56
+ stories.push({
57
+ events: [event],
58
+ label: raw === "agent_start" ? "Pi started a turn" : raw === "agent_end" ? "Pi finished its turn" : raw,
59
+ status: "observed",
60
+ calls: 1,
61
+ });
62
+ continue;
63
+ }
64
+ const [, name, phase] = toolEvent;
65
+ const call = event.details?.find((line) => /^Call: \d+$/.test(line));
66
+ const key = call && `${name}:${call}`;
67
+ let story = phase === "end" && key ? starts.get(key) : undefined;
68
+ if (story) {
69
+ starts.delete(key!);
70
+ // A call finishing after a different action belongs at the time its result arrived.
71
+ stories.splice(stories.indexOf(story), 1);
72
+ story.events.push(event);
73
+ } else {
74
+ const purpose = event.details?.find((line) => line.startsWith("Purpose: "))?.slice(9);
75
+ story = {
76
+ events: [event],
77
+ label: safeDashboardSummary(purpose) ?? toolPurpose(name!),
78
+ status: "observed",
79
+ group: name,
80
+ calls: 1,
81
+ legacy: !key,
82
+ };
83
+ }
84
+ if (phase === "start" && key) starts.set(key, story);
85
+ story.status = event.state === "failed" ? "failed" : phase === "end" ? "finished" : "Started";
86
+ stories.push(story);
87
+ }
88
+ const grouped: Story[] = [];
89
+ for (const story of stories) {
90
+ const last = grouped.at(-1);
91
+ if (
92
+ last &&
93
+ story.legacy &&
94
+ last.legacy &&
95
+ story.group === last.group &&
96
+ story.label === last.label &&
97
+ story.status !== "failed" &&
98
+ last.status !== "failed"
99
+ ) {
100
+ // Older Pi observations have no call identity. Count raw records, never inferred commands.
101
+ last.events.push(...story.events);
102
+ last.status = "observed";
103
+ } else if (
104
+ last &&
105
+ !story.legacy &&
106
+ !last.legacy &&
107
+ story.group &&
108
+ story.group === last.group &&
109
+ story.status === "finished" &&
110
+ last.status === story.status &&
111
+ story.label === last.label
112
+ ) {
113
+ last.events.push(...story.events);
114
+ last.calls++;
115
+ } else grouped.push(story);
116
+ }
117
+ return grouped.reverse().map(({ events: raw, label, calls, status, legacy }) => ({
118
+ key: `activity:${generation}:${raw[0]!.id}`,
119
+ label: legacy && raw.length > 1 ? `${label} (${raw.length} events)` : calls > 1 ? `${label} (×${calls})` : label,
120
+ status: disconnected ? "last-observed" : status,
121
+ elapsed: "",
122
+ briefDetails: [
123
+ label,
124
+ ...(disconnected ? ["Last seen before the dashboard disconnected."] : []),
125
+ ...(status === "failed"
126
+ ? ["Pi reported an error."]
127
+ : status === "Started"
128
+ ? ["Pi reported starting this action. No finish is in these recent events."]
129
+ : []),
130
+ ],
131
+ details: raw.map(
132
+ (event) =>
133
+ `${event.details?.find((line) => line.startsWith("Observed: "))?.slice(10) ?? "Time unavailable"} · ${clean(event.label)}${event.state === "failed" ? " · error" : ""}`,
134
+ ),
135
+ }));
136
+ }