paseo-office 0.2.1 → 0.2.3

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.
@@ -14,6 +14,8 @@ export interface JiraEnv {
14
14
  baseUrl: string;
15
15
  email: string;
16
16
  token: string;
17
+ /** What a refused token's message names; the environment's variable when absent. */
18
+ tokenVariable?: string;
17
19
  }
18
20
 
19
21
  /** Jira's site and sign-in from the daemon's environment; null unless all three are set. */
@@ -70,19 +72,29 @@ function jqlTime(since: number, timeZone: string): string {
70
72
  return `${day} ${parts.get("hour")}:${parts.get("minute")}`;
71
73
  }
72
74
 
75
+ function jiraTracker(env: JiraEnv, fetchFn: typeof fetch): Tracker {
76
+ const basic = Buffer.from(`${env.email}:${env.token}`).toString("base64");
77
+ return {
78
+ name: "Jira",
79
+ tokenVariable: env.tokenVariable ?? "ATLASSIAN_API_TOKEN",
80
+ headers: { Authorization: `Basic ${basic}` },
81
+ fetchFn,
82
+ };
83
+ }
84
+
85
+ /** One signed-in request, to tell whether Jira takes the sign-in. Rejects with a `TrackerProblem`. */
86
+ export async function probeJira(env: JiraEnv, fetchFn: typeof fetch = fetch): Promise<void> {
87
+ const tracker = jiraTracker(env, fetchFn);
88
+ await getJson({ tracker, url: `${env.baseUrl}/rest/api/3/myself`, schema: MyselfSchema });
89
+ }
90
+
73
91
  /** New bugs in `projects`, keys already checked against the settings' pattern. */
74
92
  export function createJiraReader(
75
93
  env: JiraEnv,
76
94
  projects: string[],
77
95
  fetchFn: typeof fetch = fetch,
78
96
  ): TrackerReader {
79
- const basic = Buffer.from(`${env.email}:${env.token}`).toString("base64");
80
- const tracker: Tracker = {
81
- name: "Jira",
82
- tokenVariable: "ATLASSIAN_API_TOKEN",
83
- headers: { Authorization: `Basic ${basic}` },
84
- fetchFn,
85
- };
97
+ const tracker = jiraTracker(env, fetchFn);
86
98
  const api = `${env.baseUrl}/rest/api/3`;
87
99
 
88
100
  async function read(since: number): Promise<FoundIssue[]> {
@@ -1,10 +1,11 @@
1
1
  import type { IncidentSource } from "../shared/contracts.js";
2
2
  import { JIRA_KEY, parseKeys, SENTRY_SLUG } from "../shared/settings.js";
3
3
  import type { TrackerReader } from "./incidents-http.js";
4
- import { createJiraReader, jiraEnv } from "./incidents-jira.js";
5
- import { createSentryReader, sentryToken } from "./incidents-sentry.js";
4
+ import { createJiraReader } from "./incidents-jira.js";
5
+ import { createSentryReader } from "./incidents-sentry.js";
6
6
  import type { OfficeCadence, OfficeSchedules } from "./local-schedules.js";
7
7
  import { createScheduleFollower, type OfficeSchedule } from "./schedule-follower.js";
8
+ import type { TrackerCredentials } from "./tracker-credentials.js";
8
9
 
9
10
  /** The check's schedule's name among the office's schedules, and the handler that answers it. */
10
11
  export const INCIDENTS_SCHEDULE = "incidents";
@@ -23,29 +24,28 @@ export interface IncidentsSettings {
23
24
  }
24
25
 
25
26
  /**
26
- * The trackers that are on: each needs its token variables in `env` and a project in the
27
- * settings, and Sentry an organisation too.
27
+ * The trackers that are on: each needs a sign-in in `credentials` and a project in the settings,
28
+ * and Sentry an organisation too.
28
29
  */
29
30
  export function incidentsReaders(
30
31
  values: IncidentsSettings,
31
- env: NodeJS.ProcessEnv,
32
+ credentials: TrackerCredentials,
32
33
  ): Partial<Record<IncidentSource, TrackerReader>> {
33
34
  const readers: Partial<Record<IncidentSource, TrackerReader>> = {};
34
- const jira = jiraEnv(env);
35
+ const { jira, sentry } = credentials;
35
36
  const jiraProjects = parseKeys(values.jiraProjects, JIRA_KEY);
36
37
  if (jira !== null && jiraProjects.length > 0) {
37
38
  readers.jira = createJiraReader(jira, jiraProjects);
38
39
  }
39
- const token = sentryToken(env);
40
40
  const org = values.sentryOrg.trim();
41
41
  const sentryProjects = parseKeys(values.sentryProjects, SENTRY_SLUG);
42
- const sentryOn = token !== null && org !== "" && sentryProjects.length > 0;
43
- if (sentryOn) {
42
+ if (sentry !== null && org !== "" && sentryProjects.length > 0) {
44
43
  readers.sentry = createSentryReader({
45
44
  url: values.sentryUrl,
46
45
  org,
47
46
  projects: sentryProjects,
48
- token,
47
+ token: sentry.token,
48
+ tokenVariable: sentry.tokenVariable,
49
49
  });
50
50
  }
51
51
  return readers;
@@ -23,6 +23,8 @@ export interface SentryReaderInput {
23
23
  /** Project slugs, already checked against the settings' pattern. */
24
24
  projects: string[];
25
25
  token: string;
26
+ /** What a refused token's message names; the environment's variable when absent. */
27
+ tokenVariable?: string;
26
28
  }
27
29
 
28
30
  const ProjectsSchema = z.array(z.object({ id: z.string(), slug: z.string() }));
@@ -36,6 +38,36 @@ const IssuesSchema = z.array(
36
38
  }),
37
39
  );
38
40
 
41
+ type SentrySignIn = Omit<SentryReaderInput, "projects">;
42
+
43
+ function sentryApi(input: SentrySignIn): string {
44
+ const site = new URL(input.url.trim());
45
+ const org = encodeURIComponent(input.org.trim());
46
+ return `${site.origin}${site.pathname.replace(/\/+$/, "")}/api/0/organizations/${org}`;
47
+ }
48
+
49
+ function sentryTracker(input: SentrySignIn, fetchFn: typeof fetch): Tracker {
50
+ return {
51
+ name: "Sentry",
52
+ tokenVariable: input.tokenVariable ?? "SENTRY_AUTH_TOKEN",
53
+ headers: { Authorization: `Bearer ${input.token}` },
54
+ fetchFn,
55
+ };
56
+ }
57
+
58
+ /**
59
+ * One signed-in request, to tell whether Sentry takes the token for the organisation. Rejects
60
+ * with a `TrackerProblem`.
61
+ */
62
+ export async function probeSentry(
63
+ input: SentrySignIn,
64
+ fetchFn: typeof fetch = fetch,
65
+ ): Promise<void> {
66
+ const tracker = sentryTracker(input, fetchFn);
67
+ const url = `${sentryApi(input)}/projects/?per_page=1`;
68
+ await getJson({ tracker, url, schema: ProjectsSchema });
69
+ }
70
+
39
71
  /** New unresolved issues in the listed projects. */
40
72
  export function createSentryReader(
41
73
  input: SentryReaderInput,
@@ -43,14 +75,8 @@ export function createSentryReader(
43
75
  ): TrackerReader {
44
76
  const { projects } = input;
45
77
  const org = input.org.trim();
46
- const site = new URL(input.url.trim());
47
- const api = `${site.origin}${site.pathname.replace(/\/+$/, "")}/api/0/organizations/${encodeURIComponent(org)}`;
48
- const tracker: Tracker = {
49
- name: "Sentry",
50
- tokenVariable: "SENTRY_AUTH_TOKEN",
51
- headers: { Authorization: `Bearer ${input.token}` },
52
- fetchFn,
53
- };
78
+ const api = sentryApi(input);
79
+ const tracker = sentryTracker(input, fetchFn);
54
80
 
55
81
  /**
56
82
  * The listed projects' ids, in the order listed. The issue search takes slugs too, but only on
@@ -17,6 +17,8 @@ export function createLifeFeed(deps: {
17
17
  const pending = new Map<string, Promise<void>>();
18
18
  const folderTeams = new Map<string, Set<string>>();
19
19
  let connected = false;
20
+ /** The name each workspace went by at the last view, to tell a rename. */
21
+ const shown = new Map<string, string>();
20
22
  let queuedAge = Promise.resolve();
21
23
  function snapshot(): Snapshot {
22
24
  const born = new Map<string, string>();
@@ -84,6 +86,13 @@ export function createLifeFeed(deps: {
84
86
  return;
85
87
  }
86
88
  const names = new Map(view.workspaces.map((w) => [w.id, w.name]));
89
+ // A workspace that goes by another name since the last view is the same team: its tenure
90
+ // goes with it, so a rename makes nobody an intern again.
91
+ for (const [id, name] of names) {
92
+ const before = shown.get(id);
93
+ if (before !== undefined && before !== name) deps.tenure.rename(before, name);
94
+ shown.set(id, name);
95
+ }
87
96
  const at = deps.now();
88
97
  const today = new Date(at).toDateString();
89
98
  const seeds = new Map(
@@ -123,6 +132,10 @@ export function createLifeFeed(deps: {
123
132
  readFolders(view, names);
124
133
  changed();
125
134
  },
135
+ /** A team now goes by `to`: its tenure goes with it, before the directory says so. */
136
+ renamed(from: string, to: string) {
137
+ if (deps.tenure.rename(from, to)) changed();
138
+ },
126
139
  async turnEnded(id: string, lookup?: () => Promise<string | null>) {
127
140
  const name = teams.get(id) ?? (await lookup?.());
128
141
  if (name) {
@@ -7,6 +7,8 @@ import {
7
7
  type ChatServicePorts,
8
8
  } from "./chat-service.js";
9
9
  import { PARENT_AGENT_ID_LABEL } from "./directory.js";
10
+ import { writerMode, writerModeChoices } from "./writer-mode.js";
11
+ import type { WriterModes } from "../shared/contracts.js";
10
12
  import type { Hub, HubPorts } from "./hub.js";
11
13
  import type { JanitorPorts } from "./janitor.js";
12
14
  import { wakeTargetOf } from "./mention-queue.js";
@@ -250,28 +252,45 @@ export function liveScriptLogPorts(
250
252
 
251
253
  type AgentConfig = Parameters<Paseo["agents"]["create"]>[0]["config"];
252
254
 
253
- // Claude's "Accept File Edits", which a provider extending Claude lists too. The owner's call:
254
- // nobody watches the 8:00 writer, so it edits the notes without asking.
255
- const ACCEPT_EDITS_MODE = "acceptEdits";
256
-
257
255
  /**
258
256
  * The host's default provider, as the host can tell it. The app's new-agent form starts from the
259
257
  * provider the device chose last, which the host never sees; so this takes the first enabled,
260
258
  * ready provider in the daemon's order, with the model the form gives that provider: its default
261
- * (else its first selectable one). The mode is the provider's that accepts edits, else its
262
- * default: Codex's and OpenCode's default modes edit in the workspace without asking already.
259
+ * (else its first selectable one). The mode is `writerMode`'s: the settings' where the provider
260
+ * offers it, else the one that accepts edits, else the provider's default. Nobody watches the
261
+ * 8:00 writer, so by default it edits the notes without asking.
263
262
  */
264
- async function defaultAgentConfig(paseo: Paseo, cwd: string): Promise<AgentConfig> {
263
+ async function writerProvider(paseo: Paseo, cwd: string) {
265
264
  const { entries } = await paseo.providers.waitForReady({ cwd });
266
265
  const entry = entries.find((candidate) => candidate.enabled && candidate.status === "ready");
267
266
  if (entry === undefined) throw new Error("No agent provider is ready on this host");
267
+ return entry;
268
+ }
269
+
270
+ /** The provider the writer would start on now, its modes, and the one `wanted` comes to. */
271
+ export async function readWriterModes(
272
+ holder: PaseoHolder,
273
+ cwd: string,
274
+ wanted: string,
275
+ ): Promise<WriterModes> {
276
+ const entry = await writerProvider(holder.require(), cwd);
277
+ const { modeId, fellBack } = writerMode(entry, wanted);
278
+ return {
279
+ provider: entry.label ?? entry.provider,
280
+ modes: writerModeChoices(entry),
281
+ modeId: modeId ?? null,
282
+ fellBack,
283
+ };
284
+ }
285
+
286
+ async function defaultAgentConfig(paseo: Paseo, cwd: string, wanted: string): Promise<AgentConfig> {
287
+ const entry = await writerProvider(paseo, cwd);
268
288
  const models = (entry.models ?? []).filter((model) => model.isSelectable !== false);
269
289
  const model = models.find((candidate) => candidate.isDefault) ?? models[0];
270
290
  if (model === undefined) {
271
291
  throw new Error(`The provider ${entry.label ?? entry.provider} offers no model`);
272
292
  }
273
- const acceptsEdits = (entry.modes ?? []).some((mode) => mode.id === ACCEPT_EDITS_MODE);
274
- const modeId = acceptsEdits ? ACCEPT_EDITS_MODE : entry.defaultModeId;
293
+ const { modeId } = writerMode(entry, wanted);
275
294
  return {
276
295
  provider: `${entry.provider}/${model.id}`,
277
296
  ...(modeId ? { modeId } : {}),
@@ -290,9 +309,9 @@ export function liveNotesPorts(
290
309
  (found) => found.isDirectory(),
291
310
  () => false,
292
311
  ),
293
- async startAgent({ cwd, title, prompt }) {
312
+ async startAgent({ cwd, title, prompt, mode }) {
294
313
  const paseo = holder.require();
295
- const config = await defaultAgentConfig(paseo, cwd);
314
+ const config = await defaultAgentConfig(paseo, cwd, mode ?? "");
296
315
  const workspace = await paseo.workspaces.open(cwd);
297
316
  const agent = await workspace.agents.create({ config, title, prompt });
298
317
  return agent.id;
@@ -9,6 +9,8 @@ const NOTES: OfficeSchedule = { name: NOTES_SCHEDULE, label: "Stand-up notes", l
9
9
  export interface NotesSettings {
10
10
  notesFolder: string;
11
11
  notesTimeZone: string;
12
+ /** The mode the writer starts in, by the provider's id; empty or absent for the office's choice. */
13
+ notesMode?: string;
12
14
  }
13
15
 
14
16
  /** What the 8:00 run follows: the folder and zone, and its weekdays, 0 for Sunday. */
@@ -48,6 +48,8 @@ export interface WriterStart {
48
48
  cwd: string;
49
49
  title: string;
50
50
  prompt: string;
51
+ /** The settings' mode for the writer; absent when none is set. */
52
+ mode?: string;
51
53
  }
52
54
 
53
55
  export interface NotesPorts {
@@ -219,7 +221,13 @@ export function createNotesWriter(ports: NotesPorts): NotesWriter {
219
221
  report: standupReport(await ports.snapshot(), now),
220
222
  });
221
223
  endedWhileStarting = new Map();
222
- const writerId = await ports.startAgent({ cwd: folder, title: NOTES_WRITER_TITLE, prompt });
224
+ const mode = settings.notesMode?.trim() ?? "";
225
+ const writerId = await ports.startAgent({
226
+ cwd: folder,
227
+ title: NOTES_WRITER_TITLE,
228
+ prompt,
229
+ ...(mode === "" ? {} : { mode }),
230
+ });
223
231
  return { writerId, entry: { folder, ...day } };
224
232
  }
225
233
 
package/server/paths.ts CHANGED
@@ -35,6 +35,11 @@ export function incidentsFile(env: NodeJS.ProcessEnv, home: string): string {
35
35
  return join(officeDir(env, home), "incidents.json");
36
36
  }
37
37
 
38
+ /** The tracker connections saved from the settings. It holds tokens: owner-only. */
39
+ export function trackersFile(env: NodeJS.ProcessEnv, home: string): string {
40
+ return join(officeDir(env, home), "trackers.json");
41
+ }
42
+
38
43
  /** The team chat's conversation, kept as upstream's engine writes it. */
39
44
  export function chatFile(env: NodeJS.ProcessEnv, home: string): string {
40
45
  return join(officeDir(env, home), "chat.json");
package/server/tenure.ts CHANGED
@@ -55,6 +55,8 @@ export interface Tenure {
55
55
  list(live: ReadonlySet<string>): TenureProject[];
56
56
  seed(teams: readonly SeedTeam[]): void;
57
57
  get(team: string): TenureEntry | null;
58
+ /** A team that goes by another name keeps its entry; false when it has none or `to` is taken. */
59
+ rename(from: string, to: string): boolean;
58
60
  /** True once seed() has run on this ledger, now or on an earlier start. */
59
61
  seeded(): boolean;
60
62
  }
@@ -94,6 +96,14 @@ export function createTenure(deps: { store: TenureStore; now?: () => number }):
94
96
  return {
95
97
  seeded: () => ledger.seeded,
96
98
  get: (team) => projects[team] ?? null,
99
+ rename(from, to) {
100
+ const entry = projects[from];
101
+ if (!entry || !to || from === to || projects[to]) return false;
102
+ projects[to] = entry;
103
+ delete projects[from];
104
+ save();
105
+ return true;
106
+ },
97
107
  seed(teams) {
98
108
  if (ledger.seeded) return;
99
109
  const at = now();
@@ -0,0 +1,141 @@
1
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { z } from "zod";
4
+ import type { IncidentSource, TrackersChange } from "../shared/contracts.js";
5
+ import { isTokenSafe } from "../shared/settings.js";
6
+ import { jiraEnv, type JiraEnv } from "./incidents-jira.js";
7
+ import { sentryToken } from "./incidents-sentry.js";
8
+
9
+ const SavedTrackersSchema = z.object({
10
+ version: z.literal(1),
11
+ jira: z.object({ baseUrl: z.string(), email: z.string(), token: z.string() }).optional(),
12
+ sentry: z.object({ token: z.string() }).optional(),
13
+ });
14
+ /** The connections saved from the settings. They hold tokens: never sent to a client or logged. */
15
+ export type SavedTrackers = z.output<typeof SavedTrackersSchema>;
16
+
17
+ export const NO_SAVED_TRACKERS: SavedTrackers = { version: 1 };
18
+
19
+ export interface TrackerCredentialsStore {
20
+ /** A missing or unreadable file is no saved connection; any other read error rejects. */
21
+ load(): Promise<SavedTrackers>;
22
+ /** Rejects when the write fails. */
23
+ save(saved: SavedTrackers): Promise<void>;
24
+ }
25
+
26
+ function isMissing(error: unknown): boolean {
27
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
28
+ }
29
+
30
+ /** The file is written for its owner only, and replaced whole so its mode is always that. */
31
+ export function createTrackerCredentialsStore(options: {
32
+ file: string;
33
+ log(message: string): void;
34
+ }): TrackerCredentialsStore {
35
+ const { file, log } = options;
36
+ let temp = 0;
37
+
38
+ async function load(): Promise<SavedTrackers> {
39
+ let text: string;
40
+ try {
41
+ text = await readFile(file, "utf8");
42
+ } catch (error) {
43
+ if (isMissing(error)) return NO_SAVED_TRACKERS;
44
+ throw error;
45
+ }
46
+ let json: unknown;
47
+ try {
48
+ json = JSON.parse(text);
49
+ } catch (error) {
50
+ if (!(error instanceof SyntaxError)) throw error;
51
+ json = null;
52
+ }
53
+ const parsed = SavedTrackersSchema.safeParse(json);
54
+ if (parsed.success) return parsed.data;
55
+ // Only that it is unreadable: a parse error's message quotes the file, which holds tokens.
56
+ log(`[office] ${file} is unreadable; no tracker connection is saved until the next save`);
57
+ return NO_SAVED_TRACKERS;
58
+ }
59
+
60
+ async function save(saved: SavedTrackers): Promise<void> {
61
+ temp += 1;
62
+ const tempFile = `${file}.tmp-${temp}`;
63
+ await mkdir(dirname(file), { recursive: true });
64
+ try {
65
+ await writeFile(tempFile, `${JSON.stringify(saved)}\n`, { encoding: "utf8", mode: 0o600 });
66
+ await rename(tempFile, file);
67
+ } catch (error) {
68
+ await rm(tempFile, { force: true }).catch(() => undefined);
69
+ throw error;
70
+ }
71
+ }
72
+
73
+ return { load, save };
74
+ }
75
+
76
+ /** Where a tracker's sign-in comes from: the settings' saved connection, or the daemon's environment. */
77
+ export type CredentialSource = "saved" | "env";
78
+
79
+ interface Sourced {
80
+ source: CredentialSource;
81
+ /** What a refused token's message tells the owner to check. */
82
+ tokenVariable: string;
83
+ }
84
+
85
+ export interface TrackerCredentials {
86
+ jira: (JiraEnv & Sourced) | null;
87
+ sentry: ({ token: string } & Sourced) | null;
88
+ }
89
+
90
+ /** Each tracker's sign-in: the saved connection, else the daemon's environment, else none. */
91
+ export function trackerCredentials(
92
+ saved: SavedTrackers,
93
+ env: NodeJS.ProcessEnv,
94
+ ): TrackerCredentials {
95
+ const fromEnv = jiraEnv(env);
96
+ const envToken = sentryToken(env);
97
+ let jira: TrackerCredentials["jira"] = null;
98
+ if (saved.jira !== undefined) {
99
+ jira = { ...saved.jira, source: "saved", tokenVariable: "the saved Jira token" };
100
+ } else if (fromEnv !== null) {
101
+ jira = { ...fromEnv, source: "env", tokenVariable: "ATLASSIAN_API_TOKEN" };
102
+ }
103
+ let sentry: TrackerCredentials["sentry"] = null;
104
+ if (saved.sentry !== undefined) {
105
+ sentry = { ...saved.sentry, source: "saved", tokenVariable: "the saved Sentry token" };
106
+ } else if (envToken !== null) {
107
+ sentry = { token: envToken, source: "env", tokenVariable: "SENTRY_AUTH_TOKEN" };
108
+ }
109
+ return { jira, sentry };
110
+ }
111
+
112
+ export type SavedChange = { saved: SavedTrackers } | { problem: string };
113
+
114
+ function without(saved: SavedTrackers, tracker: IncidentSource): SavedTrackers {
115
+ const { [tracker]: _removed, ...kept } = saved;
116
+ return kept;
117
+ }
118
+
119
+ /**
120
+ * `saved` after a change from the settings, or why the change is refused. A Jira save with no
121
+ * token keeps the saved one, so the address or email can change without typing it again.
122
+ */
123
+ export function changeSavedTrackers(saved: SavedTrackers, change: TrackersChange): SavedChange {
124
+ if (change.action === "clear") return { saved: without(saved, change.tracker) };
125
+ const token = change.token.trim();
126
+ if (change.action === "save-sentry") {
127
+ if (token === "") return { problem: "Enter the Sentry auth token" };
128
+ return { saved: { ...saved, sentry: { token } } };
129
+ }
130
+ const baseUrl = change.baseUrl.trim().replace(/\/+$/, "");
131
+ const email = change.email.trim();
132
+ const kept = token === "" ? (saved.jira?.token ?? "") : token;
133
+ if (!isTokenSafe(baseUrl)) {
134
+ return {
135
+ problem: "The Jira address must be an https address (plain http only on this machine)",
136
+ };
137
+ }
138
+ if (email === "") return { problem: "Enter the Jira account's email" };
139
+ if (kept === "") return { problem: "Enter the Jira API token" };
140
+ return { saved: { ...saved, jira: { baseUrl, email, token: kept } } };
141
+ }