@koinzhang/paseo-plugin-inbox 0.1.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.
@@ -0,0 +1,39 @@
1
+ import type { AgentLive, AgentState } from "./contracts.ts";
2
+
3
+ export type AgentStatusTone = "warning" | "danger" | "success" | "accent" | "muted";
4
+
5
+ export interface AgentStatusDisplay {
6
+ label: string;
7
+ tone: AgentStatusTone;
8
+ }
9
+
10
+ /** Bot icon highlight, as in Activity's Explorer rows: error > permission > finished. */
11
+ export type AgentAttention = "error" | "permission" | "finished" | null;
12
+
13
+ export function agentAttention(live: AgentLive | undefined): AgentAttention {
14
+ if (!live) return null;
15
+ if (live.status === "error") return "error";
16
+ return live.attention;
17
+ }
18
+
19
+ export function isAgentRunning(live: AgentLive | undefined): boolean {
20
+ return live?.status === "running" || live?.status === "initializing";
21
+ }
22
+
23
+ /** Same precedence as Activity's Explorer rows: error > permission > running > finished. */
24
+ export function describeAgentStatus(
25
+ state: AgentState | undefined,
26
+ live: AgentLive | undefined,
27
+ ): AgentStatusDisplay | null {
28
+ if (state === "archived") return { label: "Archived", tone: "warning" };
29
+ if (state === "missing") return { label: "Unavailable", tone: "danger" };
30
+ if (!live) return null;
31
+ if (live.status === "error" || live.attention === "error") return { label: "Error", tone: "danger" };
32
+ if (live.attention === "permission") return { label: "Needs permission", tone: "warning" };
33
+ if (live.status === "running" || live.status === "initializing") {
34
+ return { label: "Running", tone: "accent" };
35
+ }
36
+ if (live.attention === "finished") return { label: "Finished", tone: "success" };
37
+ if (live.status === "closed") return { label: "Closed", tone: "muted" };
38
+ return { label: "Idle", tone: "muted" };
39
+ }
@@ -0,0 +1,192 @@
1
+ import { defineRpc } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+
4
+ export const ItemKind = z.enum(["agent", "note", "scratch"]);
5
+ export type ItemKind = z.infer<typeof ItemKind>;
6
+
7
+ export const AgentSnapshot = z.object({
8
+ title: z.string().nullable(),
9
+ provider: z.string(),
10
+ model: z.string().nullable(),
11
+ workspaceId: z.string().nullable(),
12
+ cwd: z.string(),
13
+ /** When the agent itself was created; missing on items starred before sorting existed. */
14
+ createdAt: z.string().nullable().optional(),
15
+ });
16
+ export type AgentSnapshot = z.infer<typeof AgentSnapshot>;
17
+
18
+ export const Item = z.object({
19
+ id: z.string(),
20
+ kind: ItemKind,
21
+ title: z.string().nullable(),
22
+ body: z.string(),
23
+ projectKey: z.string().nullable(),
24
+ projectLabel: z.string().nullable(),
25
+ agentId: z.string().nullable(),
26
+ agentSnapshot: AgentSnapshot.nullable(),
27
+ /** Workspace tag; always within the project tag. */
28
+ workspaceId: z.string().nullable(),
29
+ /** Last known workspace name, kept for archived workspaces. */
30
+ workspaceLabel: z.string().nullable(),
31
+ pinned: z.boolean(),
32
+ createdAt: z.string(),
33
+ updatedAt: z.string(),
34
+ });
35
+ export type Item = z.infer<typeof Item>;
36
+
37
+ export const ProjectSummary = z.object({
38
+ key: z.string(),
39
+ label: z.string(),
40
+ count: z.number(),
41
+ archived: z.boolean(),
42
+ });
43
+ export type ProjectSummary = z.infer<typeof ProjectSummary>;
44
+
45
+ export const WorkspaceSummary = z.object({
46
+ id: z.string(),
47
+ label: z.string(),
48
+ count: z.number(),
49
+ archived: z.boolean(),
50
+ });
51
+ export type WorkspaceSummary = z.infer<typeof WorkspaceSummary>;
52
+
53
+ /**
54
+ * `starred`: added to the Inbox; `created`: the agent's own creation time for agents,
55
+ * otherwise when the item was added; `updated`: last change; `name`: title A→Z.
56
+ */
57
+ export const ItemSort = z.enum(["starred", "created", "updated", "name"]);
58
+ export type ItemSort = z.infer<typeof ItemSort>;
59
+
60
+ export const AgentState = z.enum(["active", "archived", "missing"]);
61
+ export type AgentState = z.infer<typeof AgentState>;
62
+
63
+ export const listItems = defineRpc({
64
+ name: "items.list",
65
+ input: z.object({
66
+ kind: ItemKind.optional(),
67
+ projectKey: z.string().optional(),
68
+ query: z.string().optional(),
69
+ /** Items tagged with exactly this workspace. */
70
+ workspaceId: z.string().optional(),
71
+ /**
72
+ * A workspace's Inbox: items tagged with this workspace, plus items tagged
73
+ * only with its project.
74
+ */
75
+ inboxOf: z.string().optional(),
76
+ /** Defaults to `updated`. Pinned items always come first. */
77
+ sort: ItemSort.optional(),
78
+ }),
79
+ output: z.object({
80
+ items: z.array(Item),
81
+ projects: z.array(ProjectSummary),
82
+ /** Workspaces tagged on items of the requested kind, archived ones included. */
83
+ workspaces: z.array(WorkspaceSummary),
84
+ /** Tags of the listed items that are no longer active on the host. */
85
+ archived: z.object({ projects: z.array(z.string()), workspaces: z.array(z.string()) }),
86
+ }),
87
+ });
88
+
89
+ export const saveNote = defineRpc({
90
+ name: "items.save",
91
+ input: z.object({
92
+ id: z.string().optional(),
93
+ kind: z.enum(["note", "scratch"]),
94
+ title: z.string().nullable().optional(),
95
+ body: z.string(),
96
+ /** On create: tag this workspace and its project. */
97
+ workspaceId: z.string().optional(),
98
+ /** On create: tag only this workspace's project. */
99
+ projectOfWorkspace: z.string().optional(),
100
+ }),
101
+ output: z.object({ item: Item }),
102
+ });
103
+
104
+ /**
105
+ * Sets a note's tags. A workspace must belong to the project; with only a
106
+ * workspace, the project follows it. Agents' tags come from the agent itself.
107
+ */
108
+ export const tagItem = defineRpc({
109
+ name: "items.tag",
110
+ input: z.object({
111
+ id: z.string(),
112
+ projectKey: z.string().nullable(),
113
+ workspaceId: z.string().nullable(),
114
+ }),
115
+ output: z.object({ item: Item }),
116
+ });
117
+
118
+ export const TagProject = z.object({ key: z.string(), label: z.string() });
119
+ export type TagProject = z.infer<typeof TagProject>;
120
+
121
+ export const TagWorkspace = z.object({ id: z.string(), label: z.string(), projectKey: z.string() });
122
+ export type TagWorkspace = z.infer<typeof TagWorkspace>;
123
+
124
+ /** Active projects and workspaces that can be picked as tags. */
125
+ export const tagOptions = defineRpc({
126
+ name: "tags.options",
127
+ input: z.object({}),
128
+ output: z.object({ projects: z.array(TagProject), workspaces: z.array(TagWorkspace) }),
129
+ });
130
+
131
+ export const updateItem = defineRpc({
132
+ name: "items.update",
133
+ input: z.object({
134
+ id: z.string(),
135
+ pinned: z.boolean().optional(),
136
+ /** Only `note` is accepted: promotes a scratch entry. */
137
+ kind: z.literal("note").optional(),
138
+ }),
139
+ output: z.object({ item: Item }),
140
+ });
141
+
142
+ export const deleteItem = defineRpc({
143
+ name: "items.delete",
144
+ input: z.object({ id: z.string() }),
145
+ output: z.object({}),
146
+ });
147
+
148
+ export const starAgent = defineRpc({
149
+ name: "agents.star",
150
+ /** Tags follow the agent's own workspace and project. */
151
+ input: z.object({ agentId: z.string() }),
152
+ output: z.object({ item: Item, created: z.boolean() }),
153
+ });
154
+
155
+ export const AgentCandidate = z.object({
156
+ id: z.string(),
157
+ title: z.string().nullable(),
158
+ provider: z.string(),
159
+ });
160
+ export type AgentCandidate = z.infer<typeof AgentCandidate>;
161
+
162
+ export const agentCandidates = defineRpc({
163
+ name: "agents.candidates",
164
+ input: z.object({ workspaceId: z.string() }),
165
+ output: z.object({ agents: z.array(AgentCandidate) }),
166
+ });
167
+
168
+ /** Live host status; `attention` is a pending permission or an unseen finish / error. */
169
+ export const AgentLive = z.object({
170
+ status: z.string(),
171
+ attention: z.enum(["permission", "finished", "error"]).nullable(),
172
+ permissions: z.number().optional(),
173
+ });
174
+ export type AgentLive = z.infer<typeof AgentLive>;
175
+
176
+ export const agentStates = defineRpc({
177
+ name: "agents.states",
178
+ input: z.object({ agentIds: z.array(z.string()) }),
179
+ output: z.object({
180
+ states: z.record(z.string(), AgentState),
181
+ /** Only agents the host still knows. */
182
+ live: z.record(z.string(), AgentLive).optional(),
183
+ /** A starred agent was renamed on the host and the stored title updated; the list is stale. */
184
+ titlesChanged: z.boolean().optional(),
185
+ }),
186
+ });
187
+
188
+ export const unarchiveAgent = defineRpc({
189
+ name: "agents.unarchive",
190
+ input: z.object({ agentId: z.string() }),
191
+ output: z.object({ restoredWorkspace: z.boolean() }),
192
+ });
@@ -0,0 +1,74 @@
1
+ import { defineSettings } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+ import { ItemSort } from "./contracts.ts";
4
+
5
+ const FilterKind = z.enum(["all", "agent", "note", "scratch"]);
6
+
7
+ /** Older documents have no `sort`; the schema default fills it in. */
8
+ export function migrateInboxFilters(values: unknown, fromVersion: number): unknown {
9
+ if (fromVersion < 2) return values;
10
+ return values;
11
+ }
12
+
13
+ /** Host-scoped Inbox filters. The global page and the Explorer panel each keep their own group. */
14
+ export const inboxFilterSettings = defineSettings({
15
+ id: "list-filters",
16
+ scope: "host",
17
+ version: 2,
18
+ schema: z.object({
19
+ kind: FilterKind.default("all"),
20
+ /** Selected project chip on the global page. */
21
+ projectKey: z.string().nullable().default(null),
22
+ /** Selected workspace chip on the global page. */
23
+ workspaceId: z.string().nullable().default(null),
24
+ panelKind: FilterKind.default("all"),
25
+ /** Global page sort. The Explorer panel always lists by last update. */
26
+ sort: ItemSort.default("updated"),
27
+ }),
28
+ migrate: migrateInboxFilters,
29
+ });
30
+
31
+ export type InboxFilters = z.infer<typeof inboxFilterSettings.schema>;
32
+
33
+ export const INBOX_FILTER_DEFAULTS: InboxFilters = {
34
+ kind: "all",
35
+ projectKey: null,
36
+ workspaceId: null,
37
+ panelKind: "all",
38
+ sort: "updated",
39
+ };
40
+
41
+ export function sameInboxFilters(a: InboxFilters, b: InboxFilters): boolean {
42
+ return (
43
+ a.kind === b.kind &&
44
+ a.projectKey === b.projectKey &&
45
+ a.workspaceId === b.workspaceId &&
46
+ a.panelKind === b.panelKind &&
47
+ a.sort === b.sort
48
+ );
49
+ }
50
+
51
+ /** Sort applied to a list. Explorer panels stay on last update. */
52
+ export function inboxListSort(filters: InboxFilters, surface: { workspaceId?: string }): InboxFilters["sort"] {
53
+ return surface.workspaceId ? "updated" : filters.sort;
54
+ }
55
+
56
+ export interface VisibleInboxFilters {
57
+ kind: InboxFilters["kind"];
58
+ projectKey: string | null;
59
+ workspaceId: string | null;
60
+ }
61
+
62
+ /**
63
+ * Filters that actually narrow the list. A workspace panel always scopes to that
64
+ * workspace and ignores the global page's project and workspace chips.
65
+ */
66
+ export function visibleInboxFilters(
67
+ filters: InboxFilters,
68
+ surface: { workspaceId?: string },
69
+ ): VisibleInboxFilters {
70
+ if (surface.workspaceId) {
71
+ return { kind: filters.panelKind, projectKey: null, workspaceId: surface.workspaceId };
72
+ }
73
+ return { kind: filters.kind, projectKey: filters.projectKey, workspaceId: filters.workspaceId };
74
+ }
@@ -0,0 +1,8 @@
1
+ import type { Item } from "./contracts.ts";
2
+
3
+ export function itemTitle(item: Item): string {
4
+ if (item.kind === "agent") return item.agentSnapshot?.title || item.title || "Untitled agent";
5
+ if (item.title) return item.title;
6
+ const firstLine = item.body.split("\n").find((line) => line.trim());
7
+ return firstLine?.trim() || (item.kind === "scratch" ? "Empty scratch" : "Untitled note");
8
+ }
@@ -0,0 +1,124 @@
1
+ /** Timeline row shape used to find the latest prompt and reply. */
2
+ export interface ExchangeEntry {
3
+ item: { type: string; text?: string | null };
4
+ seqStart?: number;
5
+ timestamp?: string;
6
+ }
7
+
8
+ export interface LastExchange {
9
+ prompt: string | null;
10
+ agent: string | null;
11
+ }
12
+
13
+ export interface ExchangeCursor {
14
+ epoch: string;
15
+ seq: number;
16
+ }
17
+
18
+ export interface ExchangePage {
19
+ entries?: ReadonlyArray<ExchangeEntry> | null;
20
+ hasOlder?: boolean;
21
+ startCursor?: ExchangeCursor | null;
22
+ error?: string | null;
23
+ }
24
+
25
+ const PAGE_LIMIT = 80;
26
+ const MAX_PAGES = 5;
27
+ /** Detail text cap; longer replies stay on the agent itself. */
28
+ const EXCERPT_CHARS = 2000;
29
+
30
+ function ordered(entries: readonly ExchangeEntry[]) {
31
+ return entries
32
+ .map((entry, index) => ({ entry, index }))
33
+ .sort((a, b) => {
34
+ const seqA = a.entry.seqStart ?? -1;
35
+ const seqB = b.entry.seqStart ?? -1;
36
+ if (seqA !== seqB) return seqA - seqB;
37
+ const tsA = a.entry.timestamp ?? "";
38
+ const tsB = b.entry.timestamp ?? "";
39
+ if (tsA !== tsB) return tsA < tsB ? -1 : 1;
40
+ return a.index - b.index;
41
+ });
42
+ }
43
+
44
+ /**
45
+ * Newest non-empty user prompt, and the newest run of assistant chunks.
46
+ * A run stops at any other item, so an earlier reply split by a tool call is kept whole
47
+ * and a later one replaces it. Blank runs are skipped.
48
+ */
49
+ export function pickLastExchange(entries: readonly ExchangeEntry[]): LastExchange {
50
+ const rows = ordered(entries);
51
+ let prompt: string | null = null;
52
+ for (const { entry } of rows) {
53
+ if (entry.item.type !== "user_message") continue;
54
+ const text = entry.item.text?.trim();
55
+ if (text) prompt = text;
56
+ }
57
+
58
+ let agent: string | null = null;
59
+ for (let index = rows.length - 1; index >= 0; ) {
60
+ if (rows[index]!.entry.item.type !== "assistant_message") {
61
+ index -= 1;
62
+ continue;
63
+ }
64
+ const chunks: string[] = [];
65
+ while (index >= 0 && rows[index]!.entry.item.type === "assistant_message") {
66
+ const text = rows[index]!.entry.item.text;
67
+ if (typeof text === "string") chunks.push(text);
68
+ index -= 1;
69
+ }
70
+ const text = chunks.toReversed().join("").trim();
71
+ if (text) {
72
+ agent = text;
73
+ break;
74
+ }
75
+ }
76
+ return { prompt, agent };
77
+ }
78
+
79
+ /** The newest assistant run starts at the first row we have, so an older page may hold its beginning. */
80
+ export function assistantRunReachesStart(entries: readonly ExchangeEntry[]): boolean {
81
+ const rows = ordered(entries);
82
+ let index = rows.length - 1;
83
+ while (index >= 0 && rows[index]!.entry.item.type !== "assistant_message") index -= 1;
84
+ if (index < 0) return false;
85
+ while (index >= 0 && rows[index]!.entry.item.type === "assistant_message") index -= 1;
86
+ return index < 0;
87
+ }
88
+
89
+ export function excerpt(text: string, maxChars = EXCERPT_CHARS): string {
90
+ const trimmed = text.trim();
91
+ if (trimmed.length <= maxChars) return trimmed;
92
+ return `${trimmed.slice(0, maxChars).trimEnd()}…`;
93
+ }
94
+
95
+ /**
96
+ * Walk the timeline tail toward older pages until both sides are found and the
97
+ * newest reply is not cut off by the window, or the page cap is hit.
98
+ */
99
+ export async function readLastExchange(
100
+ fetchPage: (input: { direction: "tail" | "before"; cursor?: ExchangeCursor }) => Promise<ExchangePage>,
101
+ ): Promise<LastExchange> {
102
+ let collected: ExchangeEntry[] = [];
103
+ let cursor: ExchangeCursor | undefined;
104
+ let direction: "tail" | "before" = "tail";
105
+ let picked: LastExchange = { prompt: null, agent: null };
106
+ for (let page = 0; page < MAX_PAGES; page += 1) {
107
+ const result = await fetchPage({
108
+ direction,
109
+ ...(cursor !== undefined ? { cursor } : {}),
110
+ });
111
+ if (result.error) throw new Error(result.error);
112
+ const entries = result.entries ?? [];
113
+ collected = direction === "tail" ? [...entries] : [...entries, ...collected];
114
+ picked = pickLastExchange(collected);
115
+ const truncated = assistantRunReachesStart(collected);
116
+ if (picked.prompt && picked.agent && !truncated) return picked;
117
+ if (!result.hasOlder || result.startCursor == null) return picked;
118
+ direction = "before";
119
+ cursor = result.startCursor;
120
+ }
121
+ return picked;
122
+ }
123
+
124
+ export const LAST_EXCHANGE_PAGE_LIMIT = PAGE_LIMIT;
package/shared/note.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** A note with neither a title nor body text is never stored. */
2
+ export function isEmptyNote(title: string | null | undefined, body: string): boolean {
3
+ return !title?.trim() && !body.trim();
4
+ }
@@ -0,0 +1,4 @@
1
+ /** Runtime plugin id (paseo-plugin.json / install / data dir). */
2
+ export const PLUGIN_ID = "inbox";
3
+
4
+ export const LOG_PREFIX = `[${PLUGIN_ID}]`;
@@ -0,0 +1,55 @@
1
+ export interface ProjectRef {
2
+ key: string;
3
+ label: string;
4
+ }
5
+
6
+ /**
7
+ * Normalize a git remote URL to `host/owner/repo` so SSH, HTTPS, and scp-style
8
+ * remotes of the same repository share one key. Returns null for local paths.
9
+ */
10
+ export function normalizeRemoteUrl(raw: string): string | null {
11
+ let value = raw.trim();
12
+ if (!value) return null;
13
+ if (value.startsWith("/") || value.startsWith("file://") || /^[A-Za-z]:[\\/]/.test(value)) {
14
+ return null;
15
+ }
16
+
17
+ let host: string;
18
+ let path: string;
19
+ const scheme = /^[a-z][a-z0-9+.-]*:\/\//i.exec(value);
20
+ if (scheme) {
21
+ value = value.slice(scheme[0].length);
22
+ const slash = value.indexOf("/");
23
+ host = slash === -1 ? value : value.slice(0, slash);
24
+ path = slash === -1 ? "" : value.slice(slash + 1);
25
+ } else {
26
+ // scp-like: [user@]host:owner/repo
27
+ const colon = value.indexOf(":");
28
+ if (colon === -1) return null;
29
+ host = value.slice(0, colon);
30
+ path = value.slice(colon + 1);
31
+ }
32
+
33
+ host = host.replace(/^[^@]*@/, "").replace(/:\d+$/, "").toLowerCase();
34
+ path = path
35
+ .replace(/[?#].*$/, "")
36
+ .replace(/\/+$/, "")
37
+ .replace(/\.git$/i, "")
38
+ .replace(/^\/+/, "");
39
+ if (!host || !path) return null;
40
+ return `${host}/${path}`;
41
+ }
42
+
43
+ function lastSegment(value: string): string {
44
+ const parts = value.split(/[\\/]/).filter(Boolean);
45
+ return parts[parts.length - 1] ?? value;
46
+ }
47
+
48
+ export function remoteProject(normalized: string): ProjectRef {
49
+ return { key: `remote:${normalized}`, label: lastSegment(normalized) };
50
+ }
51
+
52
+ export function pathProject(absolutePath: string): ProjectRef {
53
+ const trimmed = absolutePath.length > 1 ? absolutePath.replace(/[\\/]+$/, "") : absolutePath;
54
+ return { key: `path:${trimmed}`, label: lastSegment(trimmed) || trimmed };
55
+ }
@@ -0,0 +1,9 @@
1
+ export interface InboxCommand {
2
+ /** Empty: star the current agent; otherwise save as scratch. */
3
+ text: string;
4
+ }
5
+
6
+ /** The whole argument is scratch text as typed; there are no options. */
7
+ export function parseInboxCommand(args: string): InboxCommand {
8
+ return { text: args.trim() };
9
+ }