paseo-office 0.2.4 → 0.2.6

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.
@@ -0,0 +1,218 @@
1
+ import { z } from "zod";
2
+ import { ACTIVITY_KINDS, LOBBY, type ActivityKind, type ActivityStep } from "../shared/names.js";
3
+ import type { OfficeAgent } from "../shared/contracts.js";
4
+ import { agentTitle } from "../shared/model.js";
5
+ import {
6
+ DAY_MS,
7
+ LANE_STEPS_MAX,
8
+ TIMELINE_STATES,
9
+ isCommand,
10
+ isEdit,
11
+ type Timeline,
12
+ type TimelineLane,
13
+ type TimelineState,
14
+ } from "../shared/timeline.js";
15
+ import type { DirectoryView } from "./hub.js";
16
+
17
+ /** How long the office remembers, and the most marks it keeps: the oldest go first. */
18
+ export const TIMELINE_KEEP_MS = 8 * DAY_MS;
19
+ export const TIMELINE_MARKS_MAX = 40_000;
20
+
21
+ const STATES = [...TIMELINE_STATES, "off"] as const;
22
+ type Seen = (typeof STATES)[number];
23
+
24
+ /**
25
+ * One thing seen of an agent at a time: its state changed (`s`, "off" when the office stopped
26
+ * watching it), it started a tool call (`k`), or its turns cost more (`c`, the US dollars added).
27
+ */
28
+ const MarkSchema = z.object({
29
+ t: z.number(),
30
+ a: z.string(),
31
+ s: z.enum(STATES).optional(),
32
+ k: z.enum(ACTIVITY_KINDS).optional(),
33
+ c: z.number().optional(),
34
+ });
35
+ type Mark = z.output<typeof MarkSchema>;
36
+
37
+ const WhoSchema = z.object({ name: z.string(), team: z.string(), provider: z.string() });
38
+
39
+ export const TimelineFileSchema = z.object({
40
+ version: z.literal(1),
41
+ who: z.record(z.string(), WhoSchema),
42
+ marks: z.array(MarkSchema),
43
+ });
44
+ export type TimelineFile = z.output<typeof TimelineFileSchema>;
45
+
46
+ export interface TimelinePorts {
47
+ now(): number;
48
+ /** Called with the whole log after each change; the caller writes it when it sees fit. */
49
+ save(file: TimelineFile): void;
50
+ }
51
+
52
+ export interface TimelineLog {
53
+ /** The office as the directory reports it; null when the office stops watching. */
54
+ view(view: DirectoryView | null): void;
55
+ /** The tool call each running agent is at, as the activity reads see it. */
56
+ steps(doing: Readonly<Record<string, ActivityStep>>): void;
57
+ read(from: number, to: number): Timeline;
58
+ }
59
+
60
+ function seenOf(agent: OfficeAgent): Seen {
61
+ if (agent.status === "closed") return "off";
62
+ if (agent.status === "error") return "fail";
63
+ if (agent.permissions.length > 0) return "wait";
64
+ return agent.status === "idle" ? "rest" : "work";
65
+ }
66
+
67
+ interface Building {
68
+ lane: TimelineLane;
69
+ state: Seen;
70
+ since: number;
71
+ cost: number | null;
72
+ }
73
+
74
+ /**
75
+ * What the office saw each agent do, kept for eight days. It sees only while an office is open:
76
+ * the time between is a gap in every lane, not a rest. `kept` is the file of an earlier run; its
77
+ * agents are closed at its last mark, since nobody saw when they stopped.
78
+ */
79
+ export function createTimelineLog(ports: TimelinePorts, kept: TimelineFile | null): TimelineLog {
80
+ const who: TimelineFile["who"] = { ...kept?.who };
81
+ let marks: Mark[] = kept?.marks.filter((mark) => mark.t >= ports.now() - TIMELINE_KEEP_MS) ?? [];
82
+ const states = new Map<string, Seen>();
83
+ const costs = new Map<string, number>();
84
+ const calls = new Map<string, string>();
85
+ for (const mark of marks) if (mark.s !== undefined) states.set(mark.a, mark.s);
86
+ const last = marks.at(-1)?.t ?? 0;
87
+ for (const [id, state] of states) if (state !== "off") marks.push({ t: last, a: id, s: "off" });
88
+ states.clear();
89
+
90
+ function saved(): void {
91
+ if (marks.length > TIMELINE_MARKS_MAX) marks = marks.slice(-TIMELINE_MARKS_MAX);
92
+ const listed = new Set(marks.map((mark) => mark.a));
93
+ for (const id of Object.keys(who)) if (!listed.has(id)) delete who[id];
94
+ ports.save({ version: 1, who, marks });
95
+ }
96
+
97
+ function seeAgent(agent: OfficeAgent, team: string, t: number): boolean {
98
+ let changed = false;
99
+ const state = seenOf(agent);
100
+ if ((states.get(agent.id) ?? "off") !== state) {
101
+ states.set(agent.id, state);
102
+ marks.push({ t, a: agent.id, s: state });
103
+ changed = true;
104
+ }
105
+ if (state !== "off" || changed) {
106
+ who[agent.id] = { name: agentTitle(agent), team, provider: agent.provider };
107
+ }
108
+ const cost = agent.costUsd;
109
+ if (cost === undefined) return changed;
110
+ const before = costs.get(agent.id);
111
+ costs.set(agent.id, cost);
112
+ // The first reading is what the agent cost before the office looked: not this range's.
113
+ if (before === undefined || cost <= before) return changed;
114
+ marks.push({ t, a: agent.id, c: cost - before });
115
+ return true;
116
+ }
117
+
118
+ function stopWatching(ids: Iterable<string>, t: number): boolean {
119
+ let changed = false;
120
+ for (const id of ids) {
121
+ if ((states.get(id) ?? "off") === "off") continue;
122
+ states.set(id, "off");
123
+ calls.delete(id);
124
+ marks.push({ t, a: id, s: "off" });
125
+ changed = true;
126
+ }
127
+ return changed;
128
+ }
129
+
130
+ return {
131
+ view(view) {
132
+ const t = ports.now();
133
+ if (view === null) {
134
+ if (stopWatching([...states.keys()], t)) saved();
135
+ costs.clear();
136
+ return;
137
+ }
138
+ const teams = new Map(view.workspaces.map((workspace) => [workspace.id, workspace.name]));
139
+ let changed = false;
140
+ const here = new Set<string>();
141
+ for (const agent of view.agents) {
142
+ here.add(agent.id);
143
+ const team = (agent.workspaceId && teams.get(agent.workspaceId)) || LOBBY;
144
+ if (seeAgent(agent, team, t)) changed = true;
145
+ }
146
+ const gone = [...states.keys()].filter((id) => !here.has(id));
147
+ if (stopWatching(gone, t)) changed = true;
148
+ if (changed) saved();
149
+ },
150
+ steps(doing) {
151
+ const t = ports.now();
152
+ let changed = false;
153
+ for (const [id, step] of Object.entries(doing)) {
154
+ if (calls.get(id) === step.key || states.get(id) === undefined) continue;
155
+ calls.set(id, step.key);
156
+ marks.push({ t, a: id, k: step.kind });
157
+ changed = true;
158
+ }
159
+ if (changed) saved();
160
+ },
161
+ read(from, to) {
162
+ const end = Math.min(to, ports.now());
163
+ const building = new Map<string, Building>();
164
+ const close = (lane: Building, at: number) => {
165
+ const start = Math.max(lane.since, from);
166
+ const stop = Math.min(at, end);
167
+ if (lane.state !== "off" && stop > start) {
168
+ lane.lane.spans.push({ from: start, to: stop, state: lane.state as TimelineState });
169
+ }
170
+ };
171
+ for (const mark of marks) {
172
+ if (mark.t > end) break;
173
+ let lane = building.get(mark.a);
174
+ if (lane === undefined) {
175
+ const known = who[mark.a] ?? { name: mark.a, team: LOBBY, provider: "" };
176
+ lane = {
177
+ lane: {
178
+ id: mark.a,
179
+ ...known,
180
+ spans: [],
181
+ steps: [],
182
+ edits: 0,
183
+ commands: 0,
184
+ costUsd: null,
185
+ },
186
+ state: "off",
187
+ since: 0,
188
+ cost: null,
189
+ };
190
+ building.set(mark.a, lane);
191
+ }
192
+ if (mark.s !== undefined) {
193
+ close(lane, mark.t);
194
+ lane.state = mark.s;
195
+ lane.since = mark.t;
196
+ }
197
+ if (mark.t < from) continue;
198
+ if (mark.k !== undefined) countStep(lane.lane, mark.t, mark.k);
199
+ if (mark.c !== undefined) lane.lane.costUsd = (lane.lane.costUsd ?? 0) + mark.c;
200
+ }
201
+ const lanes: TimelineLane[] = [];
202
+ for (const lane of building.values()) {
203
+ close(lane, end);
204
+ if (lane.lane.spans.length === 0) continue;
205
+ lane.lane.steps = lane.lane.steps.slice(-LANE_STEPS_MAX);
206
+ lanes.push(lane.lane);
207
+ }
208
+ lanes.sort((a, b) => a.team.localeCompare(b.team) || a.name.localeCompare(b.name));
209
+ return { from, to: end, lanes };
210
+ },
211
+ };
212
+ }
213
+
214
+ function countStep(lane: TimelineLane, at: number, kind: ActivityKind): void {
215
+ lane.steps.push({ at, kind });
216
+ if (isEdit(kind)) lane.edits += 1;
217
+ if (isCommand(kind)) lane.commands += 1;
218
+ }
@@ -0,0 +1,168 @@
1
+ import { z } from "zod";
2
+ import type { OfficeAgent } from "../shared/contracts.js";
3
+ import { agentTitle } from "../shared/model.js";
4
+ import { LOBBY } from "../shared/names.js";
5
+ import {
6
+ VAULT_HITS_MAX,
7
+ VAULT_MESSAGES_MAX,
8
+ VAULT_TALKS_MAX,
9
+ VAULT_TEXT_MAX,
10
+ VaultMessageSchema,
11
+ promptReport,
12
+ searchWords,
13
+ snippetOf,
14
+ type PromptReport,
15
+ type VaultHit,
16
+ type VaultTalk,
17
+ } from "../shared/vault.js";
18
+ import { errorMessage } from "./errors.js";
19
+ import type { DirectoryView } from "./hub.js";
20
+
21
+ /** How many of an agent's newest timeline items are read after each of its turns. */
22
+ export const VAULT_TAIL_LIMIT = 80;
23
+
24
+ const TalkSchema = z.object({
25
+ name: z.string(),
26
+ team: z.string(),
27
+ /** The last timeline sequence number read: what comes after is new. */
28
+ seq: z.number(),
29
+ messages: z.array(VaultMessageSchema),
30
+ });
31
+ type Talk = z.output<typeof TalkSchema>;
32
+
33
+ export const VaultFileSchema = z.object({
34
+ version: z.literal(1),
35
+ talks: z.record(z.string(), TalkSchema),
36
+ });
37
+ export type VaultFile = z.output<typeof VaultFileSchema>;
38
+
39
+ /** A timeline entry as the vault reads it: when, where in the timeline, and the item. */
40
+ export interface VaultEntry {
41
+ at: number;
42
+ seq: number;
43
+ item: { type: string; text?: unknown };
44
+ }
45
+
46
+ export interface VaultPorts {
47
+ /** The newest entries of an agent's timeline, oldest first. */
48
+ tail(agentId: string): Promise<readonly VaultEntry[]>;
49
+ /** Whether the owner has turned the vault on; off, nothing is read or kept. */
50
+ on(): boolean;
51
+ save(file: VaultFile): void;
52
+ log(message: string): void;
53
+ }
54
+
55
+ export interface Vault {
56
+ /** The office as the directory reports it; an agent seen for the first time, or whose turn ended, is read. */
57
+ view(view: DirectoryView | null): void;
58
+ search(query: string): VaultHit[];
59
+ talk(agentId: string): VaultTalk | null;
60
+ /** The prompts sent since `from` against the prompt helper's rules. */
61
+ report(from: number): PromptReport;
62
+ /** Resolves when every read asked for so far has ended. */
63
+ settled(): Promise<void>;
64
+ }
65
+
66
+ function cut(text: string): string {
67
+ return text.length > VAULT_TEXT_MAX ? `${text.slice(0, VAULT_TEXT_MAX - 1)}…` : text;
68
+ }
69
+
70
+ function lastAt(talk: Talk): number {
71
+ return talk.messages.at(-1)?.at ?? 0;
72
+ }
73
+
74
+ /**
75
+ * What was said in each conversation, kept on the host after the agent is gone: the prompts and
76
+ * the replies, not the tool calls. It reads an agent's timeline when it first sees the agent and
77
+ * after each of its turns, so it holds what was said while an office was open.
78
+ */
79
+ export function createVault(ports: VaultPorts, kept: VaultFile | null): Vault {
80
+ const talks = new Map<string, Talk>(Object.entries(kept?.talks ?? {}));
81
+ const resting = new Map<string, boolean>();
82
+ let chain: Promise<void> = Promise.resolve();
83
+
84
+ function saved(): void {
85
+ if (talks.size > VAULT_TALKS_MAX) {
86
+ const oldest = [...talks].sort((a, b) => lastAt(a[1]) - lastAt(b[1]));
87
+ for (const [id] of oldest.slice(0, talks.size - VAULT_TALKS_MAX)) talks.delete(id);
88
+ }
89
+ ports.save({ version: 1, talks: Object.fromEntries(talks) });
90
+ }
91
+
92
+ async function read(agent: OfficeAgent, team: string): Promise<void> {
93
+ const entries = await ports.tail(agent.id);
94
+ const talk = talks.get(agent.id) ?? { name: "", team, seq: -1, messages: [] };
95
+ let added = false;
96
+ for (const entry of entries) {
97
+ const { type, text } = entry.item;
98
+ if (entry.seq <= talk.seq) continue;
99
+ talk.seq = entry.seq;
100
+ if ((type !== "user_message" && type !== "assistant_message") || typeof text !== "string") {
101
+ continue;
102
+ }
103
+ if (text.trim() === "") continue;
104
+ const role = type === "user_message" ? "user" : "assistant";
105
+ talk.messages.push({ at: entry.at, role, text: cut(text) });
106
+ added = true;
107
+ }
108
+ if (!added) return;
109
+ talk.name = agentTitle(agent);
110
+ talk.team = team;
111
+ if (talk.messages.length > VAULT_MESSAGES_MAX) {
112
+ talk.messages = talk.messages.slice(-VAULT_MESSAGES_MAX);
113
+ }
114
+ talks.set(agent.id, talk);
115
+ saved();
116
+ }
117
+
118
+ return {
119
+ view(view) {
120
+ if (view === null || !ports.on()) {
121
+ // Seen again later, each agent is read again: what it said meanwhile is then new.
122
+ resting.clear();
123
+ return;
124
+ }
125
+ const teams = new Map(view.workspaces.map((workspace) => [workspace.id, workspace.name]));
126
+ for (const agent of view.agents) {
127
+ const rests = agent.status === "idle" || agent.status === "error";
128
+ const before = resting.get(agent.id);
129
+ resting.set(agent.id, rests);
130
+ if (before !== undefined && !(rests && !before)) continue;
131
+ const team = (agent.workspaceId && teams.get(agent.workspaceId)) || LOBBY;
132
+ chain = chain
133
+ .then(() => read(agent, team))
134
+ .catch((error: unknown) =>
135
+ ports.log(`[office] history of ${agent.id}: ${errorMessage(error)}`),
136
+ );
137
+ }
138
+ },
139
+ search(query) {
140
+ const words = searchWords(query);
141
+ const hits: VaultHit[] = [];
142
+ for (const [agentId, talk] of talks) {
143
+ for (const message of talk.messages) {
144
+ const snippet = snippetOf(message.text, words);
145
+ if (snippet === null) continue;
146
+ const { at, role } = message;
147
+ hits.push({ agentId, name: talk.name, team: talk.team, at, role, snippet });
148
+ }
149
+ }
150
+ return hits.sort((a, b) => b.at - a.at).slice(0, VAULT_HITS_MAX);
151
+ },
152
+ talk(agentId) {
153
+ const talk = talks.get(agentId);
154
+ if (talk === undefined) return null;
155
+ return { agentId, name: talk.name, team: talk.team, messages: talk.messages };
156
+ },
157
+ report(from) {
158
+ const prompts: string[] = [];
159
+ for (const talk of talks.values()) {
160
+ for (const message of talk.messages) {
161
+ if (message.role === "user" && message.at >= from) prompts.push(message.text);
162
+ }
163
+ }
164
+ return promptReport(prompts);
165
+ },
166
+ settled: () => chain,
167
+ };
168
+ }
@@ -3,6 +3,8 @@ import { AppearanceSchema } from "./appearance.js";
3
3
  import { WORDS_LANGUAGES } from "./scene-language.js";
4
4
  import { defineRpc, defineSubscription } from "@getpaseo/plugin";
5
5
  import { PlanUsageSchema } from "./plan-usage.js";
6
+ import { TimelineSchema } from "./timeline.js";
7
+ import { PromptReportSchema, VaultHitSchema, VaultTalkSchema } from "./vault.js";
6
8
  import { z } from "zod";
7
9
  // In their own file, so code that needs only a name does not load the schemas.
8
10
  import { ACTIVITY_KINDS, TEST_RESULTS } from "./names.js";
@@ -797,6 +799,43 @@ export const planUsageRpc = defineRpc({
797
799
  ]),
798
800
  });
799
801
 
802
+ /**
803
+ * What the office saw each agent do between two times (epoch ms), a lane per agent. It holds
804
+ * what was seen while an office was open, for the last eight days.
805
+ */
806
+ export const timelineRpc = defineRpc({
807
+ name: "office.timeline.request",
808
+ input: z.object({ from: z.number(), to: z.number() }),
809
+ output: z.union([
810
+ z.object({ ok: z.literal(true), timeline: TimelineSchema }),
811
+ z.object({ ok: z.literal(false), problem: z.string() }),
812
+ ]),
813
+ });
814
+
815
+ /**
816
+ * The history vault. `on` false means the owner has it off: nothing is kept and nothing found.
817
+ * A search answers with the newest messages that hold every word of the query.
818
+ */
819
+ export const vaultSearchRpc = defineRpc({
820
+ name: "office.vault.search.request",
821
+ input: z.object({ query: z.string().max(200) }),
822
+ output: z.object({ on: z.boolean(), hits: z.array(VaultHitSchema) }),
823
+ });
824
+
825
+ /** One kept conversation; null when the vault has none for this agent. */
826
+ export const vaultTalkRpc = defineRpc({
827
+ name: "office.vault.talk.request",
828
+ input: z.object({ agentId: z.string() }),
829
+ output: z.object({ talk: VaultTalkSchema.nullable() }),
830
+ });
831
+
832
+ /** The last seven days' prompts against the prompt helper's rules, worked out on the host. */
833
+ export const vaultReportRpc = defineRpc({
834
+ name: "office.vault.report.request",
835
+ input: z.object({}),
836
+ output: z.object({ on: z.boolean(), report: PromptReportSchema }),
837
+ });
838
+
800
839
  export const WriterModesSchema = z.object({
801
840
  /** The provider the writer would start on now, by its label. */
802
841
  provider: z.string(),
@@ -77,6 +77,7 @@ const HostValuesSchema = z.object({
77
77
  // A plan this build does not know (a later build's, or a hand edit) reads as the company floor.
78
78
  floorPlan: z.enum(FLOOR_PLANS).default("pro").catch("pro"),
79
79
  streamerMode: z.boolean().default(true),
80
+ historyVault: z.boolean().default(false),
80
81
  stickyNotes: z.string().max(STICKY_NOTES_TEXT_MAX).default(""),
81
82
  jiraProjects: z.string().default(""),
82
83
  sentryOrg: z.string().default(""),
@@ -143,7 +144,9 @@ const SUNDAY_TO_THURSDAY = [0, 1, 2, 3, 4];
143
144
  * the 3D floor's plan: `pro` the company floor, `cozy` one open room, or `hq` headquarters.
144
145
  * `streamerMode` on (the default) keeps file names, commands and sites out of what the office
145
146
  * sends to the floor; off, a person's bubble names what they are at. `stickyNotes` are the
146
- * owner's notes on the 3D whiteboard, with `;` between them. `jiraProjects`
147
+ * owner's notes on the 3D whiteboard, with `;` between them. `historyVault` on has the office
148
+ * keep what is said in each conversation in a file on the host; it is off until the owner turns
149
+ * it on. `jiraProjects`
147
150
  * and `sentryProjects` are the comma separated projects checked for incidents, `sentryOrg` their
148
151
  * Sentry organisation and `sentryUrl` the Sentry the token is sent to.
149
152
  */
@@ -0,0 +1,177 @@
1
+ import { z } from "zod";
2
+ import { ACTIVITY_KINDS, type ActivityKind } from "./names.js";
3
+
4
+ /** What an agent is at, as the timeline draws it: at work, waiting for the user, resting, stopped on an error. */
5
+ export const TIMELINE_STATES = ["work", "wait", "rest", "fail"] as const;
6
+ export type TimelineState = (typeof TIMELINE_STATES)[number];
7
+
8
+ const SpanSchema = z.object({ from: z.number(), to: z.number(), state: z.enum(TIMELINE_STATES) });
9
+ export type TimelineSpan = z.output<typeof SpanSchema>;
10
+
11
+ const StepSchema = z.object({ at: z.number(), kind: z.enum(ACTIVITY_KINDS) });
12
+ export type TimelineStep = z.output<typeof StepSchema>;
13
+
14
+ /** The most steps of one lane that are sent: the newest. The counts cover them all. */
15
+ export const LANE_STEPS_MAX = 600;
16
+
17
+ export const TimelineLaneSchema = z.object({
18
+ id: z.string(),
19
+ name: z.string(),
20
+ team: z.string(),
21
+ provider: z.string(),
22
+ /** In order, none overlapping; a time the office was not watching has no span. */
23
+ spans: z.array(SpanSchema),
24
+ steps: z.array(StepSchema),
25
+ /** Tool calls in the range by what they were for: files changed, commands run. */
26
+ edits: z.number(),
27
+ commands: z.number(),
28
+ /** What the agent's turns cost in the range; null when its provider says no cost. */
29
+ costUsd: z.number().nullable(),
30
+ });
31
+ export type TimelineLane = z.output<typeof TimelineLaneSchema>;
32
+
33
+ export const TimelineSchema = z.object({
34
+ from: z.number(),
35
+ to: z.number(),
36
+ lanes: z.array(TimelineLaneSchema),
37
+ });
38
+ export type Timeline = z.output<typeof TimelineSchema>;
39
+
40
+ const HOUR = 3_600_000;
41
+ export const DAY_MS = 24 * HOUR;
42
+ export const TIMELINE_RANGES = [
43
+ { id: "1h", label: "1 hour", ms: HOUR },
44
+ { id: "6h", label: "6 hours", ms: 6 * HOUR },
45
+ { id: "24h", label: "24 hours", ms: DAY_MS },
46
+ ] as const;
47
+ export type TimelineRange = (typeof TIMELINE_RANGES)[number]["id"];
48
+
49
+ /** How many times faster than the clock a replay runs. */
50
+ export const REPLAY_SPEEDS = [30, 60, 120] as const;
51
+ export type ReplaySpeed = (typeof REPLAY_SPEEDS)[number];
52
+
53
+ const EDITS: ReadonlySet<ActivityKind> = new Set(["edit", "write"]);
54
+ const COMMANDS: ReadonlySet<ActivityKind> = new Set(["command", "test", "deploy"]);
55
+ export const isEdit = (kind: ActivityKind) => EDITS.has(kind);
56
+ export const isCommand = (kind: ActivityKind) => COMMANDS.has(kind);
57
+
58
+ /** What the agent was at then; null while the office was not watching it. */
59
+ export function stateAt(lane: TimelineLane, at: number): TimelineState | null {
60
+ return lane.spans.find((span) => span.from <= at && at < span.to)?.state ?? null;
61
+ }
62
+
63
+ // How long a tool call stays what the agent "is at" in a replay: the reads are 5 s apart.
64
+ const STEP_SHOWN_MS = 60_000;
65
+
66
+ const KIND_WORDS: Readonly<Record<ActivityKind, string>> = {
67
+ read: "reading",
68
+ search: "searching",
69
+ skill: "reading a skill",
70
+ edit: "editing",
71
+ write: "writing a file",
72
+ command: "running a command",
73
+ web: "on the web",
74
+ tool: "using a tool",
75
+ subagent: "handing work to a sub-agent",
76
+ plan: "planning",
77
+ test: "running tests",
78
+ commit: "committing",
79
+ push: "pushing",
80
+ deploy: "deploying",
81
+ };
82
+ const STATE_WORDS: Readonly<Record<TimelineState, string>> = {
83
+ work: "at work",
84
+ wait: "waiting for you",
85
+ rest: "resting",
86
+ fail: "stopped on an error",
87
+ };
88
+
89
+ /** What the agent was doing then, in a few words. */
90
+ export function doingAt(lane: TimelineLane, at: number): string {
91
+ const state = stateAt(lane, at);
92
+ if (state === null) return "not watched";
93
+ if (state !== "work") return STATE_WORDS[state];
94
+ // (no findLast: the phone's engine lacks it)
95
+ let kind: ActivityKind | null = null;
96
+ for (const step of lane.steps) {
97
+ if (step.at > at) break;
98
+ if (at - step.at < STEP_SHOWN_MS) kind = step.kind;
99
+ }
100
+ return kind === null ? STATE_WORDS.work : KIND_WORDS[kind];
101
+ }
102
+
103
+ /** "3 h 20 min", "45 min", "under a minute". */
104
+ export function durationText(ms: number): string {
105
+ const minutes = Math.round(ms / 60_000);
106
+ if (minutes < 1) return "under a minute";
107
+ if (minutes < 60) return `${minutes} min`;
108
+ const rest = minutes % 60;
109
+ return rest === 0 ? `${Math.floor(minutes / 60)} h` : `${Math.floor(minutes / 60)} h ${rest} min`;
110
+ }
111
+
112
+ export interface WeekRecap {
113
+ /** Time at work, of every agent together. */
114
+ workMs: number;
115
+ /** Turns started: a rest, an error or an unwatched time that turned into work. */
116
+ prompts: number;
117
+ edits: number;
118
+ commands: number;
119
+ /** Null when no provider said a cost. */
120
+ costUsd: number | null;
121
+ /** The team with the most time at work; null when nobody worked. */
122
+ busiestTeam: string | null;
123
+ /** Time at work in each of the 24 hours ending at `to`, oldest first. */
124
+ days: { from: number; workMs: number }[];
125
+ }
126
+
127
+ function overlap(span: TimelineSpan, from: number, to: number): number {
128
+ return Math.max(0, Math.min(span.to, to) - Math.max(span.from, from));
129
+ }
130
+
131
+ function promptsOf(lane: TimelineLane): number {
132
+ let prompts = 0;
133
+ lane.spans.forEach((span, index) => {
134
+ if (span.state !== "work") return;
135
+ const before = lane.spans[index - 1];
136
+ // Work straight after a wait is the same turn going on: the user answered, nobody prompted.
137
+ const sameTurn = before !== undefined && before.state === "wait" && before.to === span.from;
138
+ if (!sameTurn) prompts += 1;
139
+ });
140
+ return prompts;
141
+ }
142
+
143
+ /** A timeline's totals, with its time at work in days that end at the timeline's end. */
144
+ export function weekRecap(timeline: Timeline): WeekRecap {
145
+ const days: WeekRecap["days"] = [];
146
+ for (let from = timeline.to - DAY_MS; from >= timeline.from; from -= DAY_MS) {
147
+ days.unshift({ from, workMs: 0 });
148
+ }
149
+ const byTeam = new Map<string, number>();
150
+ let costUsd: number | null = null;
151
+ let workMs = 0;
152
+ for (const lane of timeline.lanes) {
153
+ if (lane.costUsd !== null) costUsd = (costUsd ?? 0) + lane.costUsd;
154
+ for (const span of lane.spans) {
155
+ if (span.state !== "work") continue;
156
+ const worked = span.to - span.from;
157
+ workMs += worked;
158
+ byTeam.set(lane.team, (byTeam.get(lane.team) ?? 0) + worked);
159
+ for (const day of days) day.workMs += overlap(span, day.from, day.from + DAY_MS);
160
+ }
161
+ }
162
+ let busiestTeam: string | null = null;
163
+ for (const [team, worked] of byTeam) {
164
+ if (busiestTeam === null || worked > (byTeam.get(busiestTeam) ?? 0)) busiestTeam = team;
165
+ }
166
+ const sum = (pick: (lane: TimelineLane) => number) =>
167
+ timeline.lanes.reduce((total, lane) => total + pick(lane), 0);
168
+ return {
169
+ workMs,
170
+ prompts: sum(promptsOf),
171
+ edits: sum((lane) => lane.edits),
172
+ commands: sum((lane) => lane.commands),
173
+ costUsd,
174
+ busiestTeam,
175
+ days,
176
+ };
177
+ }