@parallelworks/code 0.1.0 → 0.2.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 (70) hide show
  1. package/README.md +138 -24
  2. package/dist/api.d.ts +3469 -0
  3. package/dist/apiClient.d.ts +26 -0
  4. package/dist/apiClient.js +5 -0
  5. package/dist/claudeApi.d.ts +27 -0
  6. package/dist/claudeApi.js +250 -0
  7. package/dist/command.d.ts +47 -0
  8. package/dist/command.js +64 -0
  9. package/dist/commandsApi.d.ts +64 -0
  10. package/dist/commandsApi.js +267 -0
  11. package/dist/createPwCodeApi.d.ts +688 -0
  12. package/dist/createPwCodeApi.js +31 -0
  13. package/dist/index.d.ts +16 -3
  14. package/dist/index.js +16 -3
  15. package/dist/locales/en/agentTranscript.js +170 -0
  16. package/dist/locales/en/agents.js +380 -0
  17. package/dist/locales/en.d.ts +531 -0
  18. package/dist/locales/en.js +8 -0
  19. package/dist/locales/es/agentTranscript.js +170 -0
  20. package/dist/locales/es/agents.js +380 -0
  21. package/dist/locales/es.d.ts +3 -0
  22. package/dist/locales/es.js +8 -0
  23. package/dist/locales/ja/agentTranscript.js +170 -0
  24. package/dist/locales/ja/agents.js +380 -0
  25. package/dist/locales/ja.d.ts +3 -0
  26. package/dist/locales/ja.js +8 -0
  27. package/dist/locales/ko/agentTranscript.js +170 -0
  28. package/dist/locales/ko/agents.js +380 -0
  29. package/dist/locales/ko.d.ts +3 -0
  30. package/dist/locales/ko.js +8 -0
  31. package/dist/locales/zh/agentTranscript.js +170 -0
  32. package/dist/locales/zh/agents.js +380 -0
  33. package/dist/locales/zh.d.ts +3 -0
  34. package/dist/locales/zh.js +8 -0
  35. package/dist/machine.d.ts +49 -0
  36. package/dist/machine.js +60 -0
  37. package/dist/messages.d.ts +17 -0
  38. package/dist/messages.js +31 -0
  39. package/dist/notices.d.ts +11 -0
  40. package/dist/notices.js +94 -0
  41. package/dist/pullRequest.d.ts +8 -0
  42. package/dist/pullRequest.js +29 -0
  43. package/dist/query.d.ts +28 -0
  44. package/dist/query.js +25 -0
  45. package/dist/session.d.ts +70 -1
  46. package/dist/session.js +101 -1
  47. package/dist/sessionEvents.d.ts +27 -0
  48. package/dist/sessionEvents.js +212 -0
  49. package/dist/sessionsApi.d.ts +105 -0
  50. package/dist/sessionsApi.js +513 -0
  51. package/dist/toolStrings.d.ts +4 -0
  52. package/dist/toolStrings.js +95 -0
  53. package/dist/transcript.d.ts +12 -1
  54. package/dist/transcript.js +40 -2
  55. package/dist/types.d.ts +20 -1
  56. package/dist/useTranscript.d.ts +4 -1
  57. package/dist/useTranscript.js +54 -11
  58. package/dist/wording.d.ts +43 -0
  59. package/dist/wording.js +101 -0
  60. package/locales/en/agentTranscript.json +162 -0
  61. package/locales/en/agents.json +366 -0
  62. package/locales/es/agentTranscript.json +162 -0
  63. package/locales/es/agents.json +366 -0
  64. package/locales/ja/agentTranscript.json +162 -0
  65. package/locales/ja/agents.json +366 -0
  66. package/locales/ko/agentTranscript.json +162 -0
  67. package/locales/ko/agents.json +366 -0
  68. package/locales/zh/agentTranscript.json +162 -0
  69. package/locales/zh/agents.json +366 -0
  70. package/package.json +23 -8
@@ -0,0 +1,60 @@
1
+ // src/machine.ts
2
+ /** A computer's daemon connected itself; every other machine is a resource
3
+ * reached through its pw agent. */
4
+ function isComputer(machine) {
5
+ return machine.kind === "local";
6
+ }
7
+ /** The pw code command that picks a session up. A resource's daemon answers
8
+ * any terminal signed in to pw; a computer's only that computer. */
9
+ function terminalHandoff(machine, sessionId, username) {
10
+ if (isComputer(machine)) return {
11
+ on: "computer",
12
+ command: `pw code -r ${sessionId}`,
13
+ host: machine.hostname || machine.name
14
+ };
15
+ const resource = machine.owner && machine.owner !== username ? `pw://${machine.owner}/${machine.name}` : machine.name;
16
+ const args = [
17
+ "code",
18
+ "attach",
19
+ `${resource}/${sessionId}`
20
+ ];
21
+ return {
22
+ on: "resource",
23
+ command: `pw ${args.join(" ")}`,
24
+ args,
25
+ resource
26
+ };
27
+ }
28
+ function splitMachines(machines) {
29
+ return {
30
+ computers: machines.filter(isComputer),
31
+ resources: machines.filter((m) => !isComputer(m))
32
+ };
33
+ }
34
+ function isConnected(machine) {
35
+ return machine?.status === "connected";
36
+ }
37
+ /** A machine the listing does not know is not down: only one that reports a
38
+ * status other than connected is. */
39
+ function isMachineDown(machine) {
40
+ return !!machine && !isConnected(machine);
41
+ }
42
+ var unreachableCodes = /* @__PURE__ */ new Set([
43
+ "agents_unreachable",
44
+ "agents_no_daemon",
45
+ "agents_no_agent"
46
+ ]);
47
+ /** A request that failed because pw code on the machine could not be reached. */
48
+ function isUnreachableError(error) {
49
+ const code = error?.code;
50
+ return typeof code === "string" && unreachableCodes.has(code);
51
+ }
52
+ function machinesById(machines) {
53
+ return new Map(machines.map((m) => [m.id, m]));
54
+ }
55
+ /** Only a machine whose owner turned on starting from another client lets one
56
+ * start a session; every other machine only shows what its owner opened. */
57
+ function canStartHere(machine) {
58
+ return isConnected(machine) && !!machine.remoteStart;
59
+ }
60
+ export { canStartHere, isComputer, isConnected, isMachineDown, isUnreachableError, machinesById, splitMachines, terminalHandoff };
@@ -0,0 +1,17 @@
1
+ import { type createTranslator } from 'use-intl';
2
+ import type en from './locales/en.js';
3
+ /** pw code's messages in one language, by namespace, for a host to merge into
4
+ * its own. Typed from the English catalogs, which every language matches. */
5
+ export type PwCodeMessages = typeof en;
6
+ export type PwCodeNamespace = keyof PwCodeMessages;
7
+ /** A use-intl translator over one of pw code's namespaces. */
8
+ export type PwCodeTranslator<N extends PwCodeNamespace> = ReturnType<typeof createTranslator<PwCodeMessages, N>>;
9
+ export declare const pwCodeNamespaces: readonly ["agentTranscript", "agents"];
10
+ export declare const pwCodeLocales: readonly ['en', 'es', 'ja', 'ko', 'zh'];
11
+ export type PwCodeLocale = (typeof pwCodeLocales)[number];
12
+ export declare function isPwCodeLocale(locale: string): locale is PwCodeLocale;
13
+ /** pw code's messages in one of `pwCodeLocales`; any other locale rejects. */
14
+ export declare function loadPwCodeMessages(locale: string): Promise<PwCodeMessages>;
15
+ /** use-intl's useTranslations, typed from pw code's catalogs whatever
16
+ * messages the host declares to use-intl. */
17
+ export declare function usePwCodeTranslations<N extends PwCodeNamespace>(namespace: N): PwCodeTranslator<N>;
@@ -0,0 +1,31 @@
1
+ import { useTranslations } from "use-intl";
2
+ // src/messages.ts
3
+ var pwCodeNamespaces = ["agentTranscript", "agents"];
4
+ var pwCodeLocales = [
5
+ "en",
6
+ "es",
7
+ "ja",
8
+ "ko",
9
+ "zh"
10
+ ];
11
+ var catalogs = {
12
+ en: () => import("./locales/en.js"),
13
+ es: () => import("./locales/es.js"),
14
+ ja: () => import("./locales/ja.js"),
15
+ ko: () => import("./locales/ko.js"),
16
+ zh: () => import("./locales/zh.js")
17
+ };
18
+ function isPwCodeLocale(locale) {
19
+ return pwCodeLocales.includes(locale);
20
+ }
21
+ /** pw code's messages in one of `pwCodeLocales`; any other locale rejects. */
22
+ function loadPwCodeMessages(locale) {
23
+ if (!isPwCodeLocale(locale)) return Promise.reject(/* @__PURE__ */ new Error(`no pw code messages for ${locale}`));
24
+ return catalogs[locale]().then((module) => module.default);
25
+ }
26
+ /** use-intl's useTranslations, typed from pw code's catalogs whatever
27
+ * messages the host declares to use-intl. */
28
+ function usePwCodeTranslations(namespace) {
29
+ return useTranslations(namespace);
30
+ }
31
+ export { isPwCodeLocale, loadPwCodeMessages, pwCodeLocales, pwCodeNamespaces, usePwCodeTranslations };
@@ -0,0 +1,11 @@
1
+ import { type PwCodeTranslator } from './messages.js';
2
+ import type { CompactionNotice, RecapNotice, TranscriptWords } from './transcript.js';
3
+ /** When a usage limit resets, as a session's notices name it. */
4
+ export declare function useResumeTime(): (at: string) => string;
5
+ export declare function useCompactionNotice(): CompactionNotice;
6
+ export declare function useRecapNotice(): RecapNotice;
7
+ /** How long a turn took, as the terminal says it: 42s, 2m 5s, 1h 4m. */
8
+ export declare function turnDuration(t: PwCodeTranslator<'agents'>, ms: number): string;
9
+ /** The session's own lines: what a goal step opens to, how a turn ended,
10
+ * which plan a /plan showed, and how a background task reported back. */
11
+ export declare function useTranscriptWords(): TranscriptWords;
@@ -0,0 +1,94 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { useCallback, useMemo } from "react";
3
+ import { DateTime } from "luxon";
4
+ import { sanitizeLabel } from "@parallelworks/ui/ai/headless";
5
+ import { useFormatter } from "use-intl";
6
+ // src/notices.ts
7
+ /** When a usage limit resets, as a session's notices name it. */
8
+ function useResumeTime() {
9
+ const format = useFormatter();
10
+ return useCallback((at) => format.dateTime(DateTime.fromISO(at).toJSDate(), {
11
+ dateStyle: "medium",
12
+ timeStyle: "short"
13
+ }), [format]);
14
+ }
15
+ function useCompactionNotice() {
16
+ const t = usePwCodeTranslations("agents");
17
+ return useMemo(() => ({
18
+ command: t("detail.compacted"),
19
+ automatic: t("detail.compactedAutomatically")
20
+ }), [t]);
21
+ }
22
+ function useRecapNotice() {
23
+ const t = usePwCodeTranslations("agents");
24
+ return useCallback((recap) => t("detail.recap", { recap }), [t]);
25
+ }
26
+ /** How long a turn took, as the terminal says it: 42s, 2m 5s, 1h 4m. */
27
+ function turnDuration(t, ms) {
28
+ const total = Math.round(ms / 1e3);
29
+ if (total < 60) return t("detail.turnSeconds", { seconds: total });
30
+ if (total < 3600) return t("detail.turnMinutes", {
31
+ minutes: Math.floor(total / 60),
32
+ seconds: total % 60
33
+ });
34
+ return t("detail.turnHours", {
35
+ hours: Math.floor(total / 3600),
36
+ minutes: Math.floor(total / 60) % 60
37
+ });
38
+ }
39
+ /** The session's own lines: what a goal step opens to, how a turn ended,
40
+ * which plan a /plan showed, and how a background task reported back. */
41
+ function useTranscriptWords() {
42
+ const t = usePwCodeTranslations("agents");
43
+ const tTranscript = usePwCodeTranslations("agentTranscript");
44
+ const format = useFormatter();
45
+ return useMemo(() => ({
46
+ goalDetail: (p) => t("detail.goalDetail", {
47
+ condition: p.condition ?? "",
48
+ reason: p.reason ?? ""
49
+ }),
50
+ turnEnd: (te, verb, waiting) => {
51
+ if (waiting) return t("detail.turnEndWaiting", { count: te.pendingAgents ?? 0 });
52
+ const ended = DateTime.fromISO(te.endedAt);
53
+ const days = Math.floor(DateTime.now().startOf("day").diff(ended.startOf("day"), "days").days);
54
+ const time = format.dateTime(ended.toJSDate(), {
55
+ hour: "numeric",
56
+ minute: "2-digit",
57
+ ...days > 0 ? { weekday: "long" } : {},
58
+ ...days >= 7 ? {
59
+ month: "short",
60
+ day: "numeric"
61
+ } : {}
62
+ });
63
+ return t("detail.turnEnd", {
64
+ verb,
65
+ duration: turnDuration(t, te.durationMs),
66
+ time
67
+ });
68
+ },
69
+ planAnswer: (path, opened) => opened ? t("detail.planOpened", { path }) : path,
70
+ deliveryLine: (n) => {
71
+ const name = sanitizeLabel(n.description) || n.id;
72
+ if (n.interim) return t("detail.subagentMessage", { name });
73
+ if (n.shell) return n.exitCode ? t("detail.commandFailed", {
74
+ name,
75
+ code: n.exitCode
76
+ }) : t("detail.commandCompleted", { name });
77
+ const outcome = n.failed ? "failed" : "finished";
78
+ return n.elapsedMs ? t("detail.agentEndedAfter", {
79
+ name,
80
+ outcome,
81
+ elapsed: turnDuration(t, n.elapsedMs)
82
+ }) : t("detail.agentEnded", {
83
+ name,
84
+ outcome
85
+ });
86
+ },
87
+ allowDirectory: ({ path, subtree }) => subtree ? tTranscript("transcript.allowDirectoryTree", { path }) : tTranscript("transcript.allowDirectoryOnly", { path })
88
+ }), [
89
+ t,
90
+ tTranscript,
91
+ format
92
+ ]);
93
+ }
94
+ export { turnDuration, useCompactionNotice, useRecapNotice, useResumeTime, useTranscriptWords };
@@ -0,0 +1,8 @@
1
+ /** owner/repo#number, or group/project!number for a GitLab merge request; null for anything but a plain URL of one. */
2
+ export declare function pullRequestLabel(url: string | undefined): string | null;
3
+ /** The `pullRequestLabel` of a pull or merge request link as copied, even one to a comment. */
4
+ export declare function pastedPullRequestLabel(text: string): string | null;
5
+ /** repo#number, or project!number, from the `pullRequestLabel`. */
6
+ export declare function pullRequestShortLabel(pr: string): string;
7
+ /** What the forge of a `pullRequestLabel` calls it: GitLab writes a merge request with `!`. */
8
+ export declare function pullRequestKind(pr: string): 'pullRequest' | 'mergeRequest';
@@ -0,0 +1,29 @@
1
+ // src/pullRequest.ts
2
+ var pullRequestUrl = /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)$/;
3
+ var mergeRequestUrl = /^https?:\/\/[a-zA-Z0-9][\w.-]*(?::\d+)?\/([\w.-]+(?:\/[\w.-]+)+)\/-\/merge_requests\/(\d+)$/;
4
+ /** owner/repo#number, or group/project!number for a GitLab merge request; null for anything but a plain URL of one. */
5
+ function pullRequestLabel(url) {
6
+ const pr = url?.match(pullRequestUrl);
7
+ if (pr) return `${pr[1]}#${pr[2]}`;
8
+ const mr = url?.match(mergeRequestUrl);
9
+ return mr ? `${mr[1]}!${mr[2]}` : null;
10
+ }
11
+ var pastedPullRequestUrl = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)(?:[/?#]\S*)?$/i;
12
+ var pastedMergeRequestUrl = /^(?:https?:\/\/)?[a-z0-9][\w.-]*(?::\d+)?\/([\w.-]+(?:\/[\w.-]+)+)\/-\/merge_requests\/(\d+)(?:[/?#]\S*)?$/i;
13
+ /** The `pullRequestLabel` of a pull or merge request link as copied, even one to a comment. */
14
+ function pastedPullRequestLabel(text) {
15
+ const pasted = text.trim();
16
+ const pr = pasted.match(pastedPullRequestUrl);
17
+ if (pr) return `${pr[1]}#${pr[2]}`;
18
+ const mr = pasted.match(pastedMergeRequestUrl);
19
+ return mr ? `${mr[1]}!${mr[2]}` : null;
20
+ }
21
+ /** repo#number, or project!number, from the `pullRequestLabel`. */
22
+ function pullRequestShortLabel(pr) {
23
+ return pr.slice(pr.lastIndexOf("/") + 1);
24
+ }
25
+ /** What the forge of a `pullRequestLabel` calls it: GitLab writes a merge request with `!`. */
26
+ function pullRequestKind(pr) {
27
+ return pr.includes("!") ? "mergeRequest" : "pullRequest";
28
+ }
29
+ export { pastedPullRequestLabel, pullRequestKind, pullRequestLabel, pullRequestShortLabel };
@@ -0,0 +1,28 @@
1
+ import type { MaybeOptionalInit } from 'openapi-fetch';
2
+ import { type SWRConfiguration, type SWRResponse } from 'swr';
3
+ import { type PwCodeApiError, type PwCodeClient, type PwCodePaths } from './apiClient.js';
4
+ /** The routes this package reads with GET. */
5
+ export type ReadPath = {
6
+ [P in keyof PwCodePaths]: PwCodePaths[P] extends {
7
+ get: object;
8
+ } ? P : never;
9
+ }[keyof PwCodePaths];
10
+ type ReadInit<P extends ReadPath> = MaybeOptionalInit<PwCodePaths[P], 'get'>;
11
+ /** What a GET of `P` answers with. */
12
+ export type ReadData<P extends ReadPath> = PwCodePaths[P] extends {
13
+ get: {
14
+ responses: {
15
+ 200: {
16
+ content: {
17
+ 'application/json': infer D;
18
+ };
19
+ };
20
+ };
21
+ };
22
+ } ? D : never;
23
+ /** A data hook over `client` that keys each read `[prefix, path, init]`, or
24
+ * `null` to skip it, and fetches it, as swr-openapi's query hook does: a host
25
+ * reading the same routes through `@parallelworks/client/swr` shares each
26
+ * cache entry with it. It throws the client's error, so SWR keeps it. */
27
+ export declare function createQuery(client: PwCodeClient): <P extends ReadPath>(path: P, init: ReadInit<P> | null, config?: SWRConfiguration<ReadData<P>, PwCodeApiError>) => SWRResponse<ReadData<P>, PwCodeApiError>;
28
+ export {};
package/dist/query.js ADDED
@@ -0,0 +1,25 @@
1
+ import "./apiClient.js";
2
+ import { useCallback, useMemo } from "react";
3
+ import useSWR from "swr";
4
+ // src/query.ts
5
+ /** A data hook over `client` that keys each read `[prefix, path, init]`, or
6
+ * `null` to skip it, and fetches it, as swr-openapi's query hook does: a host
7
+ * reading the same routes through `@parallelworks/client/swr` shares each
8
+ * cache entry with it. It throws the client's error, so SWR keeps it. */
9
+ function createQuery(client) {
10
+ const reader = client;
11
+ return function useQuery(path, init, config) {
12
+ const key = useMemo(() => init !== null ? [
13
+ "api",
14
+ path,
15
+ init
16
+ ] : null, [path, init]);
17
+ const fetcher = useCallback(async ([, route, options]) => {
18
+ const { data, error } = await reader.GET(route, options);
19
+ if (error) throw error;
20
+ return data;
21
+ }, []);
22
+ return useSWR(key, fetcher, config);
23
+ };
24
+ }
25
+ export { createQuery };
package/dist/session.d.ts CHANGED
@@ -1,3 +1,72 @@
1
- import type { PwCodeSessionStatus } from './types.js';
1
+ import { type PwCodeMachine } from './machine.js';
2
+ import type { PwCodeApprovalRequest, PwCodeSessionStatus } from './types.js';
3
+ /** A session as the sessions listing has it, as far as the shared logic reads
4
+ * it. A host that types its API from a spec asserts its type extends this. */
5
+ export interface PwCodeSession {
6
+ machineId: string;
7
+ id: string;
8
+ status: PwCodeSessionStatus;
9
+ /** The name the reader gave the session. */
10
+ name?: string | undefined;
11
+ /** The name the session gave itself. */
12
+ autoName?: string | undefined;
13
+ /** The start of its first prompt, once the model has answered it. */
14
+ preview?: string | undefined;
15
+ /** The host whose client holds the session, while one does. */
16
+ liveHost?: string | undefined;
17
+ archivedAt?: string | undefined;
18
+ updatedAt?: string | undefined;
19
+ turnStartedAt?: string | undefined;
20
+ workspace?: string | undefined;
21
+ }
22
+ /** The approvals a session waits on, as far as their kinds. */
23
+ export type PwCodePendingApprovals = readonly Pick<PwCodeApprovalRequest, 'kind'>[] | null | undefined;
2
24
  /** The tone a session's status shows in; a web host passes it to a status badge. */
3
25
  export declare function sessionStatusVariant(status: PwCodeSessionStatus): 'info' | 'warning' | 'muted';
26
+ export declare function sessionKey(s: Pick<PwCodeSession, 'machineId' | 'id'>): string;
27
+ export declare function isSession(s: Pick<PwCodeSession, 'machineId' | 'id'>, machine: string | undefined, id: string | undefined): boolean;
28
+ /** A computer listed only as the resource reaching its daemon matches by daemonId. */
29
+ export declare function sharedStoreCopy<S extends Pick<PwCodeSession, 'machineId' | 'id'>>(list: {
30
+ machines?: readonly Pick<PwCodeMachine, 'id' | 'daemonId' | 'storeId'>[] | null | undefined;
31
+ sessions?: readonly S[] | null | undefined;
32
+ } | undefined, machine: string, id: string): S | undefined;
33
+ /** A session held only by its questions wants an answer, not an approval. */
34
+ export declare function waitsOnAnswer(approvals: PwCodePendingApprovals): boolean;
35
+ /** Machines with nothing on them do not earn a name on every row. */
36
+ export declare function spansMachines(sessions: readonly Pick<PwCodeSession, 'machineId'>[]): boolean;
37
+ export declare function pathBasename(path: string): string;
38
+ /** A running row's clock is how long its turn has run, not when its transcript
39
+ * last changed; a turn the daemon could not date falls back to the latter. */
40
+ export declare function sessionClock(s: Pick<PwCodeSession, 'status' | 'turnStartedAt' | 'updatedAt'>, compact: (iso: string | undefined) => string): string;
41
+ /** The status alone misses a session that is attached but resting between
42
+ * turns, which the daemon reports as idle. */
43
+ export declare function isActiveSession(s: Pick<PwCodeSession, 'status' | 'liveHost'>): boolean;
44
+ /** The daemon lists archived sessions too and leaves hiding them to its clients. */
45
+ export declare function isArchived(s: Pick<PwCodeSession, 'archivedAt'>): boolean;
46
+ /** A turn is in flight: there is work to stop, and the daemon refuses a fork. */
47
+ export declare function isMidTurn(s: Pick<PwCodeSession, 'status'>): boolean;
48
+ /** A dropped machine outranks the session state: it reads as the machine's
49
+ * problem, not the session's. `idle` is what a resting session shows, the
50
+ * live green for its dot and the muted ink for its text. */
51
+ export declare function sessionVariant<T extends string>(status: PwCodeSessionStatus, machine: Pick<PwCodeMachine, 'status'> | undefined, idle: T): T | 'error' | ReturnType<typeof sessionStatusVariant>;
52
+ /** An approval on a machine that stopped answering cannot be acted on. */
53
+ export declare function needsYou(s: Pick<PwCodeSession, 'status' | 'archivedAt'>, machine: Pick<PwCodeMachine, 'status'> | undefined): boolean;
54
+ export interface RecentDirectory {
55
+ path: string;
56
+ name: string;
57
+ sessions: number;
58
+ updatedAt: string;
59
+ }
60
+ /** The daemon offers no way to browse, so the machine's own sessions are the
61
+ * only paths we can honestly suggest. */
62
+ export declare function recentDirectories(sessions: readonly Pick<PwCodeSession, 'machineId' | 'workspace' | 'updatedAt'>[], machineId: string | undefined): RecentDirectory[];
63
+ export declare function newestFirst<T extends {
64
+ updatedAt?: string | undefined;
65
+ }>(items: readonly T[]): T[];
66
+ /** An approval blocks the agent and goes first; a running turn is context;
67
+ * everything else is what the reader last touched, newest first. */
68
+ export declare function triageSessions<S extends Pick<PwCodeSession, 'machineId' | 'status' | 'archivedAt' | 'updatedAt'>>(sessions: readonly S[], machineById: ReadonlyMap<string, Pick<PwCodeMachine, 'status'>>): {
69
+ blocked: S[];
70
+ active: S[];
71
+ idle: S[];
72
+ };
package/dist/session.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { isConnected, isMachineDown, machinesById } from "./machine.js";
2
+ import { DateTime } from "luxon";
1
3
  // src/session.ts
2
4
  /** The tone a session's status shows in; a web host passes it to a status badge. */
3
5
  function sessionStatusVariant(status) {
@@ -8,4 +10,102 @@ function sessionStatusVariant(status) {
8
10
  default: return "muted";
9
11
  }
10
12
  }
11
- export { sessionStatusVariant };
13
+ function sessionKey(s) {
14
+ return `${s.machineId}/${s.id}`;
15
+ }
16
+ function isSession(s, machine, id) {
17
+ return s.machineId === machine && s.id === id;
18
+ }
19
+ /** A computer listed only as the resource reaching its daemon matches by daemonId. */
20
+ function sharedStoreCopy(list, machine, id) {
21
+ const machines = list?.machines ?? [];
22
+ const sessions = list?.sessions ?? [];
23
+ const store = machines.find((m) => m.id === machine || m.daemonId === machine)?.storeId;
24
+ if (!store || sessions.some((s) => isSession(s, machine, id))) return;
25
+ const byId = machinesById(machines);
26
+ return sessions.find((s) => s.id === id && byId.get(s.machineId)?.storeId === store);
27
+ }
28
+ /** A session held only by its questions wants an answer, not an approval. */
29
+ function waitsOnAnswer(approvals) {
30
+ return !!approvals?.length && approvals.every((a) => a.kind === "ask");
31
+ }
32
+ /** Machines with nothing on them do not earn a name on every row. */
33
+ function spansMachines(sessions) {
34
+ return new Set(sessions.map((s) => s.machineId)).size > 1;
35
+ }
36
+ function pathBasename(path) {
37
+ return path.split("/").filter(Boolean).pop() ?? path;
38
+ }
39
+ /** A running row's clock is how long its turn has run, not when its transcript
40
+ * last changed; a turn the daemon could not date falls back to the latter. */
41
+ function sessionClock(s, compact) {
42
+ return compact(s.status === "running" && s.turnStartedAt ? s.turnStartedAt : s.updatedAt);
43
+ }
44
+ /** The status alone misses a session that is attached but resting between
45
+ * turns, which the daemon reports as idle. */
46
+ function isActiveSession(s) {
47
+ return !!s.liveHost || s.status !== "idle";
48
+ }
49
+ /** The daemon lists archived sessions too and leaves hiding them to its clients. */
50
+ function isArchived(s) {
51
+ return !!s.archivedAt;
52
+ }
53
+ /** A turn is in flight: there is work to stop, and the daemon refuses a fork. */
54
+ function isMidTurn(s) {
55
+ return s.status === "running" || s.status === "awaiting_approval";
56
+ }
57
+ /** A dropped machine outranks the session state: it reads as the machine's
58
+ * problem, not the session's. `idle` is what a resting session shows, the
59
+ * live green for its dot and the muted ink for its text. */
60
+ function sessionVariant(status, machine, idle) {
61
+ if (isMachineDown(machine)) return "error";
62
+ return status === "idle" ? idle : sessionStatusVariant(status);
63
+ }
64
+ /** An approval on a machine that stopped answering cannot be acted on. */
65
+ function needsYou(s, machine) {
66
+ return !isArchived(s) && s.status === "awaiting_approval" && isConnected(machine);
67
+ }
68
+ /** The daemon offers no way to browse, so the machine's own sessions are the
69
+ * only paths we can honestly suggest. */
70
+ function recentDirectories(sessions, machineId) {
71
+ if (!machineId) return [];
72
+ const byPath = /* @__PURE__ */ new Map();
73
+ for (const s of sessions) {
74
+ if (s.machineId !== machineId || !s.workspace) continue;
75
+ const found = byPath.get(s.workspace);
76
+ if (found) {
77
+ found.sessions += 1;
78
+ if (updatedMillis(s) > updatedMillis(found)) found.updatedAt = s.updatedAt ?? "";
79
+ continue;
80
+ }
81
+ byPath.set(s.workspace, {
82
+ path: s.workspace,
83
+ name: pathBasename(s.workspace),
84
+ sessions: 1,
85
+ updatedAt: s.updatedAt ?? ""
86
+ });
87
+ }
88
+ return newestFirst([...byPath.values()]);
89
+ }
90
+ /** An unparseable timestamp would make the comparator return NaN, which leaves
91
+ * the sort order up to the engine. */
92
+ function updatedMillis(item) {
93
+ const millis = DateTime.fromISO(item.updatedAt ?? "").toMillis();
94
+ return Number.isFinite(millis) ? millis : 0;
95
+ }
96
+ function newestFirst(items) {
97
+ return [...items].sort((a, b) => updatedMillis(b) - updatedMillis(a));
98
+ }
99
+ /** An approval blocks the agent and goes first; a running turn is context;
100
+ * everything else is what the reader last touched, newest first. */
101
+ function triageSessions(sessions, machineById) {
102
+ const ordered = newestFirst(sessions.filter((s) => !isArchived(s)));
103
+ const blocked = ordered.filter((s) => needsYou(s, machineById.get(s.machineId)));
104
+ const rest = ordered.filter((s) => !blocked.includes(s));
105
+ return {
106
+ blocked,
107
+ active: rest.filter((s) => s.status === "running"),
108
+ idle: rest.filter((s) => s.status !== "running")
109
+ };
110
+ }
111
+ export { isActiveSession, isArchived, isMidTurn, isSession, needsYou, newestFirst, pathBasename, recentDirectories, sessionClock, sessionKey, sessionStatusVariant, sessionVariant, sharedStoreCopy, spansMachines, triageSessions, waitsOnAnswer };
@@ -0,0 +1,27 @@
1
+ import type { Schemas } from './apiClient.js';
2
+ type StreamEvent = Schemas['AgentStreamEvent'];
3
+ type Machine = Schemas['AgentMachine'];
4
+ export interface PwCodeSocketOptions {
5
+ /** Opens a WebSocket to `path` on the platform's host, signed in as the API
6
+ * client is. Resolving asynchronously lets a host fetch a token first. Each
7
+ * reconnect calls it again, with the path resuming after the last frame. */
8
+ openSocket?: ((path: string) => WebSocket | Promise<WebSocket>) | undefined;
9
+ /** Whether the app is out of sight, where animation frames do not run, so
10
+ * frames are applied as they arrive. */
11
+ hidden?: (() => boolean) | undefined;
12
+ }
13
+ /** The path a session's event feed is served at, resuming after frame `after`. */
14
+ export declare function sessionEventsPath(machine: string, id: string, after: number): string;
15
+ /** Frames after which the list of subagents may read differently: one started
16
+ * or ended, one asked for or got an approval, or a turn began or closed. */
17
+ export declare function changesSubagents(ev: StreamEvent): boolean;
18
+ /** `machines` with each one in `fed` that the listing lost counted as connected. */
19
+ export declare function reachedByFeed(machines: Machine[], fed: ReadonlySet<string>): Machine[];
20
+ export declare function sessionEvents({ openSocket, hidden }: PwCodeSocketOptions): {
21
+ useSessionEvents: (machine: string, id: string, cursor: (() => number) | undefined, onEvent: (event: StreamEvent) => void) => {
22
+ connected: boolean;
23
+ disconnected: boolean;
24
+ };
25
+ useFedMachines: () => ReadonlySet<string>;
26
+ };
27
+ export {};