@uniqbit/mate-core 1.0.0 → 1.0.1-canary.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mate-companion-mentions",
3
- "version": "1.0.0",
3
+ "version": "1.0.1-canary.0",
4
4
  "description": "@mate:<path> mentions: find and attach files from the mate companion repo in the @ menu.",
5
5
  "author": {
6
6
  "name": "Kevin Tornquist"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniqbit/mate-core",
3
- "version": "1.0.0",
3
+ "version": "1.0.1-canary.0",
4
4
  "description": "Core framework and plugin APIs for Mate.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,16 @@
1
+ import { selectOne } from "../lib/components/select-one";
2
+ import { TRIAGE_AGENT_NAMES, type FoundAgent } from "../lib/triage/launch";
3
+
4
+ /** `--version` lines carry extra text (`2.1.0 (Claude Code)`); show the number alone. */
5
+ export function agentLabel(found: FoundAgent): string {
6
+ const name = TRIAGE_AGENT_NAMES[found.agent];
7
+ const version = found.version?.match(/\d+\.\d+\S*/)?.[0];
8
+ return version ? `${name} ${version}` : name;
9
+ }
10
+
11
+ export function selectAgent(agents: FoundAgent[]): Promise<FoundAgent | null> {
12
+ return selectOne(agents, {
13
+ title: "Several agents are installed — pick one",
14
+ toItem: (found) => ({ key: found.agent, label: agentLabel(found) }),
15
+ });
16
+ }
@@ -1,5 +1,3 @@
1
- import readline from "node:readline/promises";
2
-
3
1
  import { FRAMEWORK_NAME } from "../../framework";
4
2
  import { FrictionRefusal } from "../../lib/friction/fields";
5
3
  import { formatCommand } from "../../runtime/command-arg";
@@ -17,6 +15,7 @@ import {
17
15
  } from "../../lib/triage/prepare";
18
16
  import { recordTriageLauncher } from "../../lib/triage/session";
19
17
  import { currentSession } from "../../runtime/session-id";
18
+ import { selectAgent } from "../agent-selector";
20
19
  import { collectDoctorReport } from "./doctor";
21
20
 
22
21
  interface TriageArgs {
@@ -57,35 +56,23 @@ export interface TriageDeps {
57
56
  cwd?: string;
58
57
  env?: Record<string, string | undefined>;
59
58
  now?: Date;
60
- /** Asks which agent to start; null when no terminal can ask. Defaults to a prompt on a TTY stdin. */
59
+ /** Asks which agent to start; null when no terminal can ask. Defaults to a menu when stdin and stdout are TTYs. */
61
60
  ask?: AskAgent | null;
62
61
  collectDoctor?: (cwd: string) => Promise<unknown>;
63
62
  launch?: typeof launchAgent;
64
63
  }
65
64
 
66
- type AskAgent = (choices: TriageAgent[]) => Promise<TriageAgent | null>;
67
-
68
- const askAgent: AskAgent = async (choices) => {
69
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
70
- try {
71
- const answer = await rl.question(`Start which agent? (${choices.join("/")}) `);
72
- const picked = answer.trim().toLowerCase();
73
- return choices.find((choice) => choice === picked) ?? null;
74
- } finally {
75
- rl.close();
76
- }
77
- };
65
+ type AskAgent = (agents: FoundAgent[]) => Promise<FoundAgent | null>;
78
66
 
79
67
  async function chooseAgent(
80
68
  requested: TriageAgent | null,
81
69
  agents: FoundAgent[],
82
70
  ask: AskAgent | null,
83
71
  ): Promise<{ found: FoundAgent } | { error: string }> {
84
- const pick = (id: TriageAgent | null, error: string) => {
85
- const found = agents.find((agent) => agent.agent === id);
86
- return found ? { found } : { error };
87
- };
88
- if (requested) return pick(requested, `${TRIAGE_AGENT_NAMES[requested]} was not found on PATH.`);
72
+ if (requested) {
73
+ const found = agents.find((agent) => agent.agent === requested);
74
+ return found ? { found } : { error: `${TRIAGE_AGENT_NAMES[requested]} was not found on PATH.` };
75
+ }
89
76
  if (agents.length === 0) {
90
77
  return {
91
78
  error: `No agent was found: install ${TRIAGE_AGENTS.map((id) => TRIAGE_AGENT_NAMES[id]).join(" or ")}, or start your own agent with the prompt in prompt.md.`,
@@ -94,8 +81,8 @@ async function chooseAgent(
94
81
  if (agents.length === 1) return { found: agents[0]! };
95
82
  const flags = agents.map((agent) => `--agent ${agent.agent}`).join(" or ");
96
83
  if (!ask) return { error: `Several agents are installed; choose one with ${flags}.` };
97
- const picked = await ask(agents.map((agent) => agent.agent));
98
- return pick(picked, `No agent chosen; choose one with ${flags}.`);
84
+ const found = await ask(agents);
85
+ return found ? { found } : { error: `No agent chosen; choose one with ${flags}.` };
99
86
  }
100
87
 
101
88
  function printPaths(files: TriageSessionFiles): void {
@@ -152,7 +139,8 @@ export async function runTriageCommand(argv: string[] = [], deps: TriageDeps = {
152
139
  return;
153
140
  }
154
141
 
155
- const ask = deps.ask === undefined ? (process.stdin.isTTY ? askAgent : null) : deps.ask;
142
+ const terminal = Boolean(process.stdin.isTTY && process.stdout.isTTY);
143
+ const ask = deps.ask === undefined ? (terminal ? selectAgent : null) : deps.ask;
156
144
  const choice = await chooseAgent(args.agent, agents, ask);
157
145
  if ("error" in choice) {
158
146
  console.error(`${FRAMEWORK_NAME}: ${choice.error}`);
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.0.0",
3
- "sha512": "sha512-pUKQLcYiKxPD5TZmBeRaY9b49n2Jl7gXHfXThaTAOmDF3hA2pAyT0uEBMV4ZZmJ2M2oXmq+rxCf2Fzkwu3O77g=="
2
+ "version": "1.0.1-canary.0",
3
+ "sha512": "sha512-5MM2kuh/ihpcEgM2DQhi0SeXbOahrasT0uaBgjUTdO7A5W1gComjzEcRbgqp2hikQH5K9NsrL9OiFun1Vwgx5A=="
4
4
  }
@@ -323,8 +323,9 @@ export interface ChangeNext {
323
323
  /**
324
324
  * @command mate workflow next <change>
325
325
  * @description Prints the stage a change is at and its next actions as a `## Next steps`
326
- * section, writing nothing: the hand-off `mate workflow done` would print, computed from the
327
- * declaration, the change's Delivery Record and its tasks alone, whatever a session wrote.
326
+ * section, writing nothing: the hand-off `mate workflow done` would print, less its
327
+ * `Start a fresh session` before apply, computed from the declaration, the change's Delivery
328
+ * Record and its tasks alone, whatever a session wrote.
328
329
  * @flags
329
330
  * - `--json` — emit a {@link ChangeNext}: `ok`, `change`, `stage`, `open`, `handoff`,
330
331
  * `actions` and `optional`.
@@ -0,0 +1,26 @@
1
+ import { selectOne, type SelectOneOptions } from "../lib/components/select-one";
2
+ import type { CompanionMatch } from "../lib/orchestrator/repository-link";
3
+
4
+ /**
5
+ * Prompts the user to pick one companion when the active working repo is
6
+ * linked from more than one companion's registry (`CompanionResolver`
7
+ * reports this via `ambiguousMatches`, since only one companion may be
8
+ * active for a repo at a time).
9
+ */
10
+ export function selectCompanion(
11
+ matches: CompanionMatch[],
12
+ options: SelectOneOptions = {},
13
+ ): Promise<CompanionMatch | null> {
14
+ return selectOne(
15
+ matches,
16
+ {
17
+ title: "Multiple companions link this repo — pick one",
18
+ toItem: (match) => ({
19
+ key: match.companionPath,
20
+ label: match.companionPath,
21
+ description: `(repo: ${match.repositoryId})`,
22
+ }),
23
+ },
24
+ options,
25
+ );
26
+ }
@@ -0,0 +1,122 @@
1
+ /** @jsxRuntime automatic */
2
+ /** @jsxImportSource react */
3
+ import { Box, render as inkRender } from "ink";
4
+ import React, { useEffect } from "react";
5
+ import { SelectMenu, type SelectMenuItem } from "./select-menu";
6
+ import { WizardFooter } from "./wizard-footer";
7
+ import { WizardHeader } from "./wizard-header";
8
+
9
+ export interface SelectOneOptions {
10
+ stdin?: NodeJS.ReadStream;
11
+ stdout?: NodeJS.WriteStream;
12
+ stderr?: NodeJS.WriteStream;
13
+ }
14
+
15
+ interface SelectOneConfig<T> {
16
+ title: string;
17
+ toItem: (value: T) => SelectMenuItem;
18
+ }
19
+
20
+ /** Raw mode turns Ctrl+C into "\x03" instead of SIGINT, so it cancels like q and escape. */
21
+ function parseSelectOneInput(input: string): "submit" | "cancel" | "up" | "down" | null {
22
+ if (input === "\r" || input === "\n") return "submit";
23
+ if (input === "\x1b[A" || input === "[A") return "up";
24
+ if (input === "\x1b[B" || input === "[B") return "down";
25
+ if (input === "\x1b" || input === "\x03" || input.toLowerCase() === "q") return "cancel";
26
+ return null;
27
+ }
28
+
29
+ interface SelectOneAppProps {
30
+ title: string;
31
+ items: SelectMenuItem[];
32
+ activeIndex: number;
33
+ onMounted?: () => void;
34
+ }
35
+
36
+ function SelectOneApp({
37
+ title,
38
+ items,
39
+ activeIndex,
40
+ onMounted,
41
+ }: SelectOneAppProps): React.JSX.Element {
42
+ useEffect(() => {
43
+ onMounted?.();
44
+ }, [onMounted]);
45
+
46
+ return (
47
+ <Box flexDirection="column" width="100%">
48
+ <WizardHeader title={title} step={0} totalSteps={1} />
49
+ <Box marginTop={1} flexDirection="column">
50
+ <SelectMenu items={items} activeIndex={activeIndex} />
51
+ </Box>
52
+ <WizardFooter hint="↑↓ navigate · enter select · q cancel" />
53
+ </Box>
54
+ );
55
+ }
56
+
57
+ /** Terminal menu that picks one of `values`; null when cancelled. */
58
+ export async function selectOne<T>(
59
+ values: T[],
60
+ config: SelectOneConfig<T>,
61
+ options: SelectOneOptions = {},
62
+ ): Promise<T | null> {
63
+ const stdin = options.stdin ?? process.stdin;
64
+ const stdout = options.stdout ?? process.stdout;
65
+ const stderr = options.stderr ?? process.stderr;
66
+ if (!stdin.isTTY || !stdout.isTTY) {
67
+ throw new Error("Select menu requires a TTY.");
68
+ }
69
+
70
+ const items = values.map(config.toItem);
71
+ let activeIndex = 0;
72
+ let finalResult: T | null = null;
73
+ let rendered: ReturnType<typeof inkRender> | undefined;
74
+
75
+ stdin.resume();
76
+ (stdin as NodeJS.ReadStream & { ref?: () => void }).ref?.();
77
+ const keepAlive = setInterval(() => {}, 1 << 30);
78
+
79
+ const cleanup = () => {
80
+ clearInterval(keepAlive);
81
+ stdin.off("data", onData);
82
+ stdin.pause();
83
+ stdin.setRawMode?.(false);
84
+ (stdin as NodeJS.ReadStream & { unref?: () => void }).unref?.();
85
+ };
86
+
87
+ const app = () => (
88
+ <SelectOneApp
89
+ title={config.title}
90
+ items={items}
91
+ activeIndex={activeIndex}
92
+ onMounted={onMounted}
93
+ />
94
+ );
95
+
96
+ const onMounted = () => {
97
+ stdin.on("data", onData);
98
+ };
99
+
100
+ const onData = (chunk: string) => {
101
+ const action = parseSelectOneInput(chunk);
102
+ if (!action) return;
103
+ if (action === "up" || action === "down") {
104
+ activeIndex = (activeIndex + (action === "up" ? -1 : 1) + items.length) % items.length;
105
+ rendered?.rerender(app());
106
+ return;
107
+ }
108
+ // Ink resolves exit only after a stdout flush; later keys must not overwrite the choice.
109
+ stdin.off("data", onData);
110
+ finalResult = action === "submit" ? (values[activeIndex] ?? null) : null;
111
+ rendered?.unmount();
112
+ };
113
+
114
+ stdin.setEncoding("utf8");
115
+ stdin.setRawMode?.(true);
116
+
117
+ rendered = inkRender(app(), { stdin, stdout, stderr });
118
+ return rendered
119
+ .waitUntilExit()
120
+ .then(() => finalResult)
121
+ .finally(cleanup);
122
+ }
@@ -17,7 +17,7 @@ export interface SkillAction {
17
17
  afterReview?: true;
18
18
  }
19
19
 
20
- /** A step outside any skill: a merge or a review. */
20
+ /** A step outside any skill: a merge, a review or a fresh session. */
21
21
  export interface TextAction {
22
22
  kind: "text";
23
23
  text: string;
@@ -336,7 +336,13 @@ function orderHandoff(
336
336
  const next = nextStage(workflow, id);
337
337
  if (!next) return NOTHING;
338
338
  optional.push(...next.optional.map((stage) => skill(stage.entry, name)));
339
- if (next.kind === "skill") return buildHandoff(optional, [skill(next.entry!, name)]);
339
+ if (next.kind === "skill") {
340
+ const stage = workflow.stages.find((each) => each.id === next.id);
341
+ return buildHandoff(optional, [
342
+ ...freshSessionAfterStep(workflow, finished, stage, NO_PROGRESS),
343
+ skill(next.entry!, name),
344
+ ]);
345
+ }
340
346
  // Nothing to review yet.
341
347
  id = next.id;
342
348
  }
@@ -357,6 +363,19 @@ function stepToRun(
357
363
  return { skill: stage.steps.find((step) => step.own)?.skill ?? stage.entry, open: reason };
358
364
  }
359
365
 
366
+ function freshSessionAfterStep(
367
+ workflow: Workflow,
368
+ finished: WorkflowSkillStage | null,
369
+ stage: WorkflowStage | undefined,
370
+ progress: PathProgress,
371
+ ): TextAction[] {
372
+ if (!finished || stage?.id !== "apply") return [];
373
+ const started =
374
+ (progress.steps[stage.id]?.length ?? 0) > 0 || (progress.plan?.completedTasks ?? 0) > 0;
375
+ const before = workflow.stages.indexOf(finished) < workflow.stages.indexOf(stage);
376
+ return !started && before ? [text("Start a fresh session")] : [];
377
+ }
378
+
360
379
  interface Placed {
361
380
  progress: PathProgress;
362
381
  stage: WorkflowStage | null;
@@ -405,7 +424,14 @@ function progressHandoff(
405
424
  // null for a stage held by state.
406
425
  const open = heldByState(position) && finished ? missing(position, progress) : next.open;
407
426
  const action = skill(next.skill, name);
408
- return buildHandoff(passed(at), [here && open ? { ...action, note: open } : action], counted);
427
+ return buildHandoff(
428
+ passed(at),
429
+ [
430
+ ...freshSessionAfterStep(workflow, finished, position, progress),
431
+ here && open ? { ...action, note: open } : action,
432
+ ],
433
+ counted,
434
+ );
409
435
  }
410
436
  // The reviews up to the next skill stage, then that stage as following them.
411
437
  const artifacts = subject.artifacts ?? [];
@@ -429,6 +455,7 @@ function progressHandoff(
429
455
  passed(follower),
430
456
  [
431
457
  ...reviews,
458
+ ...freshSessionAfterStep(workflow, finished, next, progress),
432
459
  ...(next?.kind === "skill"
433
460
  ? [{ ...skill(next.entry, name), afterReview: true as const }]
434
461
  : []),
@@ -1,139 +0,0 @@
1
- /** @jsxRuntime automatic */
2
- /** @jsxImportSource react */
3
- import { Box, render as inkRender } from "ink";
4
- import React, { useEffect } from "react";
5
- import { SelectMenu, type SelectMenuItem } from "../lib/components/select-menu";
6
- import { WizardFooter } from "../lib/components/wizard-footer";
7
- import { WizardHeader } from "../lib/components/wizard-header";
8
- import type { CompanionMatch } from "../lib/orchestrator/repository-link";
9
-
10
- export interface CompanionSelectorOptions {
11
- stdin?: NodeJS.ReadStream;
12
- stdout?: NodeJS.WriteStream;
13
- stderr?: NodeJS.WriteStream;
14
- }
15
-
16
- const companionSelectorDeps = {
17
- render: inkRender,
18
- };
19
-
20
- function parseCompanionSelectorInput(input: string): "submit" | "cancel" | "up" | "down" | null {
21
- if (input === "\r" || input === "\n") return "submit";
22
- if (input === "\x1b[A" || input === "[A") return "up";
23
- if (input === "\x1b[B" || input === "[B") return "down";
24
- if (input === "\x1b" || input.toLowerCase() === "q") return "cancel";
25
- return null;
26
- }
27
-
28
- interface CompanionSelectorAppProps {
29
- items: SelectMenuItem[];
30
- activeIndex: number;
31
- onMounted?: () => void;
32
- }
33
-
34
- function CompanionSelectorApp({
35
- items,
36
- activeIndex,
37
- onMounted,
38
- }: CompanionSelectorAppProps): React.JSX.Element {
39
- useEffect(() => {
40
- onMounted?.();
41
- }, [onMounted]);
42
-
43
- return (
44
- <Box flexDirection="column" width="100%">
45
- <WizardHeader title="Multiple companions link this repo — pick one" step={0} totalSteps={1} />
46
- <Box marginTop={1} flexDirection="column">
47
- <SelectMenu items={items} activeIndex={activeIndex} />
48
- </Box>
49
- <WizardFooter hint="↑↓ navigate · enter select · q cancel" />
50
- </Box>
51
- );
52
- }
53
-
54
- /**
55
- * Prompts the user to pick one companion when the active working repo is
56
- * linked from more than one companion's registry (`CompanionResolver`
57
- * reports this via `ambiguousMatches`, since only one companion may be
58
- * active for a repo at a time).
59
- */
60
- export async function selectCompanion(
61
- matches: CompanionMatch[],
62
- options: CompanionSelectorOptions = {},
63
- ): Promise<CompanionMatch | null> {
64
- const stdin = options.stdin ?? process.stdin;
65
- const stdout = options.stdout ?? process.stdout;
66
- const stderr = options.stderr ?? process.stderr;
67
- if (!stdin.isTTY || !stdout.isTTY) {
68
- throw new Error("Companion selector requires a TTY.");
69
- }
70
-
71
- const items: SelectMenuItem[] = matches.map((match) => ({
72
- key: match.companionPath,
73
- label: match.companionPath,
74
- description: `(repo: ${match.repositoryId})`,
75
- }));
76
-
77
- let activeIndex = 0;
78
- let finalResult: CompanionMatch | null = null;
79
- let resolved = false;
80
- let rendered: ReturnType<typeof companionSelectorDeps.render> | undefined;
81
-
82
- stdin.resume();
83
- (stdin as NodeJS.ReadStream & { ref?: () => void }).ref?.();
84
- const keepAlive = setInterval(() => {}, 1 << 30);
85
-
86
- const cleanup = () => {
87
- clearInterval(keepAlive);
88
- stdin.off("data", onData);
89
- stdin.pause();
90
- stdin.setRawMode?.(false);
91
- (stdin as NodeJS.ReadStream & { unref?: () => void }).unref?.();
92
- };
93
-
94
- const rerender = () => {
95
- rendered?.rerender(
96
- <CompanionSelectorApp items={items} activeIndex={activeIndex} onMounted={onMounted} />,
97
- );
98
- };
99
-
100
- const onMounted = () => {
101
- stdin.on("data", onData);
102
- };
103
-
104
- const onData = (chunk: string) => {
105
- const action = parseCompanionSelectorInput(chunk);
106
- if (!action) return;
107
- if (action === "cancel") {
108
- finalResult = null;
109
- rendered?.unmount();
110
- return;
111
- }
112
- if (action === "up" || action === "down") {
113
- activeIndex = (activeIndex + (action === "up" ? -1 : 1) + items.length) % items.length;
114
- rerender();
115
- return;
116
- }
117
- if (action === "submit") {
118
- finalResult = matches[activeIndex] ?? null;
119
- rendered?.unmount();
120
- }
121
- };
122
-
123
- stdin.setEncoding("utf8");
124
- stdin.setRawMode?.(true);
125
-
126
- return new Promise<CompanionMatch | null>((resolve) => {
127
- rendered = companionSelectorDeps.render(
128
- <CompanionSelectorApp items={items} activeIndex={activeIndex} onMounted={onMounted} />,
129
- { stdin, stdout, stderr },
130
- );
131
-
132
- rendered.waitUntilExit().then(() => {
133
- if (resolved) return;
134
- resolved = true;
135
- cleanup();
136
- resolve(finalResult);
137
- });
138
- });
139
- }