@parallelworks/code 0.1.0 → 0.3.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 (118) hide show
  1. package/README.md +171 -24
  2. package/dist/ago.d.ts +8 -0
  3. package/dist/ago.js +26 -0
  4. package/dist/api.d.ts +3547 -0
  5. package/dist/apiClient.d.ts +26 -0
  6. package/dist/apiClient.js +5 -0
  7. package/dist/base64.d.ts +3 -0
  8. package/dist/base64.js +15 -0
  9. package/dist/chatHandoff.d.ts +12 -0
  10. package/dist/chatHandoff.js +27 -0
  11. package/dist/claudeAccounts.d.ts +112 -0
  12. package/dist/claudeAccounts.js +234 -0
  13. package/dist/claudeApi.d.ts +27 -0
  14. package/dist/claudeApi.js +250 -0
  15. package/dist/claudeSignIn.d.ts +62 -0
  16. package/dist/claudeSignIn.js +239 -0
  17. package/dist/command.d.ts +47 -0
  18. package/dist/command.js +64 -0
  19. package/dist/commandsApi.d.ts +64 -0
  20. package/dist/commandsApi.js +267 -0
  21. package/dist/contextRow.d.ts +25 -0
  22. package/dist/contextRow.js +16 -0
  23. package/dist/createPwCodeApi.d.ts +696 -0
  24. package/dist/createPwCodeApi.js +33 -0
  25. package/dist/howSessionsAppear.d.ts +12 -0
  26. package/dist/howSessionsAppear.js +24 -0
  27. package/dist/index.d.ts +39 -3
  28. package/dist/index.js +38 -3
  29. package/dist/locales/en/agentTranscript.js +162 -0
  30. package/dist/locales/en/agents.js +380 -0
  31. package/dist/locales/en.d.ts +523 -0
  32. package/dist/locales/en.js +8 -0
  33. package/dist/locales/es/agentTranscript.js +162 -0
  34. package/dist/locales/es/agents.js +380 -0
  35. package/dist/locales/es.d.ts +3 -0
  36. package/dist/locales/es.js +8 -0
  37. package/dist/locales/ja/agentTranscript.js +162 -0
  38. package/dist/locales/ja/agents.js +380 -0
  39. package/dist/locales/ja.d.ts +3 -0
  40. package/dist/locales/ja.js +8 -0
  41. package/dist/locales/ko/agentTranscript.js +162 -0
  42. package/dist/locales/ko/agents.js +380 -0
  43. package/dist/locales/ko.d.ts +3 -0
  44. package/dist/locales/ko.js +8 -0
  45. package/dist/locales/zh/agentTranscript.js +162 -0
  46. package/dist/locales/zh/agents.js +380 -0
  47. package/dist/locales/zh.d.ts +3 -0
  48. package/dist/locales/zh.js +8 -0
  49. package/dist/machine.d.ts +51 -0
  50. package/dist/machine.js +60 -0
  51. package/dist/messages.d.ts +17 -0
  52. package/dist/messages.js +31 -0
  53. package/dist/models.d.ts +47 -0
  54. package/dist/models.js +49 -0
  55. package/dist/notices.d.ts +12 -0
  56. package/dist/notices.js +120 -0
  57. package/dist/pullRequest.d.ts +8 -0
  58. package/dist/pullRequest.js +29 -0
  59. package/dist/pullRequestList.d.ts +52 -0
  60. package/dist/pullRequestList.js +106 -0
  61. package/dist/query.d.ts +28 -0
  62. package/dist/query.js +25 -0
  63. package/dist/session.d.ts +75 -1
  64. package/dist/session.js +101 -1
  65. package/dist/sessionActions.d.ts +105 -0
  66. package/dist/sessionActions.js +178 -0
  67. package/dist/sessionEvents.d.ts +27 -0
  68. package/dist/sessionEvents.js +212 -0
  69. package/dist/sessionGroups.d.ts +49 -0
  70. package/dist/sessionGroups.js +72 -0
  71. package/dist/sessionHeader.d.ts +14 -0
  72. package/dist/sessionHeader.js +16 -0
  73. package/dist/sessionList.d.ts +134 -0
  74. package/dist/sessionList.js +271 -0
  75. package/dist/sessionsApi.d.ts +105 -0
  76. package/dist/sessionsApi.js +511 -0
  77. package/dist/settingsApi.d.ts +36 -0
  78. package/dist/settingsApi.js +151 -0
  79. package/dist/startSession.d.ts +138 -0
  80. package/dist/startSession.js +234 -0
  81. package/dist/terminalHandoffPanel.d.ts +30 -0
  82. package/dist/terminalHandoffPanel.js +33 -0
  83. package/dist/toolStrings.d.ts +4 -0
  84. package/dist/toolStrings.js +95 -0
  85. package/dist/transcript.d.ts +14 -1
  86. package/dist/transcript.js +55 -14
  87. package/dist/types.d.ts +20 -1
  88. package/dist/usageLimit.d.ts +8 -0
  89. package/dist/usageLimit.js +13 -0
  90. package/dist/useAwayRecap.d.ts +30 -0
  91. package/dist/useAwayRecap.js +75 -0
  92. package/dist/useComposer.d.ts +121 -0
  93. package/dist/useComposer.js +244 -0
  94. package/dist/useComposerImages.d.ts +66 -0
  95. package/dist/useComposerImages.js +195 -0
  96. package/dist/useConversation.d.ts +190 -0
  97. package/dist/useConversation.js +287 -0
  98. package/dist/useSubagent.d.ts +58 -0
  99. package/dist/useSubagent.js +149 -0
  100. package/dist/useTranscript.d.ts +4 -1
  101. package/dist/useTranscript.js +54 -11
  102. package/dist/wording.d.ts +43 -0
  103. package/dist/wording.js +101 -0
  104. package/dist/workingDirectories.d.ts +32 -0
  105. package/dist/workingDirectories.js +71 -0
  106. package/dist/worktreeChoice.d.ts +31 -0
  107. package/dist/worktreeChoice.js +38 -0
  108. package/locales/en/agentTranscript.json +154 -0
  109. package/locales/en/agents.json +366 -0
  110. package/locales/es/agentTranscript.json +154 -0
  111. package/locales/es/agents.json +366 -0
  112. package/locales/ja/agentTranscript.json +154 -0
  113. package/locales/ja/agents.json +366 -0
  114. package/locales/ko/agentTranscript.json +154 -0
  115. package/locales/ko/agents.json +366 -0
  116. package/locales/zh/agentTranscript.json +154 -0
  117. package/locales/zh/agents.json +366 -0
  118. package/package.json +24 -9
@@ -0,0 +1,12 @@
1
+ import { type PwCodeTranslator } from './messages.js';
2
+ import type { CompactionNotice, GoalNotice, 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 useGoalNotice(): GoalNotice;
6
+ export declare function useCompactionNotice(): CompactionNotice;
7
+ export declare function useRecapNotice(): RecapNotice;
8
+ /** How long a turn took, as the terminal says it: 42s, 2m 5s, 1h 4m. */
9
+ export declare function turnDuration(t: PwCodeTranslator<'agents'>, ms: number): string;
10
+ /** The session's own lines: what a goal step opens to, how a turn ended,
11
+ * which plan a /plan showed, and how a background task reported back. */
12
+ export declare function useTranscriptWords(): TranscriptWords;
@@ -0,0 +1,120 @@
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, useLocale } from "use-intl";
6
+ import { formatDuration } from "@parallelworks/ui/headless";
7
+ // src/notices.ts
8
+ /** When a usage limit resets, as a session's notices name it. */
9
+ function useResumeTime() {
10
+ const format = useFormatter();
11
+ return useCallback((at) => format.dateTime(DateTime.fromISO(at).toJSDate(), {
12
+ dateStyle: "medium",
13
+ timeStyle: "short"
14
+ }), [format]);
15
+ }
16
+ function useGoalNotice() {
17
+ const t = usePwCodeTranslations("agents");
18
+ const format = useFormatter();
19
+ const locale = useLocale();
20
+ const resumeTime = useResumeTime();
21
+ return useCallback((p) => {
22
+ if (p.resumeAt) return t("detail.goalUsageLimit", { time: resumeTime(p.resumeAt) });
23
+ if (p.err) return t("detail.goalCheckFailed", { error: p.err });
24
+ if (p.outcome === "achieved") return t("detail.goalAchieved", {
25
+ elapsed: formatDuration(Math.floor((p.elapsedMs ?? 0) / 1e3) * 1e3, locale),
26
+ turns: p.turns ?? 0,
27
+ tokens: format.number(p.tokens ?? 0, {
28
+ notation: "compact",
29
+ maximumFractionDigits: 1
30
+ })
31
+ });
32
+ return t("detail.goalContinuing");
33
+ }, [
34
+ t,
35
+ format,
36
+ locale,
37
+ resumeTime
38
+ ]);
39
+ }
40
+ function useCompactionNotice() {
41
+ const t = usePwCodeTranslations("agents");
42
+ return useMemo(() => ({
43
+ command: t("detail.compacted"),
44
+ automatic: t("detail.compactedAutomatically")
45
+ }), [t]);
46
+ }
47
+ function useRecapNotice() {
48
+ const t = usePwCodeTranslations("agents");
49
+ return useCallback((recap) => t("detail.recap", { recap }), [t]);
50
+ }
51
+ /** How long a turn took, as the terminal says it: 42s, 2m 5s, 1h 4m. */
52
+ function turnDuration(t, ms) {
53
+ const total = Math.round(ms / 1e3);
54
+ if (total < 60) return t("detail.turnSeconds", { seconds: total });
55
+ if (total < 3600) return t("detail.turnMinutes", {
56
+ minutes: Math.floor(total / 60),
57
+ seconds: total % 60
58
+ });
59
+ return t("detail.turnHours", {
60
+ hours: Math.floor(total / 3600),
61
+ minutes: Math.floor(total / 60) % 60
62
+ });
63
+ }
64
+ /** The session's own lines: what a goal step opens to, how a turn ended,
65
+ * which plan a /plan showed, and how a background task reported back. */
66
+ function useTranscriptWords() {
67
+ const t = usePwCodeTranslations("agents");
68
+ const tTranscript = usePwCodeTranslations("agentTranscript");
69
+ const format = useFormatter();
70
+ return useMemo(() => ({
71
+ goalDetail: (p) => t("detail.goalDetail", {
72
+ condition: p.condition ?? "",
73
+ reason: p.reason ?? ""
74
+ }),
75
+ turnEnd: (te, verb, waiting) => {
76
+ if (waiting) return t("detail.turnEndWaiting", { count: te.pendingAgents ?? 0 });
77
+ const ended = DateTime.fromISO(te.endedAt);
78
+ const days = Math.floor(DateTime.now().startOf("day").diff(ended.startOf("day"), "days").days);
79
+ const time = format.dateTime(ended.toJSDate(), {
80
+ hour: "numeric",
81
+ minute: "2-digit",
82
+ ...days > 0 ? { weekday: "long" } : {},
83
+ ...days >= 7 ? {
84
+ month: "short",
85
+ day: "numeric"
86
+ } : {}
87
+ });
88
+ return t("detail.turnEnd", {
89
+ verb,
90
+ duration: turnDuration(t, te.durationMs),
91
+ time
92
+ });
93
+ },
94
+ planAnswer: (path, opened) => opened ? t("detail.planOpened", { path }) : path,
95
+ deliveryLine: (n) => {
96
+ const name = sanitizeLabel(n.description) || n.id;
97
+ if (n.interim) return t("detail.subagentMessage", { name });
98
+ if (n.shell) return n.exitCode ? t("detail.commandFailed", {
99
+ name,
100
+ code: n.exitCode
101
+ }) : t("detail.commandCompleted", { name });
102
+ const outcome = n.failed ? "failed" : "finished";
103
+ return n.elapsedMs ? t("detail.agentEndedAfter", {
104
+ name,
105
+ outcome,
106
+ elapsed: turnDuration(t, n.elapsedMs)
107
+ }) : t("detail.agentEnded", {
108
+ name,
109
+ outcome
110
+ });
111
+ },
112
+ allowDirectory: ({ path, subtree }) => subtree ? tTranscript("transcript.allowDirectoryTree", { path }) : tTranscript("transcript.allowDirectoryOnly", { path }),
113
+ mainConversation: t("switcher.main")
114
+ }), [
115
+ t,
116
+ tTranscript,
117
+ format
118
+ ]);
119
+ }
120
+ export { turnDuration, useCompactionNotice, useGoalNotice, 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,52 @@
1
+ import type { PwCodeTranslator } from './messages.js';
2
+ export type PullRequestState = 'open' | 'draft' | 'merged' | 'closed';
3
+ export declare function isPullRequestState(state: string | undefined): state is PullRequestState;
4
+ /** A pull or merge request's link and its `pullRequestLabel`. */
5
+ export type LabeledPullRequest = {
6
+ url: string;
7
+ pr: string;
8
+ };
9
+ /** The URLs that are plain GitHub pull requests or GitLab merge requests, each with its `pullRequestLabel`. */
10
+ export declare function labeledPullRequests(urls: readonly string[] | null | undefined): LabeledPullRequest[];
11
+ /** A pull request's state by its URL; undefined until one is read. */
12
+ export type PullRequestStateOf = (url: string) => string | undefined;
13
+ /** Reads a state from a session's pull request reads, or from the
14
+ * `pullRequestStates` a listed session carries. */
15
+ export declare function pullRequestStateOf(states: readonly {
16
+ url: string;
17
+ state?: string | undefined;
18
+ }[] | Readonly<Record<string, string>> | null | undefined): PullRequestStateOf;
19
+ /** Drafts, then open, merged and closed pull requests, the newest first within each; one whose state is unknown counts as open. */
20
+ export declare function orderPullRequests(pullRequests: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): LabeledPullRequest[];
21
+ /** Whether each pull request folds into the merged-or-closed count rather than the open one. */
22
+ export declare function pullRequestFoldGroups(ordered: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): boolean[];
23
+ /** How many of `ordered` fold whether or not they fit: its merged and closed ones, which come last, once there are `from` of them to fold; the first stays when every one is merged or closed. */
24
+ export declare function donePullRequestsToFold(ordered: readonly LabeledPullRequest[], stateOf: PullRequestStateOf, from: number): number;
25
+ /** Folded pull requests count apart while open or draft and once merged or closed; `all` counts every one, for a line with room for nothing else. */
26
+ export type PullRequestFoldGroup = 'open' | 'done' | 'all';
27
+ export type PullRequestFold = {
28
+ shown: LabeledPullRequest[];
29
+ groups: {
30
+ group: Exclude<PullRequestFoldGroup, 'all'>;
31
+ pullRequests: LabeledPullRequest[];
32
+ }[];
33
+ };
34
+ /** `ordered` but its last `folded`, which fold into an open count and a merged-or-closed one; a group with none is left out. */
35
+ export declare function foldPullRequests(ordered: readonly LabeledPullRequest[], folded: number, stateOf: PullRequestStateOf): PullRequestFold;
36
+ /** The state a folded group shows: open over draft, and merged over closed. */
37
+ export declare function pullRequestGroupState(group: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): PullRequestState | undefined;
38
+ /** Whether each pull request's state differs from the one before it, where a list marks the change. */
39
+ export declare function pullRequestStateBreaks(pullRequests: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): boolean[];
40
+ export interface PullRequestWords {
41
+ /** A pull request's tooltip, naming its state once it is known. */
42
+ title: (pr: string, state: string | undefined) => string;
43
+ /** A known state's name, which its icon is labeled with. */
44
+ state: (state: PullRequestState) => string;
45
+ /** How many pull requests a count folds away. */
46
+ more: (count: number) => string;
47
+ /** What a folded group's list is called. */
48
+ groupTitle: (group: PullRequestFoldGroup, count: number) => string;
49
+ /** The control that lists a folded group. */
50
+ showGroup: (group: Exclude<PullRequestFoldGroup, 'all'>, count: number) => string;
51
+ }
52
+ export declare function pullRequestWords(t: PwCodeTranslator<'agents'>): PullRequestWords;
@@ -0,0 +1,106 @@
1
+ import { pullRequestKind, pullRequestLabel } from "./pullRequest.js";
2
+ // src/pullRequestList.ts
3
+ var stateOrder = {
4
+ draft: 0,
5
+ open: 1,
6
+ merged: 2,
7
+ closed: 3
8
+ };
9
+ function isPullRequestState(state) {
10
+ return state !== void 0 && Object.hasOwn(stateOrder, state);
11
+ }
12
+ /** The URLs that are plain GitHub pull requests or GitLab merge requests, each with its `pullRequestLabel`. */
13
+ function labeledPullRequests(urls) {
14
+ return (urls ?? []).flatMap((url) => {
15
+ const pr = pullRequestLabel(url);
16
+ return pr ? [{
17
+ url,
18
+ pr
19
+ }] : [];
20
+ });
21
+ }
22
+ /** Reads a state from a session's pull request reads, or from the
23
+ * `pullRequestStates` a listed session carries. */
24
+ function pullRequestStateOf(states) {
25
+ if (Array.isArray(states)) return (url) => states.find((s) => s.url === url)?.state;
26
+ const byUrl = states;
27
+ return (url) => byUrl?.[url];
28
+ }
29
+ var stateRank = (state) => isPullRequestState(state) ? stateOrder[state] : stateOrder.open;
30
+ /** Drafts, then open, merged and closed pull requests, the newest first within each; one whose state is unknown counts as open. */
31
+ function orderPullRequests(pullRequests, stateOf) {
32
+ return pullRequests.map((pr, i) => ({
33
+ pr,
34
+ i,
35
+ rank: stateRank(stateOf(pr.url))
36
+ })).sort((a, b) => a.rank - b.rank || b.i - a.i).map(({ pr }) => pr);
37
+ }
38
+ var isDone = (state) => state === "merged" || state === "closed";
39
+ /** Whether each pull request folds into the merged-or-closed count rather than the open one. */
40
+ function pullRequestFoldGroups(ordered, stateOf) {
41
+ return ordered.map(({ url }) => isDone(stateOf(url)));
42
+ }
43
+ /** How many of `ordered` fold whether or not they fit: its merged and closed ones, which come last, once there are `from` of them to fold; the first stays when every one is merged or closed. */
44
+ function donePullRequestsToFold(ordered, stateOf, from) {
45
+ const done = ordered.filter(({ url }) => isDone(stateOf(url))).length;
46
+ const foldable = done === ordered.length ? done - 1 : done;
47
+ return foldable >= from ? foldable : 0;
48
+ }
49
+ /** `ordered` but its last `folded`, which fold into an open count and a merged-or-closed one; a group with none is left out. */
50
+ function foldPullRequests(ordered, folded, stateOf) {
51
+ const rest = ordered.slice(ordered.length - folded);
52
+ const groups = [{
53
+ group: "open",
54
+ pullRequests: rest.filter(({ url }) => !isDone(stateOf(url)))
55
+ }, {
56
+ group: "done",
57
+ pullRequests: rest.filter(({ url }) => isDone(stateOf(url)))
58
+ }];
59
+ return {
60
+ shown: ordered.slice(0, ordered.length - folded),
61
+ groups: groups.filter(({ pullRequests }) => pullRequests.length > 0)
62
+ };
63
+ }
64
+ var groupPrecedence = [
65
+ "open",
66
+ "draft",
67
+ "merged",
68
+ "closed"
69
+ ];
70
+ /** The state a folded group shows: open over draft, and merged over closed. */
71
+ function pullRequestGroupState(group, stateOf) {
72
+ const states = new Set(group.map(({ url }) => stateOf(url)));
73
+ return groupPrecedence.find((state) => states.has(state));
74
+ }
75
+ /** Whether each pull request's state differs from the one before it, where a list marks the change. */
76
+ function pullRequestStateBreaks(pullRequests, stateOf) {
77
+ return pullRequests.map(({ url }, i) => i > 0 && stateRank(stateOf(url)) !== stateRank(stateOf(pullRequests[i - 1]?.url ?? "")));
78
+ }
79
+ var stateTitles = {
80
+ open: "detail.pullRequestOpen",
81
+ draft: "detail.pullRequestDraft",
82
+ merged: "detail.pullRequestMerged",
83
+ closed: "detail.pullRequestClosed"
84
+ };
85
+ var groupTitles = {
86
+ open: "detail.pullRequestsMoreOpenTitle",
87
+ done: "detail.pullRequestsMoreDoneTitle",
88
+ all: "detail.pullRequestsMoreAllTitle"
89
+ };
90
+ var groupLabels = {
91
+ open: "detail.pullRequestsShowMoreOpen",
92
+ done: "detail.pullRequestsShowMoreDone"
93
+ };
94
+ function pullRequestWords(t) {
95
+ return {
96
+ title: (pr, state) => t(isPullRequestState(state) ? stateTitles[state] : "detail.pullRequest", {
97
+ pr,
98
+ kind: pullRequestKind(pr)
99
+ }),
100
+ state: (state) => t(`detail.pullRequestState.${state}`),
101
+ more: (count) => t("detail.pullRequestsMore", { count }),
102
+ groupTitle: (group, count) => t(groupTitles[group], { count }),
103
+ showGroup: (group, count) => t(groupLabels[group], { count })
104
+ };
105
+ }
106
+ export { donePullRequestsToFold, foldPullRequests, isPullRequestState, labeledPullRequests, orderPullRequests, pullRequestFoldGroups, pullRequestGroupState, pullRequestStateBreaks, pullRequestStateOf, pullRequestWords };
@@ -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,77 @@
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
+ pinnedAt?: string | undefined;
19
+ /** The id of the reader's group the session is in. */
20
+ group?: string | undefined;
21
+ /** Links to the pull requests the session opened or was pointed at. */
22
+ pullRequests?: string[] | null | undefined;
23
+ updatedAt?: string | undefined;
24
+ turnStartedAt?: string | undefined;
25
+ workspace?: string | undefined;
26
+ }
27
+ /** The approvals a session waits on, as far as their kinds. */
28
+ export type PwCodePendingApprovals = readonly Pick<PwCodeApprovalRequest, 'kind'>[] | null | undefined;
2
29
  /** The tone a session's status shows in; a web host passes it to a status badge. */
3
30
  export declare function sessionStatusVariant(status: PwCodeSessionStatus): 'info' | 'warning' | 'muted';
31
+ export declare function sessionKey(s: Pick<PwCodeSession, 'machineId' | 'id'>): string;
32
+ export declare function isSession(s: Pick<PwCodeSession, 'machineId' | 'id'>, machine: string | undefined, id: string | undefined): boolean;
33
+ /** A computer listed only as the resource reaching its daemon matches by daemonId. */
34
+ export declare function sharedStoreCopy<S extends Pick<PwCodeSession, 'machineId' | 'id'>>(list: {
35
+ machines?: readonly Pick<PwCodeMachine, 'id' | 'daemonId' | 'storeId'>[] | null | undefined;
36
+ sessions?: readonly S[] | null | undefined;
37
+ } | undefined, machine: string, id: string): S | undefined;
38
+ /** A session held only by its questions wants an answer, not an approval. */
39
+ export declare function waitsOnAnswer(approvals: PwCodePendingApprovals): boolean;
40
+ /** Machines with nothing on them do not earn a name on every row. */
41
+ export declare function spansMachines(sessions: readonly Pick<PwCodeSession, 'machineId'>[]): boolean;
42
+ export declare function pathBasename(path: string): string;
43
+ /** A running row's clock is how long its turn has run, not when its transcript
44
+ * last changed; a turn the daemon could not date falls back to the latter. */
45
+ export declare function sessionClock(s: Pick<PwCodeSession, 'status' | 'turnStartedAt' | 'updatedAt'>, compact: (iso: string | undefined) => string): string;
46
+ /** The status alone misses a session that is attached but resting between
47
+ * turns, which the daemon reports as idle. */
48
+ export declare function isActiveSession(s: Pick<PwCodeSession, 'status' | 'liveHost'>): boolean;
49
+ /** The daemon lists archived sessions too and leaves hiding them to its clients. */
50
+ export declare function isArchived(s: Pick<PwCodeSession, 'archivedAt'>): boolean;
51
+ /** A turn is in flight: there is work to stop, and the daemon refuses a fork. */
52
+ export declare function isMidTurn(s: Pick<PwCodeSession, 'status'>): boolean;
53
+ /** A dropped machine outranks the session state: it reads as the machine's
54
+ * problem, not the session's. `idle` is what a resting session shows, the
55
+ * live green for its dot and the muted ink for its text. */
56
+ export declare function sessionVariant<T extends string>(status: PwCodeSessionStatus, machine: Pick<PwCodeMachine, 'status'> | undefined, idle: T): T | 'error' | ReturnType<typeof sessionStatusVariant>;
57
+ /** An approval on a machine that stopped answering cannot be acted on. */
58
+ export declare function needsYou(s: Pick<PwCodeSession, 'status' | 'archivedAt'>, machine: Pick<PwCodeMachine, 'status'> | undefined): boolean;
59
+ export interface RecentDirectory {
60
+ path: string;
61
+ name: string;
62
+ sessions: number;
63
+ updatedAt: string;
64
+ }
65
+ /** The daemon offers no way to browse, so the machine's own sessions are the
66
+ * only paths we can honestly suggest. */
67
+ export declare function recentDirectories(sessions: readonly Pick<PwCodeSession, 'machineId' | 'workspace' | 'updatedAt'>[], machineId: string | undefined): RecentDirectory[];
68
+ export declare function newestFirst<T extends {
69
+ updatedAt?: string | undefined;
70
+ }>(items: readonly T[]): T[];
71
+ /** An approval blocks the agent and goes first; a running turn is context;
72
+ * everything else is what the reader last touched, newest first. */
73
+ export declare function triageSessions<S extends Pick<PwCodeSession, 'machineId' | 'status' | 'archivedAt' | 'updatedAt'>>(sessions: readonly S[], machineById: ReadonlyMap<string, Pick<PwCodeMachine, 'status'>>): {
74
+ blocked: S[];
75
+ active: S[];
76
+ idle: S[];
77
+ };
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 };