openmerit 0.1.11 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +20 -56
  3. package/dist/pi/scout-extension.mjs +190 -0
  4. package/dist/pi/src/index.d.ts +6 -32
  5. package/dist/pi/src/index.js +49 -787
  6. package/dist/terminal/public/app.js +37 -37
  7. package/dist/terminal/public/styles.css +0 -125
  8. package/dist/terminal/scout-update.json +1 -1
  9. package/dist/terminal/src/cli.mjs +2 -0
  10. package/dist/terminal/src/install.mjs +103 -166
  11. package/dist/terminal/src/scout-credentials.d.ts +12 -0
  12. package/dist/terminal/src/scout-credentials.js +41 -0
  13. package/dist/terminal/src/scout-credentials.ts +44 -0
  14. package/dist/terminal/src/scout-instructions.d.ts +5 -0
  15. package/dist/terminal/src/scout-instructions.js +116 -0
  16. package/dist/terminal/src/scout-instructions.ts +119 -0
  17. package/dist/terminal/src/scout-pi.d.ts +44 -0
  18. package/dist/terminal/src/scout-pi.js +84 -0
  19. package/dist/terminal/src/scout-pi.ts +76 -0
  20. package/dist/terminal/src/scout.d.ts +77 -0
  21. package/dist/terminal/src/scout.js +181 -0
  22. package/dist/terminal/src/scout.ts +164 -0
  23. package/dist/terminal/src/server.mjs +1 -1
  24. package/dist/terminal/src/telemetry.mjs +2 -2
  25. package/docs/commands.md +3 -77
  26. package/docs/getting-started.md +20 -45
  27. package/docs/index.md +9 -14
  28. package/docs/inference-terminal.md +2 -63
  29. package/docs/pi-extension.md +32 -28
  30. package/docs/roadmap.md +6 -18
  31. package/docs/scout.md +39 -255
  32. package/docs/security.md +8 -14
  33. package/docs/testing.md +8 -34
  34. package/docs/troubleshooting.md +23 -28
  35. package/package.json +6 -27
  36. package/dist/core/src/index.d.ts +0 -101
  37. package/dist/core/src/index.js +0 -1649
  38. package/dist/core/src/store.d.ts +0 -35
  39. package/dist/core/src/store.js +0 -102
  40. package/dist/pi/src/scheduler.d.ts +0 -11
  41. package/dist/pi/src/scheduler.js +0 -137
  42. package/dist/pi/src/wakeup.d.ts +0 -2
  43. package/dist/pi/src/wakeup.js +0 -108
  44. package/dist/protocol/src/index.d.ts +0 -484
  45. package/dist/protocol/src/index.js +0 -47
  46. package/dist/protocol/src/schemas.d.ts +0 -576
  47. package/dist/protocol/src/schemas.js +0 -280
  48. package/dist/terminal/public/brands/vllm.ico +0 -0
  49. package/dist/terminal/public/flow.css +0 -1
  50. package/dist/terminal/public/flow.js +0 -770
  51. package/dist/terminal/src/demo-policy.mjs +0 -205
  52. package/dist/terminal/src/enterprise-sample.mjs +0 -151
  53. package/docs/adapter-guide.md +0 -189
  54. package/docs/architecture.md +0 -59
  55. package/docs/automation.md +0 -74
  56. package/docs/budgets.md +0 -37
  57. package/docs/demo-backfill.md +0 -31
  58. package/docs/demo-fieldkit.md +0 -49
  59. package/docs/demo-placement.md +0 -32
  60. package/docs/demo-spam.md +0 -17
  61. package/docs/demo-support.md +0 -44
  62. package/docs/demo.md +0 -74
  63. package/docs/first-trial.md +0 -60
  64. package/docs/interactive-demo.md +0 -118
  65. package/docs/lifecycle.md +0 -30
  66. package/docs/metrics-and-evidence.md +0 -48
  67. package/docs/operations.md +0 -38
  68. package/docs/pareto-spec.md +0 -76
  69. package/docs/saga/a-steadier-compass.md +0 -25
  70. package/docs/saga/defining-a-task-for-ai.md +0 -154
  71. package/docs/saga/the-benchmark-is-not-the-job.md +0 -33
  72. package/docs/ux-reference.md +0 -32
@@ -0,0 +1,116 @@
1
+ export const rule = `# Application model decisions · OpenMerit Scout
2
+
3
+ Before choosing, recommending, adding, downloading, replacing or configuring
4
+ ANY application inference model, load the \`openmerit-scout\` skill and consult
5
+ \`scout_models\` on the \`openmerit\` MCP server before committing to a model.
6
+ This applies even when the user only asks you to build a feature, never mentions
7
+ models or Scout, or names a model themselves (assess it; do not silently replace it).
8
+
9
+ A pretrained model, local weights, browser inference, an SDK's default model,
10
+ embeddings, OCR, speech, image classification, detection and segmentation all
11
+ count as model choices, not implementation details. Identify this decision before
12
+ writing model-specific code, installing a model package or downloading weights.
13
+
14
+ Follow the skill's project access policy. If it is missing, ask and save it first.
15
+ Scout may answer with clarifying questions: relay them to the user and continue
16
+ the same Scout conversation with their answers before choosing.
17
+ If Scout is unavailable, fails or has no suitable evidence/candidate, disclose the
18
+ gap and pause the model decision; do not fall back to a remembered or SDK-default
19
+ model. You may continue work that does not commit to a model.
20
+
21
+ Do not consult Scout for unrelated edits, normal inference calls using an unchanged
22
+ approved model, or this coding agent's own model. Do not reselect approved models
23
+ unless the task introduces or changes a model decision.
24
+
25
+ When the user says "update openmerit", run
26
+ \`npx -y openmerit@latest update --scope user\` (use \`--scope project\` if this
27
+ rule is in the project's .claude/rules directory). Report the result, including
28
+ any conflict or manual-upgrade requirement. Do not delete edited files, bypass
29
+ permissions or rerun login automatically. A new session loads updated instructions.
30
+ `;
31
+ export const skill = `---
32
+ name: openmerit-scout
33
+ description: Consults OpenMerit Scout before choosing, adding, downloading, replacing or configuring any application inference model, including implicit choices while building features, pretrained browser/local models, SDK defaults, embeddings, OCR, speech, classification, detection, segmentation, LLMs and agents. Not for unrelated edits, ordinary inference calls or this coding agent's own model.
34
+ ---
35
+
36
+ # OpenMerit · Scout
37
+
38
+ Before introducing, recommending, replacing or configuring an application
39
+ inference model, call the \`scout_models\` tool on the \`openmerit\` MCP server.
40
+ This applies even when the user never mentions models or Scout. Downloading local
41
+ weights, using a pretrained browser model or accepting an SDK default is a model
42
+ decision: consult Scout before model-specific code, installs or downloads.
43
+ Preserve the user's explicit model choice; assess it rather than silently replacing
44
+ it. Leave unchanged, approved application selections in place.
45
+
46
+ ## Project policy
47
+
48
+ Read \`.openmerit/scout.json\` before searching. If it is absent, ask once whether this
49
+ project uses **existing-only** (only endpoints it can already reach) or
50
+ **existing-first** (prefer them, ask before searching the whole catalogue), and
51
+ which public catalogue endpoint IDs it can access. Save the answer:
52
+
53
+ \`\`\`sh
54
+ npx -y openmerit@latest project --policy existing-only --endpoint-id <id> ...
55
+ \`\`\`
56
+
57
+ Never infer access from a model name, SDK or environment-variable name. Never
58
+ record credentials, private URLs, prompts or customer data. An empty inventory
59
+ is not permission to search all models.
60
+
61
+ ## Searching
62
+
63
+ Call \`scout_models\` with a non-confidential task description as \`prompt\` and
64
+ \`endpointIds\` set to the saved inventory, including \`[]\` when empty. Send
65
+ only task requirements, never source files, secrets or real customer records.
66
+ If the MCP tool is unavailable, run
67
+ \`npx -y openmerit@latest scout "<task>" --json\`; it applies the saved inventory.
68
+
69
+ Scout is a conversation with the agent behind openmerit.ai/scout. When
70
+ \`status\` is \`needs_answers\`, fill in what the user or project already states,
71
+ show the user Scout's brief and remaining questions, and wait for their answers.
72
+ Then call again with the returned \`conversationId\` and \`brief\` set to the
73
+ rewritten components, or \`skip: true\` if the user wants Scout to assume. Never
74
+ answer Scout's questions with guesses. Send later refinements to the same
75
+ \`conversationId\`. A call with only a \`conversationId\` reads an interrupted turn.
76
+
77
+ When \`status\` is \`recommended\`, Scout has split the work into \`tasks\`, one
78
+ per model, each with up to five ranked \`models\`; cover every task. Each
79
+ model's \`cost\` names the \`endpointId\` and \`providerModelId\` to call.
80
+ Existing-only never broadens. For existing-first, if no existing candidate fits a
81
+ task, explain the gap and ask before a new conversation without \`endpointIds\`.
82
+ Compare quality evidence, reference cost/time and watch-outs. Prefer the cheapest
83
+ usable option the evidence supports, without claiming benchmarks prove
84
+ application accuracy. Use the project's actual SDK and protocol.
85
+
86
+ ## Boundaries
87
+
88
+ Ask before adding providers or credentials, spending, deploying or external
89
+ writes. Report recommendation, endpoint connectivity and application checks as
90
+ separate results, each only after it succeeds. Do not switch this coding agent's
91
+ own model.
92
+
93
+ If Scout fails or has no suitable candidate/evidence for the required deployment,
94
+ say so and pause the model decision; do not substitute a remembered recommendation
95
+ or SDK default. Continue only model-independent work. Local/browser models are not
96
+ exempt when the catalogue lacks coverage. If it reports that the device key is missing,
97
+ expired or revoked, run \`npx -y openmerit@latest login\` and then
98
+ \`npx -y openmerit@latest install\` again. Never ask the user to paste a key.
99
+ `;
100
+ export function scoutRule(client) {
101
+ if (client === 'claude-code')
102
+ return rule;
103
+ return rule.replace('load the `openmerit-scout` skill and consult', 'follow the Scout project policy below and consult')
104
+ .replaceAll('`scout_models`', '`mcp__openmerit__scout_models`')
105
+ .replace("Follow the skill's project access policy.", 'Follow the project access policy below.')
106
+ .replace('update --scope user', 'install --client pi --scope user')
107
+ .replace("rule is in the project's .claude/rules directory", "Pi installation is project-scoped");
108
+ }
109
+ export function scoutSkill(client) {
110
+ if (client === 'claude-code')
111
+ return skill;
112
+ return skill.replaceAll('`scout_models`', '`mcp__openmerit__scout_models`')
113
+ .replace('openmerit@latest login', 'openmerit@latest login --client pi')
114
+ .replace('openmerit@latest install`', 'openmerit@latest install --client pi`')
115
+ .replace('again. Never ask the user to paste a key.', 'again, using `--scope project` on both commands for a project-scoped installation. Never ask the user to paste a key.');
116
+ }
@@ -0,0 +1,119 @@
1
+ import type { ScoutClient } from './scout-credentials.ts';
2
+
3
+ export const rule = `# Application model decisions · OpenMerit Scout
4
+
5
+ Before choosing, recommending, adding, downloading, replacing or configuring
6
+ ANY application inference model, load the \`openmerit-scout\` skill and consult
7
+ \`scout_models\` on the \`openmerit\` MCP server before committing to a model.
8
+ This applies even when the user only asks you to build a feature, never mentions
9
+ models or Scout, or names a model themselves (assess it; do not silently replace it).
10
+
11
+ A pretrained model, local weights, browser inference, an SDK's default model,
12
+ embeddings, OCR, speech, image classification, detection and segmentation all
13
+ count as model choices, not implementation details. Identify this decision before
14
+ writing model-specific code, installing a model package or downloading weights.
15
+
16
+ Follow the skill's project access policy. If it is missing, ask and save it first.
17
+ Scout may answer with clarifying questions: relay them to the user and continue
18
+ the same Scout conversation with their answers before choosing.
19
+ If Scout is unavailable, fails or has no suitable evidence/candidate, disclose the
20
+ gap and pause the model decision; do not fall back to a remembered or SDK-default
21
+ model. You may continue work that does not commit to a model.
22
+
23
+ Do not consult Scout for unrelated edits, normal inference calls using an unchanged
24
+ approved model, or this coding agent's own model. Do not reselect approved models
25
+ unless the task introduces or changes a model decision.
26
+
27
+ When the user says "update openmerit", run
28
+ \`npx -y openmerit@latest update --scope user\` (use \`--scope project\` if this
29
+ rule is in the project's .claude/rules directory). Report the result, including
30
+ any conflict or manual-upgrade requirement. Do not delete edited files, bypass
31
+ permissions or rerun login automatically. A new session loads updated instructions.
32
+ `;
33
+
34
+ export const skill = `---
35
+ name: openmerit-scout
36
+ description: Consults OpenMerit Scout before choosing, adding, downloading, replacing or configuring any application inference model, including implicit choices while building features, pretrained browser/local models, SDK defaults, embeddings, OCR, speech, classification, detection, segmentation, LLMs and agents. Not for unrelated edits, ordinary inference calls or this coding agent's own model.
37
+ ---
38
+
39
+ # OpenMerit · Scout
40
+
41
+ Before introducing, recommending, replacing or configuring an application
42
+ inference model, call the \`scout_models\` tool on the \`openmerit\` MCP server.
43
+ This applies even when the user never mentions models or Scout. Downloading local
44
+ weights, using a pretrained browser model or accepting an SDK default is a model
45
+ decision: consult Scout before model-specific code, installs or downloads.
46
+ Preserve the user's explicit model choice; assess it rather than silently replacing
47
+ it. Leave unchanged, approved application selections in place.
48
+
49
+ ## Project policy
50
+
51
+ Read \`.openmerit/scout.json\` before searching. If it is absent, ask once whether this
52
+ project uses **existing-only** (only endpoints it can already reach) or
53
+ **existing-first** (prefer them, ask before searching the whole catalogue), and
54
+ which public catalogue endpoint IDs it can access. Save the answer:
55
+
56
+ \`\`\`sh
57
+ npx -y openmerit@latest project --policy existing-only --endpoint-id <id> ...
58
+ \`\`\`
59
+
60
+ Never infer access from a model name, SDK or environment-variable name. Never
61
+ record credentials, private URLs, prompts or customer data. An empty inventory
62
+ is not permission to search all models.
63
+
64
+ ## Searching
65
+
66
+ Call \`scout_models\` with a non-confidential task description as \`prompt\` and
67
+ \`endpointIds\` set to the saved inventory, including \`[]\` when empty. Send
68
+ only task requirements, never source files, secrets or real customer records.
69
+ If the MCP tool is unavailable, run
70
+ \`npx -y openmerit@latest scout "<task>" --json\`; it applies the saved inventory.
71
+
72
+ Scout is a conversation with the agent behind openmerit.ai/scout. When
73
+ \`status\` is \`needs_answers\`, fill in what the user or project already states,
74
+ show the user Scout's brief and remaining questions, and wait for their answers.
75
+ Then call again with the returned \`conversationId\` and \`brief\` set to the
76
+ rewritten components, or \`skip: true\` if the user wants Scout to assume. Never
77
+ answer Scout's questions with guesses. Send later refinements to the same
78
+ \`conversationId\`. A call with only a \`conversationId\` reads an interrupted turn.
79
+
80
+ When \`status\` is \`recommended\`, Scout has split the work into \`tasks\`, one
81
+ per model, each with up to five ranked \`models\`; cover every task. Each
82
+ model's \`cost\` names the \`endpointId\` and \`providerModelId\` to call.
83
+ Existing-only never broadens. For existing-first, if no existing candidate fits a
84
+ task, explain the gap and ask before a new conversation without \`endpointIds\`.
85
+ Compare quality evidence, reference cost/time and watch-outs. Prefer the cheapest
86
+ usable option the evidence supports, without claiming benchmarks prove
87
+ application accuracy. Use the project's actual SDK and protocol.
88
+
89
+ ## Boundaries
90
+
91
+ Ask before adding providers or credentials, spending, deploying or external
92
+ writes. Report recommendation, endpoint connectivity and application checks as
93
+ separate results, each only after it succeeds. Do not switch this coding agent's
94
+ own model.
95
+
96
+ If Scout fails or has no suitable candidate/evidence for the required deployment,
97
+ say so and pause the model decision; do not substitute a remembered recommendation
98
+ or SDK default. Continue only model-independent work. Local/browser models are not
99
+ exempt when the catalogue lacks coverage. If it reports that the device key is missing,
100
+ expired or revoked, run \`npx -y openmerit@latest login\` and then
101
+ \`npx -y openmerit@latest install\` again. Never ask the user to paste a key.
102
+ `;
103
+
104
+ export function scoutRule(client: ScoutClient): string {
105
+ if (client === 'claude-code') return rule;
106
+ return rule.replace('load the `openmerit-scout` skill and consult', 'follow the Scout project policy below and consult')
107
+ .replaceAll('`scout_models`', '`mcp__openmerit__scout_models`')
108
+ .replace("Follow the skill's project access policy.", 'Follow the project access policy below.')
109
+ .replace('update --scope user', 'install --client pi --scope user')
110
+ .replace("rule is in the project's .claude/rules directory", "Pi installation is project-scoped");
111
+ }
112
+
113
+ export function scoutSkill(client: ScoutClient): string {
114
+ if (client === 'claude-code') return skill;
115
+ return skill.replaceAll('`scout_models`', '`mcp__openmerit__scout_models`')
116
+ .replace('openmerit@latest login', 'openmerit@latest login --client pi')
117
+ .replace('openmerit@latest install`', 'openmerit@latest install --client pi`')
118
+ .replace('again. Never ask the user to paste a key.', 'again, using `--scope project` on both commands for a project-scoped installation. Never ask the user to paste a key.');
119
+ }
@@ -0,0 +1,44 @@
1
+ import type { ScoutScope } from './scout-credentials.ts';
2
+ export declare const piVersion = "1.5.0";
3
+ type RecordValue = Record<string, unknown>;
4
+ export declare function piPaths(root: string, scope: ScoutScope): {
5
+ skill: string;
6
+ rule: string;
7
+ connection: string;
8
+ record: string;
9
+ legacyRule: string;
10
+ mcpFile: string;
11
+ mcpScope: ScoutScope;
12
+ agentDir: string;
13
+ };
14
+ export declare function inspectPi(root: string, scope: ScoutScope): Promise<{
15
+ paths: {
16
+ skill: string;
17
+ rule: string;
18
+ connection: string;
19
+ record: string;
20
+ legacyRule: string;
21
+ mcpFile: string;
22
+ mcpScope: ScoutScope;
23
+ agentDir: string;
24
+ };
25
+ record: RecordValue;
26
+ owned: boolean;
27
+ current: string | null;
28
+ installedSkill: string | null;
29
+ installedRule: string | null;
30
+ serverOwned: boolean;
31
+ skillOwned: boolean;
32
+ ruleOwned: boolean;
33
+ updates: {
34
+ saved: null;
35
+ active: boolean;
36
+ conflicts: string[];
37
+ };
38
+ legacyRule: string;
39
+ shadowed: boolean;
40
+ }>;
41
+ export declare function piConflicts(state: Awaited<ReturnType<typeof inspectPi>>): string[];
42
+ export declare function configurePi(root: string, scope: ScoutScope, credentialsPath: string, ids: RecordValue): Promise<void>;
43
+ export declare function removePi(state: Awaited<ReturnType<typeof inspectPi>>): Promise<void>;
44
+ export {};
@@ -0,0 +1,84 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, mkdir, writeFile, rm } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { scoutSkill } from "./scout-instructions.js";
6
+ export const piVersion = '1.5.0';
7
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
8
+ const optional = async (path) => {
9
+ try {
10
+ return await readFile(path, 'utf8');
11
+ }
12
+ catch (error) {
13
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
14
+ return null;
15
+ throw error;
16
+ }
17
+ };
18
+ async function object(path) {
19
+ const value = JSON.parse(await optional(path) ?? '{}');
20
+ if (!value || typeof value !== 'object' || Array.isArray(value))
21
+ throw new Error(`Invalid Scout installation metadata at ${path}; nothing changed.`);
22
+ return value;
23
+ }
24
+ export function piPaths(root, scope) {
25
+ const agentDir = resolve(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), '.pi/agent'));
26
+ const base = scope === 'user' ? agentDir : join(root, '.pi');
27
+ return { skill: join(base, 'skills/openmerit-scout/SKILL.md'), rule: join(base, 'extensions/openmerit-scout.ts'),
28
+ connection: join(base, 'extensions/openmerit-scout.json'), record: join(base, 'openmerit-install.json'),
29
+ legacyRule: join(base, 'rules/openmerit.md'), mcpFile: join(base, 'mcp.json'), mcpScope: scope, agentDir };
30
+ }
31
+ export async function inspectPi(root, scope) {
32
+ const paths = piPaths(root, scope);
33
+ const otherPaths = piPaths(root, scope === 'user' ? 'project' : 'user');
34
+ const [record, connection, installedSkill, installedRule, mcp, otherMcp, other] = await Promise.all([
35
+ object(paths.record), optional(paths.connection), optional(paths.skill), optional(paths.rule), object(paths.mcpFile),
36
+ object(otherPaths.mcpFile), optional(otherPaths.rule),
37
+ ]);
38
+ const owned = record.version === 1 && record.client === 'pi' && record.scope === scope;
39
+ const matches = (value, field) => value === null || owned && [record[field], record[`pending${field[0].toUpperCase()}${field.slice(1)}`]].includes(hash(value));
40
+ return { paths, record, owned, current: connection, installedSkill, installedRule,
41
+ serverOwned: matches(connection, 'serverHash'), skillOwned: matches(installedSkill, 'skillHash'), ruleOwned: matches(installedRule, 'ruleHash'),
42
+ updates: { saved: null, active: false, conflicts: [] }, legacyRule: 'none',
43
+ shadowed: other !== null || [mcp, otherMcp].some(config => config.mcpServers && typeof config.mcpServers === 'object' && 'openmerit' in config.mcpServers), };
44
+ }
45
+ export function piConflicts(state) {
46
+ return [
47
+ ...(!state.serverOwned ? [`${state.paths.connection} was edited or is unowned.`] : []),
48
+ ...(!state.skillOwned ? [`${state.paths.skill} was edited or is unowned.`] : []),
49
+ ...(!state.ruleOwned ? [`${state.paths.rule} was edited or is unowned.`] : []),
50
+ ...(state.shadowed ? ['Another Pi Scout installation or an openmerit MCP entry shadows this installation. Resolve the duplicate before installing.'] : []),
51
+ ];
52
+ }
53
+ export async function configurePi(root, scope, credentialsPath, ids) {
54
+ const state = await inspectPi(root, scope);
55
+ const conflicts = piConflicts(state);
56
+ if (conflicts.length)
57
+ throw new Error(conflicts.join('\n'));
58
+ const extension = await readFile(new URL('../../../dist/pi/scout-extension.mjs', import.meta.url), 'utf8');
59
+ const connection = `${JSON.stringify({ credentialsPath }, null, 2)}\n`;
60
+ const skill = scoutSkill('pi');
61
+ const next = { version: 1, client: 'pi', scope, ...ids, serverHash: hash(connection), skillHash: hash(skill), ruleHash: hash(extension), installedAt: new Date().toISOString() };
62
+ const save = async (path, value) => {
63
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
64
+ await writeFile(path, typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
65
+ };
66
+ // Record intent before writing files, so interrupted installs are recoverable.
67
+ await save(state.paths.record, { ...state.record, version: 1, client: 'pi', scope,
68
+ pendingServerHash: next.serverHash, pendingSkillHash: next.skillHash, pendingRuleHash: next.ruleHash });
69
+ await save(state.paths.connection, connection);
70
+ await save(state.paths.skill, skill);
71
+ await save(state.paths.rule, extension);
72
+ await save(state.paths.record, next);
73
+ }
74
+ export async function removePi(state) {
75
+ if (state.current !== null && state.serverOwned)
76
+ await rm(state.paths.connection, { force: true });
77
+ if (state.installedRule !== null && state.ruleOwned)
78
+ await rm(state.paths.rule, { force: true });
79
+ if (state.installedSkill !== null && state.skillOwned)
80
+ await rm(state.paths.skill, { force: true });
81
+ // Keep ownership of edited files, so a future install does not adopt them.
82
+ if (state.serverOwned && state.ruleOwned && state.skillOwned)
83
+ await rm(state.paths.record, { force: true });
84
+ }
@@ -0,0 +1,76 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, mkdir, writeFile, rm } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import type { ScoutScope } from './scout-credentials.ts';
6
+ import { scoutSkill } from './scout-instructions.ts';
7
+
8
+ export const piVersion = '1.5.0';
9
+ type RecordValue = Record<string, unknown>;
10
+ const hash = (value: string) => createHash('sha256').update(value).digest('hex');
11
+ const optional = async (path: string): Promise<string | null> => {
12
+ try { return await readFile(path, 'utf8'); }
13
+ catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return null; throw error; }
14
+ };
15
+ async function object(path: string): Promise<RecordValue> {
16
+ const value: unknown = JSON.parse(await optional(path) ?? '{}');
17
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`Invalid Scout installation metadata at ${path}; nothing changed.`);
18
+ return value as RecordValue;
19
+ }
20
+ export function piPaths(root: string, scope: ScoutScope) {
21
+ const agentDir = resolve(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), '.pi/agent'));
22
+ const base = scope === 'user' ? agentDir : join(root, '.pi');
23
+ return { skill: join(base, 'skills/openmerit-scout/SKILL.md'), rule: join(base, 'extensions/openmerit-scout.ts'),
24
+ connection: join(base, 'extensions/openmerit-scout.json'), record: join(base, 'openmerit-install.json'),
25
+ legacyRule: join(base, 'rules/openmerit.md'), mcpFile: join(base, 'mcp.json'), mcpScope: scope, agentDir };
26
+ }
27
+ export async function inspectPi(root: string, scope: ScoutScope) {
28
+ const paths = piPaths(root, scope);
29
+ const otherPaths = piPaths(root, scope === 'user' ? 'project' : 'user');
30
+ const [record, connection, installedSkill, installedRule, mcp, otherMcp, other] = await Promise.all([
31
+ object(paths.record), optional(paths.connection), optional(paths.skill), optional(paths.rule), object(paths.mcpFile),
32
+ object(otherPaths.mcpFile), optional(otherPaths.rule),
33
+ ]);
34
+ const owned = record.version === 1 && record.client === 'pi' && record.scope === scope;
35
+ const matches = (value: string | null, field: string) => value === null || owned && [record[field], record[`pending${field[0]!.toUpperCase()}${field.slice(1)}`]].includes(hash(value));
36
+ return { paths, record, owned, current: connection, installedSkill, installedRule,
37
+ serverOwned: matches(connection, 'serverHash'), skillOwned: matches(installedSkill, 'skillHash'), ruleOwned: matches(installedRule, 'ruleHash'),
38
+ updates: { saved: null, active: false, conflicts: [] as string[] }, legacyRule: 'none',
39
+ shadowed: other !== null || [mcp, otherMcp].some(config => config.mcpServers && typeof config.mcpServers === 'object' && 'openmerit' in config.mcpServers),
40
+ };
41
+ }
42
+ export function piConflicts(state: Awaited<ReturnType<typeof inspectPi>>): string[] {
43
+ return [
44
+ ...(!state.serverOwned ? [`${state.paths.connection} was edited or is unowned.`] : []),
45
+ ...(!state.skillOwned ? [`${state.paths.skill} was edited or is unowned.`] : []),
46
+ ...(!state.ruleOwned ? [`${state.paths.rule} was edited or is unowned.`] : []),
47
+ ...(state.shadowed ? ['Another Pi Scout installation or an openmerit MCP entry shadows this installation. Resolve the duplicate before installing.'] : []),
48
+ ];
49
+ }
50
+ export async function configurePi(root: string, scope: ScoutScope, credentialsPath: string, ids: RecordValue) {
51
+ const state = await inspectPi(root, scope);
52
+ const conflicts = piConflicts(state);
53
+ if (conflicts.length) throw new Error(conflicts.join('\n'));
54
+ const extension = await readFile(new URL('../../../dist/pi/scout-extension.mjs', import.meta.url), 'utf8');
55
+ const connection = `${JSON.stringify({ credentialsPath }, null, 2)}\n`;
56
+ const skill = scoutSkill('pi');
57
+ const next = { version: 1, client: 'pi', scope, ...ids, serverHash: hash(connection), skillHash: hash(skill), ruleHash: hash(extension), installedAt: new Date().toISOString() };
58
+ const save = async (path: string, value: string | RecordValue) => {
59
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
60
+ await writeFile(path, typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
61
+ };
62
+ // Record intent before writing files, so interrupted installs are recoverable.
63
+ await save(state.paths.record, { ...state.record, version: 1, client: 'pi', scope,
64
+ pendingServerHash: next.serverHash, pendingSkillHash: next.skillHash, pendingRuleHash: next.ruleHash });
65
+ await save(state.paths.connection, connection);
66
+ await save(state.paths.skill, skill);
67
+ await save(state.paths.rule, extension);
68
+ await save(state.paths.record, next);
69
+ }
70
+ export async function removePi(state: Awaited<ReturnType<typeof inspectPi>>) {
71
+ if (state.current !== null && state.serverOwned) await rm(state.paths.connection, { force: true });
72
+ if (state.installedRule !== null && state.ruleOwned) await rm(state.paths.rule, { force: true });
73
+ if (state.installedSkill !== null && state.skillOwned) await rm(state.paths.skill, { force: true });
74
+ // Keep ownership of edited files, so a future install does not adopt them.
75
+ if (state.serverOwned && state.ruleOwned && state.skillOwned) await rm(state.paths.record, { force: true });
76
+ }
@@ -0,0 +1,77 @@
1
+ export declare const policyFile = ".openmerit/scout.json";
2
+ export declare const components: readonly ["input", "work", "output", "criteria", "constraints"];
3
+ export declare const help = "OpenMerit \u00B7 Scout\n\n openmerit scout \"<the work models need to do>\" [--all-endpoints] [--json]\n openmerit scout --conversation <id> [--brief <component>=<text> ...] [--skip] [\"<follow-up>\"] [--json]\n\nAsks Scout, the agent behind openmerit.ai/scout. Scout may first return a task\nbrief with clarifying questions: answer them with --brief (components: input,\nwork, output, criteria, constraints) in the same conversation, or --skip to let\nScout assume. It then splits the work into tasks and recommends up to five\nmodels for each. A turn usually takes one to three minutes.\n\nA new conversation is limited to the endpoint IDs in .openmerit/scout.json\n(set with openmerit project). --all-endpoints searches the whole catalogue and is\nrefused under the existing-only policy. Uses the device key that\n\"openmerit install\" saved for Claude Code or Pi, this project's first. Never include secrets, source files or customer records.\n";
4
+ export interface ScoutRequest {
5
+ prompt?: string;
6
+ conversationId?: string;
7
+ brief?: Partial<Record<typeof components[number], string>>;
8
+ skip?: boolean;
9
+ endpointIds?: string[];
10
+ }
11
+ export interface ScoutModel {
12
+ rank: number;
13
+ id: string;
14
+ name: string;
15
+ provider: string;
16
+ rationale: string;
17
+ watchOut: string | null;
18
+ quality: {
19
+ score: number;
20
+ evidence: Array<{
21
+ name: string;
22
+ rank: number;
23
+ of: number;
24
+ }>;
25
+ };
26
+ cost: {
27
+ usdPer1kTasks: number;
28
+ inputPerMillion: number;
29
+ outputPerMillion: number;
30
+ route: string;
31
+ endpointId: string;
32
+ providerModelId: string;
33
+ } | null;
34
+ latency?: {
35
+ seconds: number;
36
+ } | null;
37
+ recency?: {
38
+ released: string;
39
+ } | null;
40
+ }
41
+ type Priority = 'cost' | 'quality' | 'latency' | 'recency';
42
+ export interface ScoutResult {
43
+ conversationId: string;
44
+ status: 'needs_answers' | 'recommended' | 'working' | 'message' | 'error';
45
+ next?: string;
46
+ brief?: Record<string, {
47
+ text: string;
48
+ source: string;
49
+ }>;
50
+ questions?: Array<{
51
+ component: string;
52
+ question: string;
53
+ }>;
54
+ assumptions?: string[];
55
+ tasks?: Array<{
56
+ title: string;
57
+ work: string;
58
+ summary: string;
59
+ priority?: Priority;
60
+ models: ScoutModel[];
61
+ }>;
62
+ text?: string;
63
+ error?: string;
64
+ }
65
+ export declare function askScout(root: string, request: ScoutRequest, signal?: AbortSignal): Promise<ScoutResult>;
66
+ export declare function scoutTurn(root: string, request: Omit<ScoutRequest, 'endpointIds'> & {
67
+ allEndpoints?: boolean;
68
+ }, signal?: AbortSignal): Promise<ScoutResult>;
69
+ export declare function renderScout(result: ScoutResult): string;
70
+ export declare function main(args: string[], { root, print }?: {
71
+ root?: string | undefined;
72
+ print?: {
73
+ (...data: any[]): void;
74
+ (message?: any, ...optionalParams: any[]): void;
75
+ } | undefined;
76
+ }): Promise<number>;
77
+ export {};