@xingular/harness 1.3.1-unstable.4 → 1.3.1-unstable.8

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 (150) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +14 -9
  3. package/dist/cli.js +1734 -796
  4. package/dist/sdk/accounts/choices.d.ts +18 -0
  5. package/dist/sdk/accounts/choices.js +27 -0
  6. package/dist/sdk/cli.js +4 -0
  7. package/dist/sdk/commands/extensionOwners.d.ts +4 -0
  8. package/dist/sdk/commands/extensionOwners.js +17 -0
  9. package/dist/sdk/commands/list.js +15 -2
  10. package/dist/sdk/commands/promptLoader.d.ts +5 -0
  11. package/dist/sdk/commands/promptLoader.js +76 -0
  12. package/dist/sdk/commands/promptRoutes.d.ts +13 -0
  13. package/dist/sdk/commands/promptRoutes.js +46 -0
  14. package/dist/sdk/commands/registry.d.ts +14 -0
  15. package/dist/sdk/commands/registry.js +2 -0
  16. package/dist/sdk/commands/runtimeRouter.d.ts +4 -0
  17. package/dist/sdk/commands/runtimeRouter.js +48 -0
  18. package/dist/sdk/computer/boundary.d.ts +40 -0
  19. package/dist/sdk/computer/boundary.js +79 -0
  20. package/dist/sdk/computer/contracts.d.ts +127 -0
  21. package/dist/sdk/computer/contracts.js +13 -0
  22. package/dist/sdk/computer/control.d.ts +34 -0
  23. package/dist/sdk/computer/control.js +112 -0
  24. package/dist/sdk/computer/terminalCapture.d.ts +26 -0
  25. package/dist/sdk/computer/terminalCapture.js +64 -0
  26. package/dist/sdk/computer/volatileImages.d.ts +9 -0
  27. package/dist/sdk/computer/volatileImages.js +50 -0
  28. package/dist/sdk/context/runDetails.d.ts +16 -0
  29. package/dist/sdk/context/runDetails.js +22 -0
  30. package/dist/sdk/doctor/checks.js +3 -0
  31. package/dist/sdk/doctor/probe.js +8 -6
  32. package/dist/sdk/harness.d.ts +8 -0
  33. package/dist/sdk/harness.js +7 -4
  34. package/dist/sdk/history/trajectory.js +2 -0
  35. package/dist/sdk/hub/hub.js +1 -1
  36. package/dist/sdk/hub/schema.d.ts +2 -2
  37. package/dist/sdk/plugins/manifest.d.ts +2 -0
  38. package/dist/sdk/plugins/manifest.js +1 -0
  39. package/dist/sdk/prompt/compile.d.ts +3 -1
  40. package/dist/sdk/prompt/compile.js +10 -7
  41. package/dist/sdk/refine/host.d.ts +9 -1
  42. package/dist/sdk/refine/host.js +29 -0
  43. package/dist/sdk/refine/prompts.d.ts +15 -0
  44. package/dist/sdk/refine/prompts.js +44 -0
  45. package/dist/sdk/refine/recursion.js +4 -4
  46. package/dist/sdk/refine/runner.d.ts +2 -0
  47. package/dist/sdk/refine/runner.js +2 -1
  48. package/dist/sdk/refine/serverMethods.js +4 -1
  49. package/dist/sdk/refine/service.d.ts +31 -0
  50. package/dist/sdk/refine/service.js +119 -4
  51. package/dist/sdk/refine/trajectory.js +7 -2
  52. package/dist/sdk/refine/types.d.ts +16 -0
  53. package/dist/sdk/remote/webClient.js +7 -3
  54. package/dist/sdk/server/methods.js +31 -1
  55. package/dist/sdk/sessions/compactionCheckpoint.d.ts +6 -1
  56. package/dist/sdk/sessions/compactionCheckpoint.js +34 -35
  57. package/dist/sdk/sessions/contracts.d.ts +141 -2
  58. package/dist/sdk/sessions/contracts.js +115 -3
  59. package/dist/sdk/sessions/planMode.d.ts +1 -1
  60. package/dist/sdk/sessions/planMode.js +7 -4
  61. package/dist/sdk/sessions/registry.d.ts +6 -2
  62. package/dist/sdk/sessions/registry.js +16 -13
  63. package/dist/sdk/sessions/runStore.d.ts +3 -1
  64. package/dist/sdk/sessions/runStore.js +26 -8
  65. package/dist/sdk/sessions/runner.d.ts +5 -5
  66. package/dist/sdk/sessions/runner.js +78 -15
  67. package/dist/sdk/sessions/sessions.js +35 -21
  68. package/dist/sdk/sessions/workSlice.d.ts +2 -0
  69. package/dist/sdk/sessions/workSlice.js +4 -3
  70. package/dist/sdk/terminal/client.d.ts +3 -0
  71. package/dist/sdk/terminal/client.js +13 -0
  72. package/dist/sdk/terminal/controller.d.ts +2 -0
  73. package/dist/sdk/terminal/controller.js +12 -6
  74. package/dist/sdk/terminal/opentui/theme.d.ts +2 -0
  75. package/dist/sdk/terminal/opentui/theme.js +4 -0
  76. package/dist/sdk/terminal/piExtension.js +73 -13
  77. package/dist/sdk/terminal/standalone.d.ts +6 -1
  78. package/dist/sdk/terminal/standalone.js +30 -3
  79. package/dist/sdk/terminal/terminals.d.ts +11 -1
  80. package/dist/sdk/terminal/terminals.js +58 -5
  81. package/dist/sdk/terminal/trajectory.js +2 -2
  82. package/dist/sdk/terminal/tui/commandPages.d.ts +1 -1
  83. package/dist/sdk/terminal/tui/commandPages.js +4 -2
  84. package/dist/sdk/terminal/tui/commands.js +29 -65
  85. package/dist/sdk/terminal/tui/modeChoices.d.ts +18 -0
  86. package/dist/sdk/terminal/tui/modeChoices.js +26 -1
  87. package/dist/sdk/terminal/tui/pages/contextPage.d.ts +30 -1
  88. package/dist/sdk/terminal/tui/pages/contextPage.js +109 -8
  89. package/dist/sdk/terminal/tui/pages/textPage.d.ts +17 -0
  90. package/dist/sdk/terminal/tui/pages/textPage.js +52 -0
  91. package/dist/sdk/terminal/tui/pages/trajectoryPage.d.ts +1 -0
  92. package/dist/sdk/terminal/tui/pages/trajectoryPage.js +12 -3
  93. package/dist/sdk/terminal/tui/runtime.js +60 -3
  94. package/dist/sdk/terminal/tui/sideQuestion.d.ts +3 -0
  95. package/dist/sdk/terminal/tui/sideQuestion.js +7 -1
  96. package/dist/sdk/terminal/tui/status.d.ts +0 -6
  97. package/dist/sdk/terminal/tui/status.js +1 -15
  98. package/dist/sdk/terminal/tui/variantCommands.d.ts +32 -0
  99. package/dist/sdk/terminal/tui/variantCommands.js +359 -0
  100. package/dist/sdk/terminal/variantControl.d.ts +24 -0
  101. package/dist/sdk/terminal/variantControl.js +145 -0
  102. package/dist/sdk/tools/definitions.js +1 -1
  103. package/dist/sdk/tools/dispatch.d.ts +1 -1
  104. package/dist/sdk/tools/dispatch.js +17 -3
  105. package/dist/sdk/variant/store.d.ts +33 -1
  106. package/dist/sdk/variant/store.js +108 -3
  107. package/dist/sdk/worktrees/git.d.ts +2 -0
  108. package/dist/sdk/worktrees/git.js +8 -0
  109. package/dist/sdk/worktrees/snapshot.d.ts +16 -0
  110. package/dist/sdk/worktrees/snapshot.js +83 -0
  111. package/dist/sdk/world/actions.js +1 -1
  112. package/dist/terminal-opentui.js +1643 -451
  113. package/dist/terminal-pi.js +179 -56
  114. package/docs/architecture/02-sessions-and-runs.md +33 -13
  115. package/docs/architecture/03-variants.md +24 -3
  116. package/docs/architecture/04-prompt.md +22 -11
  117. package/docs/architecture/05-refinement.md +32 -5
  118. package/docs/architecture/06-plugins-and-capabilities.md +13 -2
  119. package/docs/architecture/07-tools-and-gate.md +14 -0
  120. package/docs/architecture/08-memory-and-history.md +7 -3
  121. package/docs/architecture/09-accounts-and-connectors.md +13 -3
  122. package/docs/architecture/10-server-protocol.md +26 -3
  123. package/docs/architecture/11-terminal.md +50 -19
  124. package/docs/architecture/12-storage.md +12 -4
  125. package/docs/architecture/13-world-tools.md +19 -0
  126. package/docs/architecture/14-surfaces-and-parity.md +3 -3
  127. package/docs/architecture/README.md +2 -0
  128. package/docs/architecture/proposals/PROP-0049-context-attribution.md +7 -1
  129. package/docs/architecture/proposals/PROP-0050-run-stop-codes-and-refusals.md +30 -0
  130. package/docs/architecture/proposals/PROP-0051-unfinished-run-handoff.md +110 -0
  131. package/docs/architecture/proposals/PROP-0052-terminal-refine-and-variant-switch.md +111 -0
  132. package/docs/architecture/proposals/README.md +2 -0
  133. package/docs/decisions/ADR-0032-compaction-run-checkpoints.md +3 -1
  134. package/docs/decisions/ADR-0059-run-diagnostic-evidence.md +35 -0
  135. package/docs/decisions/ADR-0060-approvals-are-controls.md +40 -0
  136. package/docs/decisions/ADR-0061-strict-plugin-command-namespaces.md +41 -0
  137. package/docs/decisions/ADR-0062-shared-account-state.md +67 -0
  138. package/docs/decisions/ADR-0063-unfinished-work-handoffs.md +32 -0
  139. package/docs/decisions/ADR-0064-account-model-fallback-on-resume.md +79 -0
  140. package/docs/decisions/ADR-0065-variant-switch-at-turn-boundaries.md +31 -0
  141. package/docs/decisions/ADR-0066-guided-refinement-from-turn-snapshots.md +37 -0
  142. package/docs/decisions/ADR-0067-cache-stable-compaction-checkpoint.md +54 -0
  143. package/docs/doctor.md +2 -0
  144. package/docs/parity.md +18 -7
  145. package/docs/releases/1.3.1-unstable.5.md +53 -0
  146. package/docs/releases/1.3.1-unstable.6.md +31 -0
  147. package/docs/releases/1.3.1-unstable.7.md +17 -0
  148. package/docs/releases/1.3.1-unstable.8.md +19 -0
  149. package/docs/terminal-tui.md +48 -16
  150. package/package.json +1 -1
@@ -21,3 +21,21 @@ export declare function resolveChoice(modes: Record<string, ModeChoice>, mode: s
21
21
  model?: string;
22
22
  effort?: Effort;
23
23
  };
24
+ /** A saved selection with the mode it was made in. */
25
+ export interface SavedChoice {
26
+ mode: string;
27
+ model?: string;
28
+ effort?: Effort;
29
+ }
30
+ /** The account's newest saved selection, whichever mode it was made in. */
31
+ export declare function latestChoice(modes: Record<string, ModeChoice>): SavedChoice | undefined;
32
+ /**
33
+ * The selection a conversation starts from when this account cannot use the model in its own
34
+ * history: the mode's own fields, then normal's, then the newest selection in any mode.
35
+ */
36
+ export declare function startChoice(modes: Record<string, ModeChoice>, mode: string): {
37
+ model?: string;
38
+ effort?: Effort;
39
+ };
40
+ /** Every model `startChoice` may try, most specific first and without repeats. */
41
+ export declare function startModels(modes: Record<string, ModeChoice>, mode: string): string[];
@@ -60,3 +60,30 @@ export function resolveChoice(modes, mode, fallback = 'normal') {
60
60
  const base = mode === fallback ? {} : modes[fallback] ?? {};
61
61
  return { model: own.model ?? base.model, effort: own.effort ?? base.effort };
62
62
  }
63
+ /** The account's newest saved selection, whichever mode it was made in. */
64
+ export function latestChoice(modes) {
65
+ let newest;
66
+ for (const [mode, entry] of Object.entries(modes)) {
67
+ if (newest && entry.updatedAt <= newest.updatedAt)
68
+ continue;
69
+ newest = {
70
+ choice: { mode, ...(entry.model ? { model: entry.model } : {}), ...(entry.effort ? { effort: entry.effort } : {}) },
71
+ updatedAt: entry.updatedAt
72
+ };
73
+ }
74
+ return newest?.choice;
75
+ }
76
+ /**
77
+ * The selection a conversation starts from when this account cannot use the model in its own
78
+ * history: the mode's own fields, then normal's, then the newest selection in any mode.
79
+ */
80
+ export function startChoice(modes, mode) {
81
+ const resolved = resolveChoice(modes, mode);
82
+ const latest = latestChoice(modes);
83
+ return { model: resolved.model ?? latest?.model, effort: resolved.effort ?? latest?.effort };
84
+ }
85
+ /** Every model `startChoice` may try, most specific first and without repeats. */
86
+ export function startModels(modes, mode) {
87
+ const ordered = [modes[mode]?.model, mode === 'normal' ? undefined : modes.normal?.model, latestChoice(modes)?.model];
88
+ return [...new Set(ordered.filter((reference) => typeof reference === 'string' && reference.length > 0))];
89
+ }
package/dist/sdk/cli.js CHANGED
@@ -48,6 +48,10 @@ Standalone terminal options:
48
48
  ~/.xingular-harness/data; npm run dev passes its own data root)
49
49
  --state <dir> State directory (interactive profile default; otherwise
50
50
  ~/.xingular-harness/state; npm run dev passes its own state directory)
51
+ --account-state <dir>
52
+ Sign in as the accounts kept in that state directory (its
53
+ accounts folder and secrets file); npm run dev shares the
54
+ installed command's account state by default
51
55
  --worktree [name], -w [name]
52
56
  Start in a new managed worktree of this repository, or in
53
57
  the named one
@@ -0,0 +1,4 @@
1
+ import type * as Pi from '@earendil-works/pi-coding-agent';
2
+ import type { Found } from "../plugins/discover.js";
3
+ /** Restore package identity lost when Harness passes individually selected paths to Pi. */
4
+ export declare function applyExtensionOwners(loader: Pi.DefaultResourceLoader, found: readonly Found[]): void;
@@ -0,0 +1,17 @@
1
+ import { resolve, sep } from 'node:path';
2
+ /** Restore package identity lost when Harness passes individually selected paths to Pi. */
3
+ export function applyExtensionOwners(loader, found) {
4
+ for (const extension of loader.getExtensions().extensions) {
5
+ if (extension.hidden)
6
+ continue;
7
+ const path = resolve(extension.resolvedPath || extension.path);
8
+ const owner = found.filter(item => item.kind === 'extension' && item.packageRoot && (path === resolve(item.path) || path.startsWith(`${resolve(item.path)}${sep}`)))
9
+ .sort((a, b) => b.path.length - a.path.length)[0];
10
+ if (!owner?.packageRoot)
11
+ continue;
12
+ const sourceInfo = { ...extension.sourceInfo, origin: 'package', baseDir: owner.packageRoot, source: owner.source ?? owner.packageRoot };
13
+ extension.sourceInfo = sourceInfo;
14
+ for (const command of extension.commands.values())
15
+ command.sourceInfo = sourceInfo;
16
+ }
17
+ }
@@ -2,6 +2,7 @@
2
2
  // terminal palette and a host's menu both read it, so they never keep their own lists.
3
3
  import { BUILTIN_PLUGIN_REGISTRY } from "../plugins/builtin.js";
4
4
  import { pluginCommandPrefix } from "../plugins/commandPrefix.js";
5
+ import { packageManifest } from "../plugins/manifest.js";
5
6
  import { CORE_COMMANDS } from "./registry.js";
6
7
  import { commandRoutes, promptCommandAvailable } from "./routes.js";
7
8
  export function listCommands(plugins) {
@@ -58,8 +59,20 @@ export function listCommands(plugins) {
58
59
  }
59
60
  }
60
61
  // Catalogue entries without a path are observed extension commands, not templates.
61
- if (contribution.kind === 'command' && contribution.path && promptCommandAvailable(contribution.name, taken, extensionCommandNames) && !out.has(contribution.name)) {
62
- out.set(contribution.name, { name: contribution.name, description: contribution.description, group: 'Prompts', source: 'prompt', owner: plugin.id });
62
+ if (contribution.kind === 'command' && contribution.path) {
63
+ const packageRoot = (plugin.source === 'package' || plugin.id.startsWith('package:')) ? plugin.path : null;
64
+ const producer = plugin.contributions.find(item => item.kind === 'code' && item.state === 'on' && item.path && item.registered?.resources?.some(resource => resource.kind === 'command' && resource.path === contribution.path));
65
+ if (packageRoot || producer?.path) {
66
+ const prefix = pluginCommandPrefix(packageRoot ? { path: contribution.path, origin: 'package', baseDir: packageRoot } : { path: producer.path });
67
+ const name = packageRoot && packageManifest(packageRoot).defaultPrompt === contribution.name ? '' : contribution.name;
68
+ if (/^[a-z][a-z0-9-]*$/.test(name) || name === '') {
69
+ extensions.push({ prefix, name, owner: packageRoot ? `package:${packageRoot}` : `extension:${producer.path}`, path: contribution.path,
70
+ listed: { name: `${prefix}:${name}`, description: contribution.description, group: 'Prompts', source: 'prompt', owner: plugin.id } });
71
+ }
72
+ }
73
+ else if (promptCommandAvailable(contribution.name, taken, extensionCommandNames) && !out.has(contribution.name)) {
74
+ out.set(contribution.name, { name: contribution.name, description: contribution.description, group: 'Prompts', source: 'prompt', owner: plugin.id });
75
+ }
63
76
  }
64
77
  if (contribution.kind === 'skill') {
65
78
  const name = `skill:${contribution.name}`;
@@ -0,0 +1,5 @@
1
+ import type * as Pi from '@earendil-works/pi-coding-agent';
2
+ import type { Found } from "../plugins/discover.js";
3
+ import type { CommandRoute } from "./routes.js";
4
+ /** Pi deduplicates by bare filename before its override; scan paths separately before qualifying. */
5
+ export declare function wrapPromptLoader(pi: typeof Pi, loader: Pi.DefaultResourceLoader, found: readonly Found[], paths: readonly string[], cwd: string, agentDir: string, extensions?: () => readonly CommandRoute[], bare?: Set<string>): Promise<Set<string>>;
@@ -0,0 +1,76 @@
1
+ import { readdirSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { namespacePrompts, promptPackageRoot } from "./promptRoutes.js";
4
+ import { pluginCommandPrefix } from "../plugins/commandPrefix.js";
5
+ const originalGetters = new WeakMap();
6
+ /** Pi deduplicates by bare filename before its override; scan paths separately before qualifying. */
7
+ export async function wrapPromptLoader(pi, loader, found, paths, cwd, agentDir, extensions = () => [], bare = new Set()) {
8
+ const scan = async (paths) => {
9
+ const files = paths.flatMap(path => {
10
+ try {
11
+ return statSync(path).isDirectory()
12
+ ? readdirSync(path).filter(name => name.endsWith('.md') && !name.startsWith('.')).sort().map(name => join(path, name))
13
+ : [path];
14
+ }
15
+ catch {
16
+ return [];
17
+ }
18
+ });
19
+ const templates = [];
20
+ for (const path of [...new Set(files)]) {
21
+ const scanner = new pi.DefaultResourceLoader({ cwd, agentDir, settingsManager: pi.SettingsManager.inMemory({}), noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, additionalPromptTemplatePaths: [path] });
22
+ await scanner.reload();
23
+ templates.push(...scanner.getPrompts().prompts);
24
+ }
25
+ return templates;
26
+ };
27
+ const templates = await scan(paths);
28
+ const discovered = new Map();
29
+ for (const extension of loader.getExtensions().extensions) {
30
+ if (extension.hidden)
31
+ continue;
32
+ const handlers = extension.handlers.get('resources_discover');
33
+ if (!handlers)
34
+ continue;
35
+ const source = extension.sourceInfo;
36
+ extension.handlers.set('resources_discover', handlers.map((handler, index) => async (event, context) => {
37
+ const result = await handler(event, context);
38
+ const key = `${extension.resolvedPath}:${index}`;
39
+ if (!result)
40
+ discovered.delete(key);
41
+ else {
42
+ const paths = (result.promptPaths ?? []).map(path => resolve(dirname(extension.resolvedPath), path));
43
+ const isPackage = source.origin === 'package' && !!source.baseDir;
44
+ const root = isPackage ? source.baseDir : extension.resolvedPath;
45
+ const commandOwner = isPackage ? undefined : { prefix: pluginCommandPrefix(source), owner: `extension:${source.path}` };
46
+ const owners = paths.map(path => ({ kind: 'prompt', path, origin: isPackage ? 'package' : 'shared', packageRoot: root, source: source.source, project: source.scope === 'project', enabled: true, ...(commandOwner ? { commandOwner } : {}) }));
47
+ discovered.set(key, { owners, prompts: await scan(paths) });
48
+ }
49
+ return result;
50
+ }));
51
+ }
52
+ bare.clear();
53
+ for (const prompt of templates)
54
+ if (promptPackageRoot(prompt, found))
55
+ bare.add(prompt.name);
56
+ const getPrompts = originalGetters.get(loader) ?? loader.getPrompts.bind(loader);
57
+ originalGetters.set(loader, getPrompts);
58
+ loader.getPrompts = () => {
59
+ const base = getPrompts();
60
+ const dynamic = [...discovered.values()];
61
+ const owners = [...found, ...dynamic.flatMap(item => item.owners)];
62
+ const byPath = new Map(base.prompts.map(prompt => [prompt.filePath, prompt]));
63
+ for (const prompt of [...templates, ...dynamic.flatMap(item => item.prompts)]) {
64
+ if (byPath.has(prompt.filePath))
65
+ continue;
66
+ if (promptPackageRoot(prompt, owners) || ![...byPath.values()].some(item => item.name === prompt.name && !promptPackageRoot(item, owners)))
67
+ byPath.set(prompt.filePath, prompt);
68
+ }
69
+ bare.clear();
70
+ for (const prompt of byPath.values())
71
+ if (promptPackageRoot(prompt, owners))
72
+ bare.add(prompt.name);
73
+ return { ...base, prompts: namespacePrompts([...byPath.values()], owners, extensions()) };
74
+ };
75
+ return bare;
76
+ }
@@ -0,0 +1,13 @@
1
+ import type { PromptTemplate } from '@earendil-works/pi-coding-agent';
2
+ import type { Found } from "../plugins/discover.js";
3
+ import { type CommandRoute } from "./routes.js";
4
+ export type PromptOwner = Found & {
5
+ commandOwner?: {
6
+ prefix: string;
7
+ owner: string;
8
+ };
9
+ };
10
+ export declare function promptOwner(path: string, found: readonly PromptOwner[]): PromptOwner | undefined;
11
+ export declare function promptPackageRoot(prompt: PromptTemplate, found: readonly PromptOwner[]): string | null;
12
+ /** Rewrite only package-owned templates; the original content and Pi's argument substitution stay intact. */
13
+ export declare function namespacePrompts(prompts: readonly PromptTemplate[], found: readonly PromptOwner[], extensions?: readonly CommandRoute[]): PromptTemplate[];
@@ -0,0 +1,46 @@
1
+ import { resolve, sep } from 'node:path';
2
+ import { pluginCommandPrefix } from "../plugins/commandPrefix.js";
3
+ import { packageManifest } from "../plugins/manifest.js";
4
+ import { commandRoutes } from "./routes.js";
5
+ /** Resolve ownership from the Harness-selected resources, not the user-controlled filename. */
6
+ function promptOwners(path, found) {
7
+ const target = resolve(path);
8
+ return found.filter(item => item.kind === 'prompt' && item.packageRoot && (target === resolve(item.path) || target.startsWith(`${resolve(item.path)}${sep}`)))
9
+ .sort((a, b) => b.path.length - a.path.length);
10
+ }
11
+ export function promptOwner(path, found) {
12
+ return promptOwners(path, found)[0];
13
+ }
14
+ export function promptPackageRoot(prompt, found) {
15
+ return promptOwner(prompt.filePath, found)?.packageRoot ?? (prompt.sourceInfo.origin === 'package' ? prompt.sourceInfo.baseDir ?? null : null);
16
+ }
17
+ /** Rewrite only package-owned templates; the original content and Pi's argument substitution stay intact. */
18
+ export function namespacePrompts(prompts, found, extensions = []) {
19
+ const loose = [];
20
+ const routes = [];
21
+ for (const prompt of prompts) {
22
+ const owners = new Set(promptOwners(prompt.filePath, found).map(owner => owner.packageRoot));
23
+ if (owners.size > 1)
24
+ continue;
25
+ const packageRoot = promptPackageRoot(prompt, found);
26
+ if (!packageRoot) {
27
+ if (!prompt.name.includes(':'))
28
+ loose.push(prompt);
29
+ continue;
30
+ }
31
+ const attribution = promptOwner(prompt.filePath, found)?.commandOwner;
32
+ const prefix = attribution?.prefix ?? pluginCommandPrefix({ path: prompt.filePath, origin: 'package', baseDir: packageRoot });
33
+ const name = !attribution && packageManifest(packageRoot).defaultPrompt === prompt.name ? '' : prompt.name;
34
+ if (name && !/^[a-z][a-z0-9-]*$/.test(name))
35
+ continue;
36
+ routes.push({ prefix, name, owner: attribution?.owner ?? `package:${packageRoot}`, path: prompt.filePath, prompt });
37
+ }
38
+ const index = commandRoutes([...extensions, ...routes]);
39
+ const selected = routes.flatMap(route => {
40
+ const key = `${route.prefix}:${route.name}`;
41
+ return !index.conflictingPrefixes.has(route.prefix) && index.routes.get(key)?.length === 1
42
+ ? [{ ...route.prompt, name: key }]
43
+ : [];
44
+ });
45
+ return [...loose, ...selected];
46
+ }
@@ -203,6 +203,20 @@ export declare const CORE_COMMANDS: readonly [{
203
203
  readonly description: "Browse skills, prompts and rules for this Harness scope";
204
204
  readonly group: "Harness";
205
205
  readonly kind: "page";
206
+ }, {
207
+ readonly name: "variant";
208
+ readonly args: "[use|restore|tag|untag|diff|revert]";
209
+ readonly description: "Versions of this variant: switch, restore, tag, compare, take components back";
210
+ readonly group: "Harness";
211
+ readonly kind: "session";
212
+ readonly methods: readonly ["variants.lineage", "variants.compare", "variants.restore", "variants.tag", "variants.untag", "variants.revert"];
213
+ }, {
214
+ readonly name: "refine";
215
+ readonly args: "[guidance|status|review|stop]";
216
+ readonly description: "Improve this variant by replaying your last request: /refine <what to look at>";
217
+ readonly group: "Harness";
218
+ readonly kind: "session";
219
+ readonly methods: readonly ["refine.fromRun", "refine.start", "refine.list", "refine.cancel", "refine.candidates", "refine.candidateDiff", "refine.candidateOutput", "refine.adopt"];
206
220
  }, {
207
221
  readonly name: "settings";
208
222
  readonly description: "Session, terminal and browser settings";
@@ -32,6 +32,8 @@ export const CORE_COMMANDS = [
32
32
  { name: 'plugins', description: 'Manage local plugins, packages, trust and settings', group: 'Harness', kind: 'page', methods: ['plugins.list', 'plugins.attach', 'plugins.detach', 'plugins.trust', 'plugins.untrust', 'plugins.configure', 'plugins.install', 'plugins.update', 'plugins.remove', 'hub.list'] },
33
33
  { name: 'hub', description: 'Browse the Community catalog and manage Hub installs', group: 'Harness', kind: 'page', methods: ['hub.list', 'hub.install', 'hub.uninstall'] },
34
34
  { name: 'components', description: 'Browse skills, prompts and rules for this Harness scope', group: 'Harness', kind: 'page' },
35
+ { name: 'variant', args: '[use|restore|tag|untag|diff|revert]', description: 'Versions of this variant: switch, restore, tag, compare, take components back', group: 'Harness', kind: 'session', methods: ['variants.lineage', 'variants.compare', 'variants.restore', 'variants.tag', 'variants.untag', 'variants.revert'] },
36
+ { name: 'refine', args: '[guidance|status|review|stop]', description: 'Improve this variant by replaying your last request: /refine <what to look at>', group: 'Harness', kind: 'session', methods: ['refine.fromRun', 'refine.start', 'refine.list', 'refine.cancel', 'refine.candidates', 'refine.candidateDiff', 'refine.candidateOutput', 'refine.adopt'] },
35
37
  { name: 'settings', description: 'Session, terminal and browser settings', group: 'Harness', kind: 'page' },
36
38
  { name: 'doctor', description: 'Check account, model, tools and runtime readiness', group: 'Harness', kind: 'page', methods: ['doctor.start', 'doctor.read'] },
37
39
  { name: 'worktree', description: 'Manage repository worktrees', group: 'Harness', kind: 'page', methods: ['worktrees.list'] },
@@ -0,0 +1,4 @@
1
+ import type { AgentSession } from '@earendil-works/pi-coding-agent';
2
+ import type { Found } from "../plugins/discover.js";
3
+ /** Intercept before Pi can dispatch a bare extension command. */
4
+ export declare function installPluginCommandRouter(session: AgentSession, found: readonly Found[], barePrompts: Set<string>): () => string[];
@@ -0,0 +1,48 @@
1
+ import { resolve, sep } from 'node:path';
2
+ import { HarnessError } from "../core/errors.js";
3
+ import { pluginCommandPrefix } from "../plugins/commandPrefix.js";
4
+ import { commandRoutes } from "./routes.js";
5
+ /** Intercept before Pi can dispatch a bare extension command. */
6
+ export function installPluginCommandRouter(session, found, barePrompts) {
7
+ const registrations = () => session.extensionRunner.getRegisteredCommands().map(command => {
8
+ const source = command.sourceInfo;
9
+ const path = resolve(source.path);
10
+ const owner = found.filter(item => item.kind === 'extension' && item.packageRoot && (path === resolve(item.path) || path.startsWith(`${resolve(item.path)}${sep}`))).sort((a, b) => b.path.length - a.path.length)[0];
11
+ const prefix = pluginCommandPrefix(owner?.packageRoot ? { path: source.path, origin: 'package', baseDir: owner.packageRoot } : source);
12
+ return { ...command, prefix, owner: owner?.packageRoot ? `package:${owner.packageRoot}` : source.origin === 'package' ? `package:${source.baseDir ?? source.source}` : `extension:${source.path}`, path: source.path };
13
+ });
14
+ const originalPrompt = session.prompt.bind(session);
15
+ session.prompt = async (text, options) => {
16
+ if (options?.expandPromptTemplates === false)
17
+ return originalPrompt(text, options);
18
+ const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(text.trim());
19
+ if (match) {
20
+ const name = match[1];
21
+ const index = commandRoutes(registrations());
22
+ const promptNames = new Set(session.resourceLoader.getPrompts().prompts.map(prompt => prompt.name));
23
+ if (name.startsWith('plugin:') || index.byName.has(name) || (barePrompts.has(name) && !promptNames.has(name))) {
24
+ throw new HarnessError('invalid_request', `Plugin command /${name} requires its owner prefix.`);
25
+ }
26
+ const separator = name.indexOf(':');
27
+ const prefix = separator < 0 ? '' : name.slice(0, separator);
28
+ if (separator > 0 && index.ownersByPrefix.has(prefix)) {
29
+ if (index.conflictingPrefixes.has(prefix))
30
+ throw new HarnessError('invalid_request', `Plugin prefix /${prefix}: is ambiguous.`);
31
+ const matches = index.routes.get(name) ?? [];
32
+ if (matches.length > 1 || matches.length === 1 && promptNames.has(name))
33
+ throw new HarnessError('invalid_request', `Plugin command /${name} is ambiguous.`);
34
+ if (matches.length === 1) {
35
+ const command = session.extensionRunner.getCommand(matches[0].invocationName);
36
+ if (!command)
37
+ throw new HarnessError('invalid_request', `Plugin command /${name} is unavailable.`);
38
+ await command.handler(match[2]?.trim() ?? '', session.extensionRunner.createCommandContext());
39
+ return;
40
+ }
41
+ if (!promptNames.has(name))
42
+ throw new HarnessError('invalid_request', `Unknown plugin command /${name}.`);
43
+ }
44
+ }
45
+ await originalPrompt(text, options);
46
+ };
47
+ return () => [...registrations().map(command => `${command.prefix}:${command.name}`), ...session.resourceLoader.getPrompts().prompts.map(prompt => prompt.name)];
48
+ }
@@ -0,0 +1,40 @@
1
+ import type { ToolSession } from "../tools/types.js";
2
+ import { type ComputerControlBackend } from "./control.js";
3
+ export type ComputerAction = 'click' | 'type' | 'key' | 'activate';
4
+ export interface ComputerApprovalDetails {
5
+ action: ComputerAction;
6
+ target: string;
7
+ /** Backend window identity; the host must not use a mutable selection as its handle. */
8
+ handle: string;
9
+ args: Record<string, unknown>;
10
+ capture?: {
11
+ id: string;
12
+ sha256: string;
13
+ width: number;
14
+ height: number;
15
+ mimeType: string;
16
+ };
17
+ }
18
+ /** Trusted parent backend. Revalidation must refuse revoked or changed targets/captures. Each
19
+ * effect must itself atomically enforce the control backend's point-of-effect requirements;
20
+ * a separate revalidation cannot close the race with revocation or window changes. */
21
+ export interface ComputerBoundaryBackend extends ComputerControlBackend {
22
+ revalidate(session: ToolSession, details: Readonly<ComputerApprovalDetails>): Promise<void>;
23
+ }
24
+ /** Trusted live state, not model input. Missing/unknown state must not be reported as attended. */
25
+ export interface ComputerBoundaryState {
26
+ attended: boolean;
27
+ plan: boolean;
28
+ }
29
+ /** An unregistered parent-side boundary for one ToolSession. The caller must still route every
30
+ * tool call through the normal gate, and keep this instance and its backend in the parent process.
31
+ * Target selection and capture are observations; click, type, key and activate each ask anew.
32
+ * The approval includes typed text and window identity in run events: do not use for secrets. */
33
+ export declare function createComputerBoundary(session: ToolSession, backend: ComputerBoundaryBackend, state: () => ComputerBoundaryState): {
34
+ target: (input: unknown) => Promise<import("./contracts.js").ComputerTarget>;
35
+ screenshot: (input: unknown) => Promise<import("./contracts.js").ComputerControlScreenshot>;
36
+ click: (input: unknown) => Promise<void>;
37
+ type: (input: unknown) => Promise<void>;
38
+ key: (input: unknown) => Promise<void>;
39
+ activate: (input: unknown) => Promise<void>;
40
+ };
@@ -0,0 +1,79 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { HarnessError } from "../core/errors.js";
3
+ import { createComputerControl } from "./control.js";
4
+ /** An unregistered parent-side boundary for one ToolSession. The caller must still route every
5
+ * tool call through the normal gate, and keep this instance and its backend in the parent process.
6
+ * Target selection and capture are observations; click, type, key and activate each ask anew.
7
+ * The approval includes typed text and window identity in run events: do not use for secrets. */
8
+ export function createComputerBoundary(session, backend, state) {
9
+ const run = session.run;
10
+ let current;
11
+ let busy = false;
12
+ function check() {
13
+ if (session.run !== run || run.finished)
14
+ throw new HarnessError('run_stopped', 'The run was stopped; computer control is cancelled.');
15
+ const live = state();
16
+ if (!live || live.attended !== true || live.plan !== false)
17
+ throw new HarnessError('computer_unavailable', 'Computer control requires an attended, non-plan run.');
18
+ }
19
+ async function approve(handle, shot) {
20
+ check();
21
+ if (!current)
22
+ throw new HarnessError('computer_error', 'Missing computer action.');
23
+ const { action, input } = current;
24
+ const details = {
25
+ action, target: input.target, handle,
26
+ args: Object.fromEntries(Object.entries(input).filter(([key]) => key !== 'target' && key !== 'screenshot')),
27
+ ...(shot ? { capture: { id: input.screenshot, sha256: createHash('sha256').update(shot.data).digest('hex'), width: shot.width, height: shot.height, mimeType: shot.mimeType } } : {})
28
+ };
29
+ // Pass independent copies across trust boundaries; neither approval presentation nor a backend
30
+ // may mutate the private, approved action before the effect.
31
+ const description = JSON.stringify(details);
32
+ const decision = await run.requestApproval({ target: `computer_${action}`, action: description, operation: { tool: `computer_${action}`, args: JSON.parse(description) }, rememberable: false, standing: 'none' });
33
+ check();
34
+ if (decision !== 'approved')
35
+ throw new HarnessError('computer_denied', 'Computer action was not approved.');
36
+ await backend.revalidate(session, JSON.parse(description));
37
+ check();
38
+ }
39
+ const guarded = {
40
+ target: (s) => backend.target(s),
41
+ screenshot: (s, handle) => backend.screenshot(s, handle),
42
+ click: async (s, handle, shot, input) => { await approve(handle, shot); check(); await backend.click(s, handle, shot, input); },
43
+ type: async (s, handle, text) => { await approve(handle); check(); await backend.type(s, handle, text); },
44
+ key: async (s, handle, key) => { await approve(handle); check(); await backend.key(s, handle, key); },
45
+ activate: async (s, handle) => { await approve(handle); check(); await backend.activate(s, handle); }
46
+ };
47
+ const control = createComputerControl(session, guarded);
48
+ async function call(input, action, execute) {
49
+ check();
50
+ if (busy)
51
+ throw new HarnessError('computer_busy', 'A computer operation is already in progress.');
52
+ // Clone before the first await, including while another actor can hold the input object.
53
+ let copy;
54
+ try {
55
+ copy = structuredClone(input);
56
+ }
57
+ catch {
58
+ throw new HarnessError('invalid_input', 'Invalid computer control input.');
59
+ }
60
+ busy = true;
61
+ try {
62
+ if (action)
63
+ current = { action, input: copy };
64
+ return await execute(copy);
65
+ }
66
+ finally {
67
+ current = undefined;
68
+ busy = false;
69
+ }
70
+ }
71
+ return {
72
+ target: (input) => call(input, undefined, control.target),
73
+ screenshot: (input) => call(input, undefined, control.screenshot),
74
+ click: (input) => call(input, 'click', control.click),
75
+ type: (input) => call(input, 'type', control.type),
76
+ key: (input) => call(input, 'key', control.key),
77
+ activate: (input) => call(input, 'activate', control.activate)
78
+ };
79
+ }
@@ -0,0 +1,127 @@
1
+ export declare const COMPUTER_LIMITS: {
2
+ readonly id: 128;
3
+ readonly text: 10000;
4
+ readonly dimension: 16384;
5
+ readonly imageData: 20000000;
6
+ };
7
+ export declare const COMPUTER_KEYS: readonly ["Enter", "Tab", "Escape", "Backspace", "Delete", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown", "Space"];
8
+ export declare const COMPUTER_CONTROL_SCHEMAS: {
9
+ readonly target: {
10
+ readonly type: "object";
11
+ readonly properties: {};
12
+ readonly additionalProperties: false;
13
+ };
14
+ readonly screenshot: {
15
+ readonly type: "object";
16
+ readonly properties: {
17
+ target: {
18
+ type: string;
19
+ minLength: number;
20
+ maxLength: 128;
21
+ };
22
+ };
23
+ readonly required: readonly ["target"];
24
+ readonly additionalProperties: false;
25
+ };
26
+ readonly click: {
27
+ readonly type: "object";
28
+ readonly properties: {
29
+ readonly screenshot: {
30
+ type: string;
31
+ minLength: number;
32
+ maxLength: 128;
33
+ };
34
+ readonly x: {
35
+ readonly type: "integer";
36
+ readonly minimum: 0;
37
+ };
38
+ readonly y: {
39
+ readonly type: "integer";
40
+ readonly minimum: 0;
41
+ };
42
+ readonly button: {
43
+ readonly type: "string";
44
+ readonly enum: readonly ["left", "right", "middle"];
45
+ };
46
+ readonly target: {
47
+ type: string;
48
+ minLength: number;
49
+ maxLength: 128;
50
+ };
51
+ };
52
+ readonly required: readonly ["target", "screenshot", "x", "y", "button"];
53
+ readonly additionalProperties: false;
54
+ };
55
+ readonly type: {
56
+ readonly type: "object";
57
+ readonly properties: {
58
+ readonly text: {
59
+ readonly type: "string";
60
+ readonly minLength: 1;
61
+ readonly maxLength: 10000;
62
+ };
63
+ readonly target: {
64
+ type: string;
65
+ minLength: number;
66
+ maxLength: 128;
67
+ };
68
+ };
69
+ readonly required: readonly ["target", "text"];
70
+ readonly additionalProperties: false;
71
+ };
72
+ readonly key: {
73
+ readonly type: "object";
74
+ readonly properties: {
75
+ readonly key: {
76
+ readonly type: "string";
77
+ readonly enum: readonly ["Enter", "Tab", "Escape", "Backspace", "Delete", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown", "Space"];
78
+ };
79
+ readonly target: {
80
+ type: string;
81
+ minLength: number;
82
+ maxLength: 128;
83
+ };
84
+ };
85
+ readonly required: readonly ["target", "key"];
86
+ readonly additionalProperties: false;
87
+ };
88
+ readonly activate: {
89
+ readonly type: "object";
90
+ readonly properties: {
91
+ target: {
92
+ type: string;
93
+ minLength: number;
94
+ maxLength: 128;
95
+ };
96
+ };
97
+ readonly required: readonly ["target"];
98
+ readonly additionalProperties: false;
99
+ };
100
+ };
101
+ export type ComputerKey = typeof COMPUTER_KEYS[number];
102
+ export type ComputerButton = 'left' | 'right' | 'middle';
103
+ export interface ComputerTargetInput {
104
+ target: string;
105
+ }
106
+ export interface ComputerClickInput extends ComputerTargetInput {
107
+ screenshot: string;
108
+ x: number;
109
+ y: number;
110
+ button: ComputerButton;
111
+ }
112
+ export interface ComputerTypeInput extends ComputerTargetInput {
113
+ text: string;
114
+ }
115
+ export interface ComputerKeyInput extends ComputerTargetInput {
116
+ key: ComputerKey;
117
+ }
118
+ export interface ComputerTarget {
119
+ target: string;
120
+ }
121
+ export interface ComputerControlScreenshot {
122
+ screenshot: string;
123
+ data: string;
124
+ mimeType: 'image/png' | 'image/jpeg';
125
+ width: number;
126
+ height: number;
127
+ }
@@ -0,0 +1,13 @@
1
+ // Backend-neutral contracts. Importing this module does not register tools or grant permission.
2
+ export const COMPUTER_LIMITS = { id: 128, text: 10_000, dimension: 16_384, imageData: 20_000_000 };
3
+ export const COMPUTER_KEYS = ['Enter', 'Tab', 'Escape', 'Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Space'];
4
+ const id = { type: 'string', minLength: 1, maxLength: COMPUTER_LIMITS.id };
5
+ const target = { target: id };
6
+ export const COMPUTER_CONTROL_SCHEMAS = {
7
+ target: { type: 'object', properties: {}, additionalProperties: false },
8
+ screenshot: { type: 'object', properties: target, required: ['target'], additionalProperties: false },
9
+ click: { type: 'object', properties: { ...target, screenshot: id, x: { type: 'integer', minimum: 0 }, y: { type: 'integer', minimum: 0 }, button: { type: 'string', enum: ['left', 'right', 'middle'] } }, required: ['target', 'screenshot', 'x', 'y', 'button'], additionalProperties: false },
10
+ type: { type: 'object', properties: { ...target, text: { type: 'string', minLength: 1, maxLength: COMPUTER_LIMITS.text } }, required: ['target', 'text'], additionalProperties: false },
11
+ key: { type: 'object', properties: { ...target, key: { type: 'string', enum: COMPUTER_KEYS } }, required: ['target', 'key'], additionalProperties: false },
12
+ activate: { type: 'object', properties: target, required: ['target'], additionalProperties: false }
13
+ };