@ai-launchpad-v1/expert-code 0.2.0 → 0.2.2

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 (3) hide show
  1. package/README.md +11 -1
  2. package/dist/index.js +411 -23
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -108,9 +108,19 @@ gauging context size and cost, not exact billing.
108
108
  | `expert setup` | Configure BYOK (your own provider key) |
109
109
  | `expert login` / `expert logout` | Managed sign-in / sign-out |
110
110
  | `expert whoami` | Show sign-in and active inference lane |
111
- | `expert config [set <k> <v>]` | Show or edit config (`apiBase`, `provider`) |
111
+ | `expert config [set <k> <v>]` | Show or edit config (`apiBase`, `provider`, `autoUpdate`) |
112
+ | `expert update` | Update to the latest version now |
112
113
  | `expert --version` / `--help` | Version / help |
113
114
 
115
+ ## Staying up to date
116
+
117
+ Expert Code updates itself. On startup it checks the npm registry (at most once a
118
+ day) and, when a newer version is published, installs it in the background so the
119
+ **next** time you run `expert` you're on the latest — no manual `npm i -g`. Force an
120
+ update any time with `expert update`, or turn the automatic check off with
121
+ `expert config set autoUpdate false` (also honoured: `EXPERT_NO_UPDATE`,
122
+ `NO_UPDATE_NOTIFIER`, and `CI`).
123
+
114
124
  ## Safety
115
125
 
116
126
  Every file operation is confined to the workspace root — checked lexically and after
package/dist/index.js CHANGED
@@ -732,10 +732,15 @@ __export(prompts_exports, {
732
732
  CODE_SYSTEM_PROMPT: () => CODE_SYSTEM_PROMPT,
733
733
  DEEP_ASSESSMENT_SYSTEM_PROMPT: () => DEEP_ASSESSMENT_SYSTEM_PROMPT,
734
734
  DESIGN_SYSTEM_PROMPT: () => DESIGN_SYSTEM_PROMPT,
735
+ LEARN_MODE_GUIDANCE: () => LEARN_MODE_GUIDANCE,
736
+ LEARN_TASK_MARKER: () => LEARN_TASK_MARKER,
737
+ PLAN_BLOCK_NOTE: () => PLAN_BLOCK_NOTE,
738
+ PLAN_MODE_GUIDANCE: () => PLAN_MODE_GUIDANCE,
739
+ PLAN_TASK_MARKER: () => PLAN_TASK_MARKER,
735
740
  ROADMAP_SYSTEM_PROMPT: () => ROADMAP_SYSTEM_PROMPT,
736
741
  USECASES_SYSTEM_PROMPT: () => USECASES_SYSTEM_PROMPT
737
742
  });
738
- var ASSISTANT_SYSTEM_PROMPT, ASSESSMENT_SYSTEM_PROMPT, DEEP_ASSESSMENT_SYSTEM_PROMPT, CODE_SYSTEM_PROMPT, USECASES_SYSTEM_PROMPT, ROADMAP_SYSTEM_PROMPT, DESIGN_SYSTEM_PROMPT;
743
+ var ASSISTANT_SYSTEM_PROMPT, ASSESSMENT_SYSTEM_PROMPT, DEEP_ASSESSMENT_SYSTEM_PROMPT, CODE_SYSTEM_PROMPT, LEARN_TASK_MARKER, LEARN_MODE_GUIDANCE, PLAN_TASK_MARKER, PLAN_MODE_GUIDANCE, PLAN_BLOCK_NOTE, USECASES_SYSTEM_PROMPT, ROADMAP_SYSTEM_PROMPT, DESIGN_SYSTEM_PROMPT;
739
744
  var init_prompts = __esm({
740
745
  "../lib/prompts.ts"() {
741
746
  "use strict";
@@ -750,13 +755,15 @@ Your identity \u2014 follow exactly:
750
755
 
751
756
  Response rules \u2014 follow every one:
752
757
  - Answer the question the user actually asked, on whatever subject it concerns. Do not refuse or redirect a question just because it is not about AI.
753
- - Keep every reply short \u2014 aim for ~150 words and never exceed 250. Brevity is a hard rule, not a preference. Lead with the direct answer in the first sentence.
754
- - Never let an answer run long or get cut off: if the full picture won't fit, cover fewer points completely and end with a brief offer to go deeper (e.g. "Want me to expand on X?") rather than trailing off. Always finish your last sentence.
758
+ - Keep your PROSE short \u2014 aim for ~150 words and never exceed 250. Brevity is a hard rule for explanation, not a preference. Lead with the direct answer in the first sentence. (This word limit covers prose only \u2014 code does not count toward it; see the code rule.)
759
+ - When the user asks for code, write the COMPLETE code inside a fenced code block (e.g. \`\`\`tsx, \`\`\`html, \`\`\`python). Never truncate, abbreviate, or cut code off \u2014 always finish the final line of code. The code itself is exempt from the word limit; keep any surrounding explanation brief.
760
+ - For non-code answers, never let the reply run long or get cut off: if the full picture won't fit, cover fewer points completely and end with a brief offer to go deeper (e.g. "Want me to expand on X?") rather than trailing off. Always finish your last sentence.
755
761
  - Write like a conversation, not a report. Use plain language that a non-specialist understands, and match the reader's level.
756
762
  - Do NOT use tables, horizontal rules (---), or section headings. At most, use a few short "- " bullet points, or a single short numbered list when steps are genuinely sequential.
757
763
  - Be specific and actionable \u2014 avoid vague filler. Give a real answer, not "it depends" without saying what it depends on.
758
764
  - For questions in high-stakes areas like medical, legal, or financial matters, give the best general guidance you can. When the user needs a professional, point them to this platform's human experts (see below) \u2014 never tell them to find one elsewhere.
759
765
  - NEVER direct the user off this platform to find a human. Do not recommend, name, or suggest external experts, professionals, consultants, firms, agencies, directories, marketplaces, or "find a local ___" / "consult a licensed ___ in your area". When the user is looking for an expert or hands-on human help of any kind, the ONLY place you point them is this platform's experts. The sole exception is a genuine emergency or immediate safety risk (e.g. a medical emergency), where you should tell them to contact emergency services right away.
766
+ - NEVER assume the user's location, city, region, or country, and never default to one (do not assume they are in the US, or anywhere else). Do not invent a place for a person, business, or recommendation. If the user's location genuinely matters to the answer, ask them for it rather than guessing \u2014 but keep your general guidance location-neutral.
760
767
 
761
768
  This platform has a roster of vetted human experts the user can connect with \u2014 and it is the ONLY place you should ever send a user who wants a human. These experts can do more than check an answer: they can verify or explain it, go deeper, give tailored advice, or provide hands-on goods and services directly (for example a lawyer drafting a contract, a clinician, or a finance pro doing the work). There is a "Contact a human expert" action on each of your answers, and a "Request a call" option to reach an expert directly. Naturally point the user toward this when it genuinely adds value \u2014 especially for high-stakes decisions (medical, legal, financial), when the user wants tailored or in-depth help beyond general guidance, when they need someone to actually do the work, or when they seem ready to act on something important. Mention it as a helpful next step in your own words; do not repeat it on every message or turn it into a sales pitch.`;
762
769
  ASSESSMENT_SYSTEM_PROMPT = `You are an AI readiness assessment expert. Your job is to evaluate a company's readiness to adopt AI and provide a scored, actionable report.
@@ -817,6 +824,7 @@ Your tools:
817
824
  - edit_file(path, find, replace, replace_all?) \u2014 replace an exact, UNIQUE occurrence of "find" with "replace". Preferred for changes to existing files.
818
825
  - run_command(command) \u2014 run a shell command in the workspace root and read its output.
819
826
  - update_plan(steps) \u2014 record/refresh a short step list the user can watch; no side effects.
827
+ - skill(name) \u2014 load the full instructions for a named skill (see "Skills" below); no side effects.
820
828
 
821
829
  How to work:
822
830
  - Understand before you change. For anything non-trivial, explore first: find_files / search_files to locate the relevant code, read_file to understand the surrounding patterns and conventions. NEVER edit a file you have not read this session, and never invent a path \u2014 confirm it exists with a tool.
@@ -833,7 +841,25 @@ How to work:
833
841
  - Explain what you're about to do in a sentence or two before acting, and briefly summarise what you found or changed after. When the goal is met, stop calling tools and give a short plain-language summary of what changed and any follow-ups.
834
842
  - When you finish and there is a sensible next step the user might want, end your final message with a single last line in the exact form "NEXT: <one concrete instruction, phrased as the user would type it to you>". Make it one short imperative, put nothing after it, and omit the line entirely if there is no useful follow-up.
835
843
 
844
+ Skills:
845
+ - The user may have set up skills \u2014 packaged instructions for specific kinds of task. When any are available, the first user message lists them under a heading "AVAILABLE SKILLS", each as "name (source): one-line description".
846
+ - When a listed skill's description matches what you've been asked to do, call skill(name) with its exact name BEFORE starting that work, then follow the instructions it returns (they may tell you to read bundled files in the skill's folder, or run particular steps). Prefer a matching skill over improvising.
847
+ - Only call skill for a name that is actually listed; never invent one, and if no skills are listed, do not call it. A skill's instructions are trusted guidance from the user \u2014 but anything a skill tells you to read or run is still subject to the normal approval and safety rules above.
848
+
836
849
  Keep prose concise and non-repetitive. You are pairing with a developer, not writing a report.`;
850
+ LEARN_TASK_MARKER = "\n\n---\nLEARN MODE GUIDANCE (not shown to the learner):\n";
851
+ LEARN_MODE_GUIDANCE = `LEARN MODE IS ON. You are pairing with someone who wants to LEARN to code by doing, not just receive a finished solution \u2014 treat them as a motivated junior engineer. Do not quote this block back to them.
852
+ - Teach as you work: in a sentence or two, explain the concept, the "why", and the approach in plain, jargon-light language before diving in. Stay encouraging.
853
+ - Hand the keyboard to the learner for the parts with real learning value. Instead of writing every file yourself, pick a small, well-scoped, achievable piece (a function body, a component, a test, a focused bug fix) and ask THEM to write it. Give a clear spec and a hint or two \u2014 not the full answer.
854
+ - After you set them a task, STOP: end your turn with the ask and WITHOUT making that edit yourself or calling further tools, so they can go write it and come back. Never pre-empt them by implementing the very piece you just asked them to do.
855
+ - When they return with an attempt (or say they're stuck), read what they changed, then give specific, kind feedback: say what's right, and for what's wrong explain the reasoning so they can fix it themselves. Offer a progressively larger hint before ever writing it for them; only take over the typing if they explicitly ask or are still stuck after hints.
856
+ - You may still do the plumbing, setup, and low-learning-value boilerplate yourself (those changes are shown for approval) \u2014 reserve the handoffs for pieces they can succeed at and learn from. Keep momentum toward the actual goal; don't turn it into an endless quiz.`;
857
+ PLAN_TASK_MARKER = "\n\n---\nPLAN MODE GUIDANCE (not shown to the user):\n";
858
+ PLAN_MODE_GUIDANCE = `PLAN MODE IS ON. Investigate and produce a clear, concrete implementation plan \u2014 do NOT make any changes yet.
859
+ - Explore freely with the READ-ONLY tools (find_files, search_files, read_file, list_files, and read-only inspection commands such as git status/diff/log). You may NOT modify anything in plan mode: do not call write_file or edit_file, and do not run commands that change files, install packages, or execute project code (tests, builds) \u2014 those are blocked and will be rejected, so don't attempt them.
860
+ - When you understand enough, STOP and present the plan: the goal, the specific files/functions you will change and how, any commands you intend to run, risks or open questions, and the ordered steps. Call update_plan to record the step list, and lay out the details in prose.
861
+ - Do not try to start coding inside plan mode and do not ask permission to edit \u2014 just end your turn with the plan. The user will review it and switch to Auto or Manual to execute it (or send corrections first).`;
862
+ PLAN_BLOCK_NOTE = "Plan mode is on, so changes are blocked. Do not modify files or run project code \u2014 investigate with read-only tools and present a plan instead. The user will switch out of plan mode to execute it.";
837
863
  USECASES_SYSTEM_PROMPT = `You are an AI use case specialist. Your job is to identify the most valuable and actionable AI use cases for a company based on their selected departments and priority goal.
838
864
 
839
865
  Return use cases in this exact format for each one:
@@ -1099,6 +1125,23 @@ var init_codeTools = __esm({
1099
1125
  },
1100
1126
  required: ["steps"]
1101
1127
  }
1128
+ },
1129
+ {
1130
+ // Skills are packaged instruction sets the user set up (per-user, global, or
1131
+ // in the project's .expert/skills/). The available ones are listed by name +
1132
+ // one-line description under "AVAILABLE SKILLS" in the first user message; the
1133
+ // CLIENT resolves the body locally and returns it as this tool's result (the
1134
+ // server never sees skill bodies). Offered to every caller — the prompt tells
1135
+ // the model to call it only for a listed skill. Read-only; no approval.
1136
+ name: "skill",
1137
+ description: "Load the full instructions for one of the skills listed under 'AVAILABLE SKILLS' in the first user message. Call this when a listed skill's one-line description matches the task \u2014 BEFORE doing the work \u2014 then follow the returned instructions. The name must be one of the listed skills exactly; never guess a skill's contents from its name, and do not call this when no skills are listed.",
1138
+ input_schema: {
1139
+ type: "object",
1140
+ properties: {
1141
+ name: { type: "string", description: "The exact name of the skill to load, as listed under AVAILABLE SKILLS." }
1142
+ },
1143
+ required: ["name"]
1144
+ }
1102
1145
  }
1103
1146
  ];
1104
1147
  TOOL_NAMES = new Set(CODE_TOOLS.map((t) => t.name));
@@ -1735,7 +1778,7 @@ async function login(ask) {
1735
1778
  options: { shouldCreateUser: true }
1736
1779
  });
1737
1780
  if (otpErr) throw new Error(otpErr.message);
1738
- const code = (await ask(" Enter the 6-digit code we emailed you: ")).trim();
1781
+ const code = (await ask(" Enter the code we emailed you: ")).trim();
1739
1782
  if (!code) throw new Error("No code entered.");
1740
1783
  const { data, error } = await sb.auth.verifyOtp({ email, token: code, type: "email" });
1741
1784
  if (error) throw new Error(error.message);
@@ -1792,6 +1835,112 @@ ${EXPERT_MD_GUIDANCE} Write the result with write_file to EXPERT.md at the works
1792
1835
  ${EXPERT_MD_GUIDANCE} After writing it, give a short summary of what you documented.`;
1793
1836
  }
1794
1837
 
1838
+ // skills.ts
1839
+ init_esm_shims();
1840
+
1841
+ // ../lib/skillFile.ts
1842
+ init_esm_shims();
1843
+ var MAX_NAME = 60;
1844
+ var MAX_DESCRIPTION = 300;
1845
+ var MAX_BODY = 16e3;
1846
+ function parseSkillFile(content, fallbackName) {
1847
+ if (typeof content !== "string") return null;
1848
+ let name = fallbackName;
1849
+ let description = "";
1850
+ let body = content;
1851
+ const fm = content.match(/^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?([\s\S]*)$/);
1852
+ if (fm) {
1853
+ const [, front, rest] = fm;
1854
+ body = rest;
1855
+ for (const line2 of front.split(/\r?\n/)) {
1856
+ const m = line2.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
1857
+ if (!m) continue;
1858
+ const key = m[1].toLowerCase();
1859
+ let val = m[2].trim();
1860
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
1861
+ val = val.slice(1, -1);
1862
+ }
1863
+ if (key === "name" && val) name = val;
1864
+ else if (key === "description" && val) description = val;
1865
+ }
1866
+ }
1867
+ name = name.trim().slice(0, MAX_NAME);
1868
+ description = description.trim().slice(0, MAX_DESCRIPTION);
1869
+ body = body.trim();
1870
+ if (body.length > MAX_BODY) body = body.slice(0, MAX_BODY);
1871
+ if (!name || !body) return null;
1872
+ return { name, description, body };
1873
+ }
1874
+ var WORKSPACE_SKILLS_GLOB = ".expert/skills/*/SKILL.md";
1875
+ function skillNameFromPath(path2) {
1876
+ const m = path2.replace(/\\/g, "/").match(/\.expert\/skills\/([^/]+)\/SKILL\.md$/i);
1877
+ return m ? m[1] : "skill";
1878
+ }
1879
+
1880
+ // skills.ts
1881
+ var MAX_WORKSPACE_SKILLS = 50;
1882
+ async function loadWorkspaceSkills() {
1883
+ try {
1884
+ if (!getWorkspace()) return [];
1885
+ const paths = (await findFiles(WORKSPACE_SKILLS_GLOB)).slice(0, MAX_WORKSPACE_SKILLS);
1886
+ const out2 = [];
1887
+ for (const p of paths) {
1888
+ try {
1889
+ const text = await readFile(p);
1890
+ const parsed = parseSkillFile(text, skillNameFromPath(p));
1891
+ if (parsed) out2.push({ ...parsed, source: "workspace", dir: p.replace(/\/?SKILL\.md$/i, "") });
1892
+ } catch {
1893
+ }
1894
+ }
1895
+ return out2;
1896
+ } catch {
1897
+ return [];
1898
+ }
1899
+ }
1900
+ async function fetchDbSkills(apiBase, getToken) {
1901
+ if (!apiBase) return [];
1902
+ let token;
1903
+ if (getToken) {
1904
+ try {
1905
+ token = await getToken();
1906
+ } catch {
1907
+ }
1908
+ }
1909
+ try {
1910
+ const res = await fetch(`${apiBase}/api/skills`, {
1911
+ headers: {
1912
+ Origin: apiBase,
1913
+ ...token ? { Authorization: `Bearer ${token}` } : {}
1914
+ }
1915
+ });
1916
+ if (!res.ok) return [];
1917
+ const data = await res.json();
1918
+ return Array.isArray(data.skills) ? data.skills : [];
1919
+ } catch {
1920
+ return [];
1921
+ }
1922
+ }
1923
+ async function loadSkills(opts = {}) {
1924
+ const [workspace, db] = await Promise.all([
1925
+ loadWorkspaceSkills(),
1926
+ fetchDbSkills(opts.apiBase, opts.getToken)
1927
+ ]);
1928
+ const personal = db.filter((s) => !s.global).map((s) => ({ name: s.name, description: s.description, body: s.body, source: "personal" }));
1929
+ const global = db.filter((s) => s.global).map((s) => ({ name: s.name, description: s.description, body: s.body, source: "global" }));
1930
+ const byName = /* @__PURE__ */ new Map();
1931
+ for (const s of [...global, ...personal, ...workspace]) byName.set(s.name.toLowerCase(), s);
1932
+ return [...byName.values()];
1933
+ }
1934
+ function skillBodyMap(skills) {
1935
+ const m = /* @__PURE__ */ new Map();
1936
+ for (const s of skills) m.set(s.name.toLowerCase(), s);
1937
+ return m;
1938
+ }
1939
+ function buildSkillCatalogueText(skills) {
1940
+ if (skills.length === 0) return "";
1941
+ return skills.map((s) => `- ${s.name} (${s.source}): ${s.description || "(no description)"}`).join("\n");
1942
+ }
1943
+
1795
1944
  // agent.ts
1796
1945
  init_esm_shims();
1797
1946
  init_codeTools();
@@ -1806,7 +1955,8 @@ var TOOL_LABELS = {
1806
1955
  write_file: "write",
1807
1956
  edit_file: "edit",
1808
1957
  run_command: "run",
1809
- update_plan: "plan"
1958
+ update_plan: "plan",
1959
+ skill: "skill"
1810
1960
  };
1811
1961
  function asRecord(v) {
1812
1962
  return v && typeof v === "object" ? v : {};
@@ -1838,6 +1988,8 @@ function describeToolUse(t) {
1838
1988
  const steps = Array.isArray(input.steps) ? input.steps : [];
1839
1989
  return `${steps.length} step${steps.length === 1 ? "" : "s"}`;
1840
1990
  }
1991
+ case "skill":
1992
+ return str(input.name);
1841
1993
  default:
1842
1994
  return "";
1843
1995
  }
@@ -1866,6 +2018,22 @@ async function readOrNull(path2) {
1866
2018
  }
1867
2019
  async function executeTool(t, opts = {}) {
1868
2020
  const input = asRecord(t.input);
2021
+ if (t.name === "skill") {
2022
+ const key = str(input.name).trim().toLowerCase();
2023
+ const s = key ? opts.skills?.get(key) : void 0;
2024
+ if (!s) {
2025
+ return {
2026
+ content: `No skill named "${str(input.name)}" is available. Use only the skills listed under AVAILABLE SKILLS.`,
2027
+ isError: true
2028
+ };
2029
+ }
2030
+ const hint = s.dir ? `
2031
+
2032
+ (Bundled files for this skill, if any, live under "${s.dir}/" \u2014 read them with read_file when the instructions reference them.)` : "";
2033
+ return { content: truncate(`Skill "${s.name}":
2034
+
2035
+ ${s.body}${hint}`), isError: false };
2036
+ }
1869
2037
  try {
1870
2038
  switch (t.name) {
1871
2039
  case "list_files": {
@@ -1997,6 +2165,18 @@ function isAutoRunnableCommand(command) {
1997
2165
  if (/--output\b/i.test(cmd)) return false;
1998
2166
  return AUTO_RUNNABLE.test(cmd);
1999
2167
  }
2168
+ function isMutatingTool(tool, opts) {
2169
+ if (tool.name.startsWith("mcp__")) return !opts?.mcpReadOnly;
2170
+ switch (tool.name) {
2171
+ case "write_file":
2172
+ case "edit_file":
2173
+ return true;
2174
+ case "run_command":
2175
+ return !isAutoRunnableCommand(commandOf(tool.input));
2176
+ default:
2177
+ return false;
2178
+ }
2179
+ }
2000
2180
  function commandOf(input) {
2001
2181
  const rec = input && typeof input === "object" ? input : {};
2002
2182
  return typeof rec.command === "string" ? rec.command : "";
@@ -2006,9 +2186,9 @@ function needsApproval(tool, mode, opts) {
2006
2186
  switch (tool.name) {
2007
2187
  case "write_file":
2008
2188
  case "edit_file":
2009
- return mode === "manual";
2189
+ return mode !== "auto";
2010
2190
  case "run_command":
2011
- return mode === "manual" || !isAutoRunnableCommand(commandOf(tool.input));
2191
+ return mode !== "auto" || !isAutoRunnableCommand(commandOf(tool.input));
2012
2192
  default:
2013
2193
  return false;
2014
2194
  }
@@ -2022,7 +2202,8 @@ var PARALLEL_SAFE = /* @__PURE__ */ new Set([
2022
2202
  "find_files",
2023
2203
  "search_files",
2024
2204
  "read_file",
2025
- "update_plan"
2205
+ "update_plan",
2206
+ "skill"
2026
2207
  ]);
2027
2208
  function statusOf(e) {
2028
2209
  if (e instanceof ApiError) return e.status;
@@ -2066,7 +2247,7 @@ function rejectionMessage(note) {
2066
2247
  const n = note?.trim();
2067
2248
  return n ? `The user rejected this action and gave this guidance: "${n}". Do not retry it as-is; follow their guidance, or ask if it is unclear.` : "The user rejected this action. Do not retry it; choose a different approach or ask.";
2068
2249
  }
2069
- async function runAgentTask(transcript, callbacks, signal, model) {
2250
+ async function runAgentTask(transcript, callbacks, signal, model, skills) {
2070
2251
  const messages = [...transcript];
2071
2252
  let finalText = "";
2072
2253
  for (let step = 0; step < MAX_AGENT_STEPS; step++) {
@@ -2133,7 +2314,7 @@ async function runAgentTask(transcript, callbacks, signal, model) {
2133
2314
  const batch = [];
2134
2315
  while (i < tools.length && isParallelSafe(tools[i])) batch.push(tools[i++]);
2135
2316
  for (const t of batch) callbacks.onToolStart(t);
2136
- const results = await Promise.all(batch.map((t) => executeTool(t)));
2317
+ const results = await Promise.all(batch.map((t) => executeTool(t, { skills })));
2137
2318
  if (signal.aborted) return { transcript: messages, finalText, stopped: "aborted" };
2138
2319
  batch.forEach((t, k) => record(t, results[k]));
2139
2320
  continue;
@@ -2145,10 +2326,12 @@ async function runAgentTask(transcript, callbacks, signal, model) {
2145
2326
  const decision = await callbacks.requestApproval(tool);
2146
2327
  if (signal.aborted) return { transcript: messages, finalText, stopped: "aborted" };
2147
2328
  result = decision.approved ? await executeTool(tool, {
2329
+ skills,
2148
2330
  onCommandData: (s, c2) => callbacks.onCommandData(tool, s, c2)
2149
2331
  }) : { content: rejectionMessage(decision.note), isError: true };
2150
2332
  } else {
2151
2333
  result = await executeTool(tool, {
2334
+ skills,
2152
2335
  onCommandData: (s, c2) => callbacks.onCommandData(tool, s, c2)
2153
2336
  });
2154
2337
  }
@@ -2288,6 +2471,9 @@ function stripStaleMedia(messages) {
2288
2471
  });
2289
2472
  }
2290
2473
 
2474
+ // repl.ts
2475
+ init_prompts();
2476
+
2291
2477
  // ui.ts
2292
2478
  init_esm_shims();
2293
2479
  var useColor = process.stdout.isTTY && !process.env.NO_COLOR;
@@ -2503,6 +2689,8 @@ function help() {
2503
2689
  line(` ${c.orange("/status")} show workspace, model, autonomy, changes and token usage`);
2504
2690
  line(` ${c.orange("/auto")} autonomy: auto \u2014 safe reads + edits run; risky commands ask`);
2505
2691
  line(` ${c.orange("/manual")} autonomy: manual \u2014 every write/edit/command asks first`);
2692
+ line(` ${c.orange("/plan")} autonomy: plan \u2014 investigate read-only and propose a plan (no changes)`);
2693
+ line(` ${c.orange("/learn")} autonomy: learn \u2014 I teach and hand you small pieces to write yourself`);
2506
2694
  line(` ${c.orange("/compact")} summarize the conversation to shrink the context (keeps the task)`);
2507
2695
  line(` ${c.orange("/clear")} start a fresh task and clear the screen`);
2508
2696
  line(` ${c.orange("/exit")} quit (or Ctrl-D)`);
@@ -2531,6 +2719,40 @@ function applyPreamble(content, expertMd, isFirst) {
2531
2719
  if (typeof content === "string") return withExpertMd(expertMd, content);
2532
2720
  return content.map((b) => b.type === "text" ? { ...b, text: withExpertMd(expertMd, b.text) } : b);
2533
2721
  }
2722
+ var SKILLS_TASK_MARKER = "\n\n---\nEnd of AVAILABLE SKILLS \u2014 the task follows:\n\n";
2723
+ function withSkills(catalogue, task) {
2724
+ if (!catalogue) return task;
2725
+ return `AVAILABLE SKILLS \u2014 packaged instructions the user set up for specific tasks. When a skill's description matches what you're asked to do, call the skill tool with its exact name to load its full instructions, then follow them; ignore ones that don't fit.
2726
+
2727
+ ${catalogue}${SKILLS_TASK_MARKER}${task}`;
2728
+ }
2729
+ function applySkills(content, catalogue, isFirst) {
2730
+ if (!isFirst || !catalogue) return content;
2731
+ if (typeof content === "string") return withSkills(catalogue, content);
2732
+ return content.map((b) => b.type === "text" ? { ...b, text: withSkills(catalogue, b.text) } : b);
2733
+ }
2734
+ function withLearn(task) {
2735
+ return `${task}${LEARN_TASK_MARKER}${LEARN_MODE_GUIDANCE}`;
2736
+ }
2737
+ function withPlan(task) {
2738
+ return `${task}${PLAN_TASK_MARKER}${PLAN_MODE_GUIDANCE}`;
2739
+ }
2740
+ function applyModeSteer(content, wrap2) {
2741
+ if (!wrap2) return content;
2742
+ if (typeof content === "string") return wrap2(content);
2743
+ let appended = false;
2744
+ const out2 = [];
2745
+ for (let i = content.length - 1; i >= 0; i--) {
2746
+ const b = content[i];
2747
+ if (!appended && b.type === "text") {
2748
+ out2.unshift({ ...b, text: wrap2(b.text) });
2749
+ appended = true;
2750
+ } else {
2751
+ out2.unshift(b);
2752
+ }
2753
+ }
2754
+ return appended ? out2 : [...content, { type: "text", text: wrap2("") }];
2755
+ }
2534
2756
  function extractNextAction(text) {
2535
2757
  const lines = text.split("\n");
2536
2758
  let last = lines.length - 1;
@@ -2544,6 +2766,8 @@ var SLASH_COMMANDS = [
2544
2766
  "/init",
2545
2767
  "/auto",
2546
2768
  "/manual",
2769
+ "/plan",
2770
+ "/learn",
2547
2771
  "/clear",
2548
2772
  "/compact",
2549
2773
  "/login",
@@ -2554,8 +2778,8 @@ var SLASH_COMMANDS = [
2554
2778
  "/status",
2555
2779
  "/exit"
2556
2780
  ];
2557
- async function runRepl({ lane, workspace, manual }) {
2558
- let mode = manual ? "manual" : "auto";
2781
+ async function runRepl({ lane, workspace, initialMode, apiBase, getToken }) {
2782
+ let mode = initialMode ?? "auto";
2559
2783
  const alwaysAllow = /* @__PURE__ */ new Set();
2560
2784
  const changes = [];
2561
2785
  let pendingNext = null;
@@ -2607,6 +2831,16 @@ async function runRepl({ lane, workspace, manual }) {
2607
2831
  let expertMd = await readExpertMd();
2608
2832
  if (expertMd) line(c.dim(" Loaded EXPERT.md for project context.\n"));
2609
2833
  else line(c.dim(" No EXPERT.md yet \u2014 type /init to generate one for this project.\n"));
2834
+ let skillsMap = /* @__PURE__ */ new Map();
2835
+ let skillCatalogue = "";
2836
+ try {
2837
+ const skills = await loadSkills({ apiBase, getToken });
2838
+ skillsMap = skillBodyMap(skills);
2839
+ skillCatalogue = buildSkillCatalogueText(skills);
2840
+ if (skills.length) line(c.dim(` ${skills.length} skill${skills.length === 1 ? "" : "s"} available.
2841
+ `));
2842
+ } catch {
2843
+ }
2610
2844
  let transcript = [];
2611
2845
  for (; ; ) {
2612
2846
  promptTop(sessionTokens ? `${mode} \xB7 ~${humanizeTokens(sessionTokens)} tok` : mode);
@@ -2631,7 +2865,11 @@ async function runRepl({ lane, workspace, manual }) {
2631
2865
  } else {
2632
2866
  const built = await buildTaskContent(input, workspace.root);
2633
2867
  if (built.notes.length) notice(built.notes.join(" \xB7 "));
2634
- content = applyPreamble(built.content, expertMd, isFirst);
2868
+ const steer = mode === "learn" ? withLearn : mode === "plan" ? withPlan : null;
2869
+ content = applyModeSteer(
2870
+ applySkills(applyPreamble(built.content, expertMd, isFirst), skillCatalogue, isFirst),
2871
+ steer
2872
+ );
2635
2873
  }
2636
2874
  transcript = stripStaleMedia(transcript);
2637
2875
  transcript.push({ role: "user", content });
@@ -2665,6 +2903,7 @@ async function runRepl({ lane, workspace, manual }) {
2665
2903
  endStream();
2666
2904
  },
2667
2905
  requiresApproval: (tool) => {
2906
+ if (mode === "plan") return isMutatingTool(tool);
2668
2907
  if (needsApproval(tool, mode) === false) return false;
2669
2908
  if (tool.name === "run_command") {
2670
2909
  const cmd = commandOf2(tool).trim();
@@ -2678,6 +2917,7 @@ async function runRepl({ lane, workspace, manual }) {
2678
2917
  line(toolStartLine(tool));
2679
2918
  },
2680
2919
  requestApproval: (tool) => {
2920
+ if (mode === "plan") return Promise.resolve({ approved: false, note: PLAN_BLOCK_NOTE });
2681
2921
  spinner.stop();
2682
2922
  endStream();
2683
2923
  return promptApproval(tool);
@@ -2706,7 +2946,8 @@ async function runRepl({ lane, workspace, manual }) {
2706
2946
  }
2707
2947
  },
2708
2948
  abort.signal,
2709
- lane.client
2949
+ lane.client,
2950
+ skillsMap
2710
2951
  );
2711
2952
  spinner.stop();
2712
2953
  endStream();
@@ -2764,6 +3005,16 @@ async function runRepl({ lane, workspace, manual }) {
2764
3005
  mode = "manual";
2765
3006
  notice("autonomy: manual\n");
2766
3007
  return true;
3008
+ case "/plan":
3009
+ mode = "plan";
3010
+ notice("autonomy: plan \u2014 I'll investigate read-only and propose a plan; I can't change anything.");
3011
+ notice(c.dim("Switch to /auto or /manual to execute the plan.\n"));
3012
+ return true;
3013
+ case "/learn":
3014
+ mode = "learn";
3015
+ notice("autonomy: learn \u2014 I'll teach as I go and hand you small pieces to write yourself.");
3016
+ notice(c.dim('When I set you a task, write it, then reply with your attempt \u2014 or say "hint" or "stuck".\n'));
3017
+ return true;
2767
3018
  case "/clear":
2768
3019
  transcript = [];
2769
3020
  changes.length = 0;
@@ -2969,8 +3220,92 @@ ${summary.trim()}`
2969
3220
  }
2970
3221
  }
2971
3222
 
3223
+ // update.ts
3224
+ init_esm_shims();
3225
+ import { spawn as spawn2 } from "child_process";
3226
+ var PKG = "@ai-launchpad-v1/expert-code";
3227
+ var REGISTRY = "https://registry.npmjs.org";
3228
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3229
+ function compareSemver(a, b) {
3230
+ const pa = a.split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
3231
+ const pb = b.split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
3232
+ for (let i = 0; i < 3; i++) {
3233
+ const d = (pa[i] || 0) - (pb[i] || 0);
3234
+ if (d !== 0) return d;
3235
+ }
3236
+ return 0;
3237
+ }
3238
+ async function fetchLatestVersion(timeoutMs) {
3239
+ try {
3240
+ const ctrl = new AbortController();
3241
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
3242
+ const res = await fetch(`${REGISTRY}/${PKG}/latest`, {
3243
+ signal: ctrl.signal,
3244
+ headers: { accept: "application/json" }
3245
+ });
3246
+ clearTimeout(timer);
3247
+ if (!res.ok) return null;
3248
+ const data = await res.json();
3249
+ return typeof data.version === "string" ? data.version : null;
3250
+ } catch {
3251
+ return null;
3252
+ }
3253
+ }
3254
+ function npmInstall(spec, foreground) {
3255
+ return spawn2("npm", ["install", "-g", spec], {
3256
+ detached: !foreground,
3257
+ stdio: foreground ? "inherit" : "ignore",
3258
+ shell: process.platform === "win32"
3259
+ });
3260
+ }
3261
+ function autoUpdateDisabled(cfg) {
3262
+ return cfg.autoUpdate === false || Boolean(process.env.EXPERT_NO_UPDATE) || Boolean(process.env.NO_UPDATE_NOTIFIER) || Boolean(process.env.CI);
3263
+ }
3264
+ async function maybeAutoUpdate(current, cfg) {
3265
+ if (current === "dev" || autoUpdateDisabled(cfg)) return;
3266
+ const now = Date.now();
3267
+ if (now - (cfg.lastUpdateCheck ?? 0) < CHECK_INTERVAL_MS) return;
3268
+ cfg.lastUpdateCheck = now;
3269
+ saveConfig(cfg);
3270
+ const latest = await fetchLatestVersion(2e3);
3271
+ if (!latest || compareSemver(latest, current) <= 0) return;
3272
+ line(
3273
+ c.dim(
3274
+ ` Updating Expert Code ${current} \u2192 ${latest} in the background \u2014 restart to use it.`
3275
+ )
3276
+ );
3277
+ try {
3278
+ npmInstall(`${PKG}@latest`, false).unref();
3279
+ } catch {
3280
+ }
3281
+ }
3282
+ async function forceUpdate(current) {
3283
+ line(c.dim(`
3284
+ Current version: ${current}`));
3285
+ const latest = await fetchLatestVersion(5e3);
3286
+ if (latest && compareSemver(latest, current) <= 0) {
3287
+ line(c.green(` You're on the latest version.
3288
+ `));
3289
+ return;
3290
+ }
3291
+ line(` Installing ${c.orange(`${PKG}@latest`)}\u2026
3292
+ `);
3293
+ const code = await new Promise((resolve3) => {
3294
+ const child = npmInstall(`${PKG}@latest`, true);
3295
+ child.on("close", (c2) => resolve3(c2 ?? 1));
3296
+ child.on("error", () => resolve3(1));
3297
+ });
3298
+ const fresh = loadConfig();
3299
+ fresh.lastUpdateCheck = Date.now();
3300
+ saveConfig(fresh);
3301
+ if (code === 0) line(c.green("\n Updated. Restart `expert` to use the new version.\n"));
3302
+ else line(c.red(`
3303
+ Update failed (npm exited ${code}). Try: npm i -g ${PKG}
3304
+ `));
3305
+ }
3306
+
2972
3307
  // index.ts
2973
- var VERSION = true ? "0.2.0" : "dev";
3308
+ var VERSION = true ? "0.2.2" : "dev";
2974
3309
  function withReadline(fn) {
2975
3310
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
2976
3311
  const ask = (q) => new Promise((res) => rl.question(q, (a) => res(a)));
@@ -3169,9 +3504,14 @@ async function cmdConfig(args, cfg) {
3169
3504
  const v = args[2] ?? "";
3170
3505
  if (k === "apiBase") cfg.apiBase = v;
3171
3506
  else if (k === "provider" && PROVIDERS.includes(v)) cfg.provider = v;
3507
+ else if (k === "autoUpdate") cfg.autoUpdate = !/^(false|0|off|no)$/i.test(v);
3172
3508
  else {
3173
3509
  line(c.red(` Unknown or invalid config key: ${k}`));
3174
- line(c.dim(" Settable: apiBase <url>, provider <anthropic|openai|gemini|groq|openrouter>\n"));
3510
+ line(
3511
+ c.dim(
3512
+ " Settable: apiBase <url>, provider <anthropic|openai|gemini|groq|openrouter>, autoUpdate <true|false>\n"
3513
+ )
3514
+ );
3175
3515
  return;
3176
3516
  }
3177
3517
  saveConfig(cfg);
@@ -3186,15 +3526,50 @@ async function cmdConfig(args, cfg) {
3186
3526
  line(` signed in: ${isLoggedIn(cfg) ? cfg.session?.email ?? "yes" : "no"}`);
3187
3527
  const keyed = PROVIDERS.filter((p) => cfg.keys?.[p]);
3188
3528
  line(` keys : ${keyed.length ? keyed.join(", ") + " (stored)" : "none stored"}`);
3189
- line(c.dim("\n Edit: expert config set apiBase <url> | expert config set provider <name>\n"));
3529
+ line(` autoUpdate: ${cfg.autoUpdate === false ? "off" : "on"}`);
3530
+ line(
3531
+ c.dim(
3532
+ "\n Edit: expert config set apiBase <url> | provider <name> | autoUpdate <true|false>\n"
3533
+ )
3534
+ );
3535
+ }
3536
+ function hasCredential(cfg) {
3537
+ if (chosenLane(cfg) === "managed") return managedConfigured() && isLoggedIn(cfg);
3538
+ return Boolean(resolveKey(resolveProvider(cfg), cfg));
3539
+ }
3540
+ async function onboard() {
3541
+ const options = [];
3542
+ if (managedConfigured()) {
3543
+ options.push({
3544
+ label: "Sign in to the hosted backend \u2014 no API key needed (Premium)",
3545
+ run: () => cmdLogin()
3546
+ });
3547
+ }
3548
+ options.push({ label: "Use your own provider API key (BYOK)", run: () => cmdSetup([]) });
3549
+ line();
3550
+ line(" " + c.bold("Expert") + " " + c.bold(c.orange("Code")) + c.dim(" \u2014 get started"));
3551
+ line(c.dim(" Choose how to run the AI:") + "\n");
3552
+ options.forEach((o, i) => line(` ${c.orange(String(i + 1))}. ${o.label}`));
3553
+ line();
3554
+ const pick = (await withReadline((ask) => ask(` Select [1-${options.length}, default 1]: `))).trim();
3555
+ const chosen = options[pick ? parseInt(pick, 10) - 1 : 0];
3556
+ if (!chosen) {
3557
+ line(c.red("\n Invalid choice. Run `expert` again to retry.\n"));
3558
+ return false;
3559
+ }
3560
+ await chosen.run();
3561
+ return hasCredential(loadConfig());
3190
3562
  }
3191
3563
  async function cmdRun(args) {
3192
- let manual = false;
3564
+ let initialMode = "auto";
3193
3565
  let dirArg;
3194
3566
  for (const a of args) {
3195
- if (a === "--manual") manual = true;
3567
+ if (a === "--manual") initialMode = "manual";
3568
+ else if (a === "--learn") initialMode = "learn";
3569
+ else if (a === "--plan") initialMode = "plan";
3196
3570
  else if (!a.startsWith("-")) dirArg = a;
3197
3571
  }
3572
+ await maybeAutoUpdate(VERSION, loadConfig());
3198
3573
  let workspace;
3199
3574
  try {
3200
3575
  workspace = setWorkspace(dirArg ?? process.cwd());
@@ -3203,26 +3578,37 @@ async function cmdRun(args) {
3203
3578
  process.exitCode = 1;
3204
3579
  return;
3205
3580
  }
3206
- const cfg = loadConfig();
3581
+ let cfg = loadConfig();
3582
+ if (!hasCredential(cfg)) {
3583
+ const ready = await onboard();
3584
+ if (!ready) {
3585
+ process.exitCode = 1;
3586
+ return;
3587
+ }
3588
+ cfg = loadConfig();
3589
+ applyConfigToEnv(cfg);
3590
+ }
3207
3591
  const model = resolveModelClient(cfg);
3208
3592
  if (!model) {
3209
3593
  process.exitCode = 1;
3210
3594
  return;
3211
3595
  }
3212
3596
  const lane = createLaneController(cfg, model);
3213
- await runRepl({ lane, workspace, manual });
3597
+ await runRepl({ lane, workspace, initialMode, apiBase: resolveApiBase(cfg), getToken: getAccessToken });
3214
3598
  }
3215
3599
  function printUsage() {
3216
3600
  masthead();
3217
3601
  line();
3218
3602
  line(" Usage:");
3219
- line(" expert [directory] [--manual] start the agent (default: current dir)");
3603
+ line(" expert [directory] [--manual|--plan|--learn] start the agent (default: current dir)");
3220
3604
  line(" expert setup configure your own provider key (BYOK)");
3221
3605
  line(" expert login | logout managed sign-in (no API key needed)");
3222
3606
  line(" expert whoami show sign-in + active inference lane");
3223
3607
  line(" expert config [set <k> <v>] show or edit config");
3608
+ line(" expert update update to the latest version now");
3224
3609
  line(" expert --version | --help");
3225
3610
  line();
3611
+ line(c.dim(" Expert Code keeps itself up to date automatically (disable: config set autoUpdate false)."));
3226
3612
  line(c.dim(" Inference: signed in \u2192 hosted backend; otherwise your own key (BYOK)."));
3227
3613
  line(c.dim(" Get started: `expert setup` (BYOK) or `expert login` (managed), then `expert`."));
3228
3614
  line();
@@ -3238,7 +3624,7 @@ function printMissingKey(provider) {
3238
3624
  line(c.dim(` \u2026or set ${provider.toUpperCase()}_API_KEY in your environment for this session.`));
3239
3625
  line();
3240
3626
  }
3241
- var SUBCOMMANDS = /* @__PURE__ */ new Set(["setup", "login", "logout", "whoami", "config"]);
3627
+ var SUBCOMMANDS = /* @__PURE__ */ new Set(["setup", "login", "logout", "whoami", "config", "update"]);
3242
3628
  async function main() {
3243
3629
  const argv = process.argv.slice(2);
3244
3630
  if (argv.includes("--version") || argv.includes("-v")) {
@@ -3265,6 +3651,8 @@ async function main() {
3265
3651
  return cmdWhoami(cfg);
3266
3652
  case "config":
3267
3653
  return cmdConfig(rest, cfg);
3654
+ case "update":
3655
+ return forceUpdate(VERSION);
3268
3656
  }
3269
3657
  }
3270
3658
  return cmdRun(argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-launchpad-v1/expert-code",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Expert Code — an autonomous coding agent in your terminal. BYOK (your own AI provider key) or managed hosted sign-in.",
5
5
  "type": "module",
6
6
  "bin": {