dsh-vscode-mode 0.29.2 → 0.31.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.
- package/README.md +120 -11
- package/lib/client.js +178 -51
- package/lib/client.js.map +1 -1
- package/lib/index.js +4860 -1576
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/dsh-vscodemode-html-plan/LICENSE +202 -0
- package/skills/dsh-vscodemode-html-plan/SKILL.md +147 -0
- package/skills/dsh-vscodemode-html-plan/examples/scheduled-send.html +298 -0
- package/skills/dsh-vscodemode-html-plan/references/blocks.md +227 -0
- package/skills/dsh-vscodemode-html-plan/references/subagent-brief.md +17 -0
- package/skills/dsh-vscodemode-html-plan/references/upstream-SKILL.md +174 -0
- package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.css +564 -0
- package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.js +1299 -0
- package/skills/dsh-vscodemode-html-plan/runtime/pack.mjs +300 -0
- package/src/ai/llmTask.ts +178 -0
- package/src/ai/llmTypes.ts +6 -0
- package/src/ai/svnCommitMsg.ts +107 -0
- package/src/ai/svnTriage.ts +34 -85
- package/src/client/aiCommit.ts +57 -0
- package/src/client/compatSummary.ts +15 -0
- package/src/client/editorFlush.ts +55 -0
- package/src/client/featurePrefs.ts +63 -0
- package/src/client/htmlPlan/HtmlPlanPanel.ts +261 -0
- package/src/client/htmlPlan/planActions.ts +347 -0
- package/src/client/htmlPlan/planPage.ts +333 -0
- package/src/client/htmlPreview.ts +218 -0
- package/src/client/index.ts +43 -0
- package/src/client/monaco/loader.ts +71 -9
- package/src/client/monaco/templateLanguages.ts +300 -0
- package/src/client/officialSidebar.ts +16 -4
- package/src/client/openPathRouter.ts +7 -0
- package/src/client/planState.ts +8 -2
- package/src/client/refCopy.ts +70 -0
- package/src/client/refIntake.ts +215 -0
- package/src/client/sidebar/menuItems.ts +11 -0
- package/src/client/sidebar/panels/FileExplorer.ts +11 -0
- package/src/client/sidebar/panels/SearchPanel.ts +214 -4
- package/src/client/sidebar/panels/SvnPanel.ts +17 -0
- package/src/client/sidebar/types.ts +2 -0
- package/src/client/styles/editor.css +112 -0
- package/src/client/svnActions.ts +7 -0
- package/src/client/svnCommit.ts +109 -0
- package/src/client/svnNotice.ts +1 -1
- package/src/client/svnStatus.ts +5 -2
- package/src/client/ui/DiffLauncher.ts +3 -1
- package/src/client/ui/EditorView.ts +221 -14
- package/src/client/ui/McpSettings.ts +108 -1
- package/src/client/ui/SvnAiPlanDialog.ts +24 -4
- package/src/client/ui/SvnCommitDialog.ts +458 -0
- package/src/client/ui/commandCatalog.ts +11 -0
- package/src/client/ui/svnCommitModel.ts +204 -0
- package/src/client/univer/UniverCacheSettings.ts +75 -0
- package/src/client/univer/UniverHost.ts +177 -0
- package/src/client/univer/api.ts +30 -0
- package/src/client/univer/routing.ts +32 -0
- package/src/client/univer/store.ts +111 -0
- package/src/fileOpenSettings.ts +118 -6
- package/src/htmlPlanCommand.ts +176 -0
- package/src/index.ts +4 -0
- package/src/paths.ts +5 -0
- package/src/refPointer.ts +193 -0
- package/src/rpc.ts +51 -0
- package/src/search/replacePlan.ts +144 -0
- package/src/search/replaceRun.ts +289 -0
- package/src/shared/keybindings.ts +11 -0
- package/src/shared/refSyntax.ts +106 -0
- package/src/shared/rpc.ts +28 -4
- package/src/shared/snippets.ts +17 -0
- package/src/shared/svn.ts +191 -10
- package/src/shared/svnActions.ts +16 -0
- package/src/shared/univer.ts +90 -0
- package/src/svn.ts +205 -47
- package/src/svnCommit.ts +348 -0
- package/src/svnCore.ts +254 -0
- package/src/svnToolJson.ts +73 -0
- package/src/svnTools.ts +566 -0
- package/src/univerBridge.ts +83 -0
- package/src/univerCache.ts +205 -0
- package/src/univerRpc.ts +144 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// pack.mjs — lint an artifact and inline everything into one portable .html
|
|
3
|
+
// node pack.mjs page.html [-o out.html] [--root dir] [--lint-only] [--quiet] [--artifact]
|
|
4
|
+
// Lint runs the same parsers the browser uses (from htmlplan.js), fills <doc-code src>
|
|
5
|
+
// from disk, inlines htmlplan.css/js and local images, and refuses to write on errors.
|
|
6
|
+
import { readFileSync, writeFileSync, existsSync, statSync, realpathSync } from 'node:fs';
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { resolve, dirname, extname, basename, relative, sep } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { createRequire } from 'node:module';
|
|
11
|
+
|
|
12
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
const require = createRequire(import.meta.url);
|
|
14
|
+
require('./htmlplan.js'); // registers globalThis.HtmlPlan (no DOM → parsers only)
|
|
15
|
+
const NW = globalThis.HtmlPlan;
|
|
16
|
+
|
|
17
|
+
const argv = process.argv.slice(2);
|
|
18
|
+
const input = argv.find((a) => !a.startsWith('-') && (argv.indexOf(a) === 0 || !['-o', '--root', '--out'].includes(argv[argv.indexOf(a) - 1])));
|
|
19
|
+
if (!input) { console.error('usage: node pack.mjs page.html [-o out.html] [--root dir] [--lint-only]'); process.exit(2); }
|
|
20
|
+
const opt = (n, d) => { const i = argv.findIndex((a) => a === n); return i >= 0 ? argv[i + 1] : d; };
|
|
21
|
+
const lintOnly = argv.includes('--lint-only'); const quiet = argv.includes('--quiet');
|
|
22
|
+
const inPath = resolve(input); const baseDir = dirname(inPath);
|
|
23
|
+
const roots = argv.flatMap((a, i) => a === '--root' ? [resolve(argv[i + 1].replace(/^~(?=\/)/, process.env.HOME))] : []); if (!roots.length) roots.push(baseDir); const root = roots[0];
|
|
24
|
+
const outPath = resolve(opt('-o', opt('--out', inPath.replace(/(\.src)?\.html?$/, '') + (inPath.includes('.src.') ? '.html' : '.packed.html'))));
|
|
25
|
+
|
|
26
|
+
let html = readFileSync(inPath, 'utf8');
|
|
27
|
+
const errors = [], warns = [], info = [];
|
|
28
|
+
const err = (m) => errors.push(m), warn = (m) => warns.push(m);
|
|
29
|
+
const lineOf = (idx) => html.slice(0, idx).split('\n').length;
|
|
30
|
+
const attrs = (s) => { const o = {}; s.replace(/([\w:.-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g, (m, k, a, b, c) => { o[k.toLowerCase()] = a ?? b ?? c ?? ''; return ''; }); return o; };
|
|
31
|
+
const unent = (s) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
|
|
32
|
+
const blockSrc = (inner) => { const m = inner.match(/<script\s+type=["']?text\/(?:plain|source)["']?\s*>([\s\S]*?)<\/script>/i); return NW.util.dedent(m ? m[1] : unent(inner.replace(/<doc-pin[\s\S]*?<\/doc-pin>|<template[\s\S]*?<\/template>|<[^>]+>/g, ''))); };
|
|
33
|
+
// Everything pack reads ends up inside a page that may be published, so reads are fenced: a file must really live (symlinks resolved)
|
|
34
|
+
// under a --root, the page's own folder, or the runtime's folder, and must not be a well-known secret file. Anything else is an error.
|
|
35
|
+
const real = (p) => { try { return realpathSync(p); } catch { return null; } };
|
|
36
|
+
const FENCE = [...new Set([...roots, baseDir, here])].map(real).filter(Boolean);
|
|
37
|
+
const inside = (f) => FENCE.some((d) => f === d || f.startsWith(d.endsWith(sep) ? d : d + sep));
|
|
38
|
+
const SECRET_NAME = new RegExp([
|
|
39
|
+
String.raw`(^|[\\/])\.(git|ssh|aws|azure|gnupg|kube|docker|password-store)([\\/]|$)`, // whole folders
|
|
40
|
+
String.raw`(^|[\\/])(\.env(\.[^\\/]*)?|\.netrc|\.npmrc|\.yarnrc(\.yml)?|\.pypirc|\.pgpass|\.my\.cnf|\.git-credentials|\.htpasswd)$`,
|
|
41
|
+
String.raw`(^|[\\/])(id_(rsa|dsa|ecdsa|ed25519)[^\\/]*|credentials[^\\/]*|secrets?(\.[^\\/]*)?|[^\\/]*_history|[^\\/]*\.local\.json)$`,
|
|
42
|
+
String.raw`\.(pem|key|p12|pfx|keystore|jks|tfvars|tfstate(\.backup)?|sqlite3?|db|kdbx|ovpn)$`,
|
|
43
|
+
].join('|'), 'i');
|
|
44
|
+
const SECRET_TEXT = /sk-ant-|sk-[A-Za-z0-9]{32,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,}|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.|(?:password|passwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token)["']?\s*[:=]\s*["'][^"'\s$<{]{12,}["']/i;
|
|
45
|
+
const reads = new Set(); // every file whose text ends up in the page
|
|
46
|
+
const refused = new Set();
|
|
47
|
+
const findFile = (p) => { for (const cand of [...roots.map((r) => resolve(r, p)), resolve(baseDir, p)]) { if (!existsSync(cand) || !statSync(cand).isFile()) continue; const f = real(cand);
|
|
48
|
+
if (!f || !inside(f)) { if (!refused.has(p)) { refused.add(p); err(`"${p}" is outside --root and the page's folder — not reading it. Pass --root <dir> for the checkout it lives in`); } continue; }
|
|
49
|
+
if (SECRET_NAME.test(f)) { if (!refused.has(p)) { refused.add(p); err(`"${p}" looks like a secrets file — not reading it`); } continue; }
|
|
50
|
+
return f; } return null; };
|
|
51
|
+
/** read a file at a git ref: tries `git show ref:path` in each --root that is a git checkout */
|
|
52
|
+
// Only two plumbing commands are ever run: `rev-parse` and `cat-file blob`. Neither touches the work tree, so no filter, hook, fsmonitor,
|
|
53
|
+
// pager, diff or credential program named in a repo's config can be started. (`status`, `diff` and `show` can start one, so they are not used.)
|
|
54
|
+
const git = (r, cmd, ...args) => { if (cmd !== 'rev-parse' && cmd !== 'cat-file') throw new Error('git ' + cmd + ' is not allowed'); return execFileSync('git', ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-C', r, cmd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64e6, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0', GIT_PAGER: 'cat' } }); };
|
|
55
|
+
/** short sha of the --root checkout a file sits in (+wt when the file has uncommitted changes); '' when it is not under a root or not in git */
|
|
56
|
+
const stamp = (f, wt) => { for (const r of roots) { const rr = real(r); if (!rr || !(f === rr || f.startsWith(rr + sep))) continue; try { const top = git(rr, 'rev-parse', '--short', 'HEAD').trim(); let same = true; if (wt) { try { same = git(rr, 'cat-file', 'blob', `HEAD:${relative(rr, f).split(sep).join('/')}`) === readFileSync(f, 'utf8'); } catch { same = false; } } return top + (same ? '' : '+wt'); } catch {} } return ''; };
|
|
57
|
+
const REF_OK = /^[A-Za-z0-9][\w.\/^~@{}-]*$/;
|
|
58
|
+
const gitShow = (ref, p) => { if (!REF_OK.test(ref) || /(^|\/)\.\.(\/|$)/.test(p) || p.startsWith('/') || p.startsWith('-') || SECRET_NAME.test(p)) { if (!refused.has(ref + ':' + p)) { refused.add(ref + ':' + p); err(`ref="${ref}" with "${p}" — not a plain git ref and a path inside the repo; not running git`); } return null; }
|
|
59
|
+
for (const r of roots) { try { return { text: git(r, 'cat-file', 'blob', `${ref}:${p}`), where: `${r}@${ref}` }; } catch {} } return null; };
|
|
60
|
+
const wc = (t) => String(t || '').trim().split(/\s+/).filter(Boolean).length;
|
|
61
|
+
const stripTags = (t) => t.replace(/<[^>]+>/g, ' ');
|
|
62
|
+
|
|
63
|
+
/* ── document-level checks ── */
|
|
64
|
+
if (!/<title>[^<]+<\/title>/i.test(html)) err('missing <title> — it names the artifact in tabs and share sheets');
|
|
65
|
+
if (!/<h1[\s>]/i.test(html)) warn('no <h1> — the response header uses it');
|
|
66
|
+
if (!/<meta[^>]+charset/i.test(html)) warn('missing <meta charset="utf-8">');
|
|
67
|
+
if (!/htmlplan\.css/.test(html) && !/<style[^>]*data-htmlplan/.test(html)) err('htmlplan.css is not linked — add <link rel="stylesheet" href="…/htmlplan.css">');
|
|
68
|
+
if (!/htmlplan\.js/.test(html) && !/<script[^>]*data-htmlplan/.test(html)) err('htmlplan.js is not included — add <script src="…/htmlplan.js" defer></script>');
|
|
69
|
+
const KNOWN = new Set(['doc-code', 'doc-pin', 'doc-flow', 'doc-seq', 'doc-schema', 'doc-tree', 'doc-calls', 'doc-machine', 'doc-mock', 'doc-shot', 'doc-quote', 'doc-ask', 'doc-note', 'doc-draft', 'doc-plan', 'doc-claim', 'doc-changes']);
|
|
70
|
+
for (const m of html.matchAll(/<(doc-[a-z]+)\b/g)) if (!KNOWN.has(m[1])) err(`line ${lineOf(m.index)}: unknown element <${m[1]}> — known: ${[...KNOWN].join(' ')}`);
|
|
71
|
+
const ids = {}; for (const m of html.matchAll(/\sid=["']([^"']+)["']/g)) { if (ids[m[1]]) err(`duplicate id="${m[1]}" (lines ${ids[m[1]]} and ${lineOf(m.index)})`); ids[m[1]] = lineOf(m.index); }
|
|
72
|
+
for (const m of html.matchAll(/href=["']#([^"']+)["']/g)) if (!ids[m[1]] && !/^s\d+/.test(m[1])) warn(`line ${lineOf(m.index)}: href="#${m[1]}" points at no id`);
|
|
73
|
+
|
|
74
|
+
{ const t = html.match(/<div class="tldr">([\s\S]*?)<\/div>/i); if (t && wc(stripTags(t[1])) > 50) warn(`.tldr is ${wc(stripTags(t[1]))} words — ≤ 40: what changes, and what you need from the reader`); }
|
|
75
|
+
{ const ti = (html.match(/<title>([^<]*)<\/title>/i) || [])[1] || '', h1 = stripTags((html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i) || [])[1] || ''); const nums = (x) => (x.match(/\d[\d,.]*/g) || []).join(' '); if (ti && h1 && nums(ti) && nums(h1) && nums(ti) !== nums(h1)) warn(`<title> "${ti.trim()}" and <h1> "${h1.trim()}" disagree on a number — the title is what the response is filed under`); }
|
|
76
|
+
|
|
77
|
+
/* ── per-block checks (and <doc-code src> fill) ── */
|
|
78
|
+
const names = new Set(); const quoteSeen = new Map(); let lastAskEnd = -1;
|
|
79
|
+
html = html.replace(/<(doc-(?!plan\b|claim\b)[a-z]+)\b([^>]*)>([\s\S]*?)<\/\1>/g, (whole, tag, rawAttrs, inner, idx) => {
|
|
80
|
+
const a = attrs(rawAttrs); const at = `line ${lineOf(idx)} <${tag}${a.id ? '#' + a.id : ''}>`;
|
|
81
|
+
try {
|
|
82
|
+
for (const k of ['caption', 'label', 'title']) if (/[<>]/.test(a[k] || '')) err(`${at}: ${k}="…" contains < or > — use < / > (or ‹ ›) inside attributes`);
|
|
83
|
+
if (/^doc-(flow|seq|schema|tree|calls|machine)$/.test(tag) && !/<script\s+type=["']?text\/(plain|source)/i.test(inner)) { const bare = inner.replace(/<template[\s\S]*?<\/template>|<doc-pin[\s\S]*?<\/doc-pin>/g, ''); const mm = bare.match(/<(?!!--)[^\s>]*/); if (mm) err(`${at}: source contains "${mm[0]}" — the browser will eat it as a tag. Wrap the block's text in <script type="text/plain">…</script> (then < > and <-> are safe)`); }
|
|
84
|
+
if (tag === 'doc-flow') { const m = NW.parseFlow(blockSrc(inner)); m.errors.forEach((e) => err(`${at}: ${e}`)); const n = m.order.length; if (!n) err(`${at}: no nodes`); if (n > 16) warn(`${at}: ${n} nodes — diagrams past ~12 stop being readable; split it or cut nodes`); Object.values(m.nodes).forEach((nd) => nd.label.split(/\s+/).forEach((w) => { if (w.length > 24) warn(`${at}: node "${nd.id}" has a ${w.length}-char word ("${w.slice(0, 20)}…") — it will force wide boxes; shorten or add a space`); })); if (!a.caption) warn(`${at}: no caption="" — say what the reader should notice`);
|
|
85
|
+
Object.values(m.nodes).forEach((nd) => { if ((nd.sub || '').length > 48) warn(`${at}: node "${nd.id}" sublabel is ${nd.sub.length} chars — it wraps to two lines max (~24 each); move the rest to indented detail`); });
|
|
86
|
+
m.edges.forEach((e) => { if ((e.label || '').length > 44) warn(`${at}: edge ${e.from}->${e.to} label is ${e.label.length} chars (two lines of ~22 max) — shorten or explain in the caption`); });
|
|
87
|
+
if (m.edges.some((e) => e.dash) && !a.dashed) warn(`${at}: uses --> but no dashed="…" — the legend will say "async / optional"; set dashed="what dashed means here"`);
|
|
88
|
+
const cols = Math.max(0, ...m.grid.map((r) => r.length)); if (cols >= 4) warn(`${at}: ${cols}-column grid — on a phone this scales to ~50% and pans; ≤3 columns (tall not wide) reads without zooming`);
|
|
89
|
+
else { const L = NW.layoutFlow(m); const scale = Math.min(1, 348 / L.W); if (scale < 0.72) { const widest = Object.values(m.nodes).flatMap((nd) => [...(nd.lines || []), ...(nd.subLines || [])]).sort((x, y) => y.length - x.length)[0] || ''; warn(`${at}: ≈${L.W}px wide → ${Math.round(scale * 100)}% on a phone. Node width is set by the longest label line, here "${widest}" (${widest.length}ch) — shorten it / move to indented detail, or drop a column`); } } }
|
|
90
|
+
else if (tag === 'doc-seq') { const m = NW.parseSeq(blockSrc(inner)); m.errors.forEach((e) => err(`${at}: ${e}`)); if (!a.caption) warn(`${at}: no caption="" — say what the reader should notice`); if (m.actors.length >= 5) warn(`${at}: ${m.actors.length} participants — a phone shows ~3 lanes without panning; split at a --- divider or fold a minor participant into a note`); if (!m.steps.length) err(`${at}: no messages`);
|
|
91
|
+
m.steps.forEach((st) => { if (st.kind === 'msg' && (st.text || '').length > 60) warn(`${at}: message "${st.text.slice(0, 30)}…" is ${st.text.length} chars — arrows carry a call, not a sentence; move detail to a note or prose`); });
|
|
92
|
+
m.actors.forEach((ac) => { if (ac.label.length > 28) warn(`${at}: participant "${ac.label}" is long — ≤18 chars keeps lanes narrow`); });
|
|
93
|
+
{ const longestA = Math.max(...m.actors.map((ac) => Math.min(ac.label.length, ac.label.length > 18 ? Math.ceil(ac.label.length / 2) + 2 : 99))); const COL = Math.min(240, Math.max(112, Math.ceil(longestA * 7.4 + 44))); const W = 48 + m.actors.length * COL; const scale = Math.min(1, 348 / W); if (scale < 0.7 && m.actors.length < 5) warn(`${at}: ${m.actors.length} lanes × ${COL}px ≈ ${W}px → ${Math.round(scale * 100)}% on a phone — shorter participant names (longest sets every lane) or one fewer lane`);
|
|
94
|
+
const once = m.actors.filter((ac) => m.steps.filter((st) => st.kind === 'msg' && (st.from === ac.id || st.to === ac.id)).length === 1); if (m.actors.length >= 4 && once.length) warn(`${at}: ${once.map((x) => x.label).join(', ')} appear${once.length === 1 ? 's' : ''} in exactly one message — fold into a "note over" and drop the lane`); } }
|
|
95
|
+
else if (tag === 'doc-schema' && !(a.lang || a.src)) { warn(`${at}: no lang= — write the schema as text in the language that states it best (lang="ts", "sql", "proto"…); the field-table form is kept only for old pages`); const m = NW.parseSchema(blockSrc(inner)); m.errors.forEach((e) => err(`${at}: ${e}`)); if (!a.caption) warn(`${at}: no caption=""`); if (!m.entities.length) err(`${at}: no entities`); m.entities.forEach((e) => { if (!e.fields.length) warn(`${at}: entity ${e.name} has no fields (indent fields under it)`); }); }
|
|
96
|
+
else if (tag === 'doc-calls') { const m = NW.parseCalls(blockSrc(inner)); m.errors.forEach((e) => err(`${at}: ${e}`)); const n = m.nodes.length; if (n > 60) warn(`${at}: ${n} rows — past ~40 the tree stops being scannable; split by entrypoint or use compact`); if (!m.nodes.some((x) => x.mark !== ' ')) warn(`${at}: no + − ~ rows — a call tree with no diff is a doc-tree of functions; mark what changes`); if (!a.caption) warn(`${at}: no caption="" — say what the reader should notice`);
|
|
97
|
+
const noLoc = m.nodes.filter((x) => x.mark !== ' ' && !x.gap && !x.loc).length; if (noLoc > 2) warn(`${at}: ${noLoc} changed calls have no file — end the line with @ path/file.ts:line so the files list can be derived and the row can open its code`);
|
|
98
|
+
for (const t of inner.matchAll(/<template\s+for=["']([^"']+)["']/g)) { if (!m.find(t[1])) err(`${at}: <template for="${t[1]}"> matches no call — use the call's symbol (the **bold** name, the <Component>, or the function before the parenthesis) or n<index>`); }
|
|
99
|
+
// context excerpts: for every row with @ file:line that resolves on disk (or via ref= + git show), embed ±CTX lines so clicking the row shows the code
|
|
100
|
+
const CTX = +(a.context || 6); const have = new Set([...inner.matchAll(/data-excerpt=["']([^"']+)["']/g)].map((x) => x[1]));
|
|
101
|
+
let added = 0, missing = 0, extra = '';
|
|
102
|
+
const seen = new Set();
|
|
103
|
+
for (const nd of m.nodes) { if (!nd.file || !nd.line || nd.gap) continue; const key = `${nd.file}:${nd.line}`; if (have.has(key) || seen.has(key)) continue; seen.add(key);
|
|
104
|
+
let text = null, sha = ''; const g = a.ref ? gitShow(a.ref, nd.file) : null; if (g) { text = g.text; sha = a.ref; } else { const f = findFile(nd.file); if (f) { text = readFileSync(f, 'utf8'); sha = stamp(f, false); } }
|
|
105
|
+
if (text == null) { missing++; continue; }
|
|
106
|
+
if (SECRET_TEXT.test(text)) { warn(`${at}: ${nd.file} looks like it holds a secret somewhere — no excerpt from it`); continue; }
|
|
107
|
+
const L = text.split('\n'); const ln = +String(nd.line).split('-')[0]; if (ln < 1 || ln > L.length) { warn(`${at}: ${key} — file has ${L.length} lines`); continue; }
|
|
108
|
+
|
|
109
|
+
const s0 = Math.max(1, ln - CTX), s1 = Math.min(L.length, ln + CTX); const slice = L.slice(s0 - 1, s1).join('\n').replace(/<\/script/gi, '<\\/script');
|
|
110
|
+
if (SECRET_TEXT.test(slice)) { warn(`${at}: ${key} looks like it holds a secret — no excerpt`); continue; } reads.add(nd.file);
|
|
111
|
+
extra += `\n<script type="text/plain" data-excerpt="${key}" data-start="${s0}"${sha ? ` data-sha="${sha}"` : ''}>\n${slice}\n</script>`; added++; }
|
|
112
|
+
if (added) info.push(`doc-calls${a.id ? '#' + a.id : ''}: embedded ${added} code excerpt${added > 1 ? 's' : ''} (click a row → its code)`);
|
|
113
|
+
if (missing && !added) warn(`${at}: ${missing} rows point at files not found under ${roots.map((r) => relative(process.cwd(), r) || '.').join(', ')} — pass --root <checkout> (and ref="<sha>" for a merged PR) so rows can open their code`);
|
|
114
|
+
else if (missing) warn(`${at}: ${missing} rows point at files not found — those rows will not open code`);
|
|
115
|
+
if (extra) return `<${tag}${rawAttrs}>${inner}${extra}</${tag}>`; }
|
|
116
|
+
else if (tag === 'doc-machine') { const m = NW.parseMachine(blockSrc(inner)); m.errors.forEach((e) => err(`${at}: ${e}`)); if (!m.order.length) err(`${at}: no states`);
|
|
117
|
+
if (m.order.length > 10) warn(`${at}: ${m.order.length} states — past ~8 the diagram needs panning; split by concern`);
|
|
118
|
+
if (!m.grid.length && !('blocks' in a) && m.events.some((e) => m.events.some((o) => o !== e && o.to === e.to && o.from !== e.from)) && m.order.length > 4) warn(`${at}: ${m.order.length} states with arrows that meet — add a grid (| a | b | rows) so labels do not overlap`);
|
|
119
|
+
Object.values(m.states).forEach((st) => { const b = st.bind; (b.shows || []).forEach((sel) => { const id = sel.replace(/^#/, ''); if (!ids[id] && !new RegExp(`id=["']${id}["']`).test(html)) err(`${at}: state ${st.id} shows "${sel}" — no element with that id`); });
|
|
120
|
+
[].concat(b.code || []).forEach((spec) => { const [f, l] = spec.split(':'); if (!l || !/^\d+$/.test(l)) err(`${at}: state ${st.id} code "${spec}" should be file:line`); else if (!new RegExp(`<doc-code[^>]*(file|title|id)=["'][^"']*${f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`).test(html)) warn(`${at}: state ${st.id} code "${spec}" — no <doc-code file=…${f}> on the page`); });
|
|
121
|
+
(b.set || []).forEach((kv) => { const k = kv.split('=')[0]; if (!new RegExp(`data-field=["']${k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`).test(html)) warn(`${at}: state ${st.id} set "${k}" — nothing on the page has data-field="${k}"`); });
|
|
122
|
+
if (b.node != null && !/<doc-flow/.test(html)) warn(`${at}: state ${st.id} binds node "${b.node}" but there is no <doc-flow>`);
|
|
123
|
+
if (b.seq != null && !/<doc-seq/.test(html)) warn(`${at}: state ${st.id} binds seq ${b.seq} but there is no <doc-seq>`); });
|
|
124
|
+
const stateEls = [...html.matchAll(/data-state=["']([^"']+)["']/g)].map((x) => x[1]).filter((v) => !/^[\w-]+$/.test(v) || true); stateEls.forEach((v) => v.split(/[\s,]+/).forEach((id) => { if (id && !m.states[id]) warn(`${at}: something has data-state="${id}" but the machine has no state "${id}"`); }));
|
|
125
|
+
const mname = a.name || m.name; if (mname) names.add(mname); [...html.matchAll(/data-play=["']([^"']+)["']/g)].forEach((x) => { const [mn, tn] = x[1].split(/[.:\/]/); if ((mn === mname || !tn) && !m.traces[tn || mn]) err(`${at}: data-play="${x[1]}" — machine has no trace "${tn || mn}" (traces: ${Object.keys(m.traces).join(', ') || 'none'})`); });
|
|
126
|
+
if (!a.caption) warn(`${at}: no caption="" — say what the reader should try`); }
|
|
127
|
+
else if (tag === 'doc-tree') { const m = NW.parseTree(blockSrc(inner)); if (!m.rows.length) err(`${at}: empty tree`); const longN = m.rows.filter((r) => r.note.length > 60); if (longN.length) warn(`${at}: ${longN.length} comment(s) over 60 chars (${longN.slice(0, 3).map((r) => r.name).join(', ')}…) — tree comments are one short clause; they truncate on phones. Explain below the tree`); m.rows.forEach((r) => { if (/\s[+~-]\s/.test(r.name)) warn(`${at}: row "${r.name.slice(0, 30)}" seems to hold several entries — one path per line`); }); }
|
|
128
|
+
else if (tag === 'doc-code' || tag === 'doc-schema') {
|
|
129
|
+
const hasScript = /<script\s+type=["']?text\/(plain|source)/i.test(inner);
|
|
130
|
+
if (a.src && !hasScript) {
|
|
131
|
+
let text, where;
|
|
132
|
+
let sha = '';
|
|
133
|
+
const g = a.ref ? gitShow(a.ref, a.src) : null;
|
|
134
|
+
if (g) { text = g.text; where = g.where; sha = a.ref; }
|
|
135
|
+
else { if (a.ref) { const f0 = findFile(a.src); if (!f0) { err(`${at}: src="${a.src}" ref="${a.ref}" — git show failed in ${roots.map((r) => relative(process.cwd(), r) || '.').join(', ')} and no plain file by that path either (is --root a checkout with that ref, or a snapshot dir containing the file?)`); return whole; } info.push(`${a.src}: no git ref ${a.ref} under the roots — using the plain file (assuming it is a snapshot at that ref)`); sha = a.ref; }
|
|
136
|
+
const all = roots.map((r) => resolve(r, a.src)).filter((c) => existsSync(c)); if (all.length > 1) warn(`${at}: src="${a.src}" exists under ${all.length} roots (${all.map((x) => relative(process.cwd(), x)).join(', ')}) — using the first; reorder --root or make the path more specific`);
|
|
137
|
+
const f = findFile(a.src); if (!f) { err(`${at}: src="${a.src}" not found (looked under ${roots.concat([baseDir]).map((r) => relative(process.cwd(), r) || '.').join(', ')})`); return whole; } text = readFileSync(f, 'utf8'); where = relative(process.cwd(), f); if (!roots.some((r) => f.startsWith(r))) warn(`${at}: src="${a.src}" resolved OUTSIDE --root, at ${where} — check it's the file you mean`);
|
|
138
|
+
if (!sha) sha = stamp(f, true); }
|
|
139
|
+
if (SECRET_TEXT.test(text)) { err(`${at}: ${a.src} looks like it holds a secret somewhere in the file — not packaging any of it`); return whole; }
|
|
140
|
+
const total = text.split('\n').length; let start = 1;
|
|
141
|
+
if (a.lines) { const mm = a.lines.match(/^(\d+)(?:-(\d+))?$/); if (!mm) err(`${at}: lines="${a.lines}" should look like 40-72`); else { start = +mm[1]; const end = +(mm[2] || mm[1]); /* lines="40" is that one line */ if (end > total || start < 1 || start > end) err(`${at}: lines="${a.lines}" but ${a.src} has ${total} lines at ${where} — is --root (or ref=) at the commit you're citing?`); text = text.split('\n').slice(start - 1, end).join('\n'); } }
|
|
142
|
+
if (SECRET_TEXT.test(text)) { err(`${at}: ${a.src} looks like it holds a secret — not packaging it`); return whole; } reads.add(a.src);
|
|
143
|
+
const nl = text.split('\n').length; if (nl > 120) warn(`${at}: ${nl} lines of code — readers skim past long listings; slice with lines="a-b"`); else if (nl > 40 && !('collapsed' in a)) warn(`${at}: ${nl}-line slice — over ~40 lines either trim to the part that carries the point or add collapsed`);
|
|
144
|
+
const extra = (a.file ? '' : ` file="${a.src}"`) + (a.start || !a.lines ? '' : ` start="${start}"`) + (sha && !a.sha ? ` sha="${String(sha).slice(0, 12)}"` : '');
|
|
145
|
+
info.push(`filled <${tag} src="${a.src}"${a.lines ? ` lines=${a.lines}` : ''}> from ${where}`);
|
|
146
|
+
return `<${tag}${rawAttrs}${extra}><script type="text/plain">${text.replace(/<\/script/gi, '<\\/script')}</script>${inner}</${tag}>`;
|
|
147
|
+
}
|
|
148
|
+
if (!hasScript && /<(?!\/?doc-pin\b)[a-z]/i.test(inner)) err(`${at}: code contains "<" but isn't wrapped — put the source inside <script type="text/plain">…</script>`);
|
|
149
|
+
if (!hasScript && !inner.trim() && !a.src) err(`${at}: empty`);
|
|
150
|
+
const n = blockSrc(inner).split('\n').length; if (n > 120) warn(`${at}: ${n} lines — slice to the part that carries the point`); else if (n > 40 && !('collapsed' in a) && hasScript) warn(`${at}: ${n}-line block — over ~40 lines trim or add collapsed`);
|
|
151
|
+
if ('collapsed' in a && !/<doc-pin/.test(inner) && !a.caption) warn(`${at}: collapsed, no pins, no caption — if nothing in it is worth pointing at, cite file:lines inline instead`);
|
|
152
|
+
if (a.file && / · |, /.test(a.file)) warn(`${at}: file="${a.file}" names two files — one block per file`);
|
|
153
|
+
if (a.file && !a.lines && !a.start && !a.src && !('diff' in a) && n > 6) warn(`${at}: file= without lines=/start= — cite the range, or start="1" if this really is the whole file, or drop file= for a sketch`);
|
|
154
|
+
if (('diff' in a || /^(diff|patch)$/.test(a.lang || '')) && hasScript) { const body = blockSrc(inner);
|
|
155
|
+
if (tag === 'doc-code' && !/^@@ .*[-+]\d/m.test(body) && !a.start && !a.lines) warn(`${at}: diff without a real "@@ -a,b +c,d @@" header (or start=) — gutter will be unnumbered; paste the hunk header from gh pr diff`);
|
|
156
|
+
let hdr = null, cntNew = 0, cntOld = 0, hl = 0; const check = () => { if (hdr && ((hdr.d != null && cntNew !== hdr.d) || (hdr.b != null && cntOld !== hdr.b))) (cntNew > hdr.d || cntOld > hdr.b ? err : warn)(`${at}: hunk "@@ -${hdr.a},${hdr.b ?? '?'} +${hdr.c},${hdr.d ?? '?'} @@" (block line ${hl}) is followed by ${cntOld}/${cntNew} old/new lines, header says ${hdr.b}/${hdr.d} — fine if you only cut the tail; if you removed LEADING or middle lines every gutter number after the cut is wrong (bump +${hdr.c} by the lines you dropped, or split into two @@ hunks)`); };
|
|
157
|
+
body.split('\n').forEach((l, i) => { const mm = l.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/); if (l.startsWith('@@')) { check(); hdr = mm ? { a: +mm[1], b: mm[2] != null ? +mm[2] : null, c: +mm[3], d: mm[4] != null ? +mm[4] : null } : null; cntNew = cntOld = 0; hl = i + 1; if (mm && mm[5] && !/^\s/.test(mm[5])) warn(`${at}: hunk header at block line ${i + 1} has text jammed after "@@" ("${mm[5].slice(0, 20)}") — leftover from an edit?`); return; }
|
|
158
|
+
if (/^\s*(…|\.\.\.)\s*$/.test(l)) { err(`${at}: "…" elision at block line ${i + 1} inside a diff hunk — the gutter can't know how many lines you cut; split into two hunks`); return; }
|
|
159
|
+
if (l[0] === '+') cntNew++; else if (l[0] === '-') cntOld++; else { cntNew++; cntOld++; } }); check(); }
|
|
160
|
+
if (!a.src && hasScript && !('wrap' in a)) { const longL = blockSrc(inner).split('\n').filter((l) => l.length > 90).length; if (longL >= 3) warn(`${at}: ${longL} lines over 90 chars in code you pasted/wrote — a phone shows ~44 mono columns; reflow the sketch (or add wrap for prose-like text)`); }
|
|
161
|
+
{ // pins must address a line number that the gutter will actually show
|
|
162
|
+
const body = blockSrc(a.src && !hasScript ? '' : inner); const isDiff = 'diff' in a || /^(diff|patch)$/.test(a.lang || ''); const st = +(a.start || (a.lines || '').match(/^\d+/)?.[0] || 1);
|
|
163
|
+
const valid = new Set(), validOld = new Set(); let A = st, B = +(a['old-start'] || st);
|
|
164
|
+
body.split('\n').forEach((l, i) => { if (!isDiff) { valid.add(st + i); return; } if (l.startsWith('@@')) { const ma = l.match(/\+(\d+)/), mb = l.match(/-(\d+)/); if (ma) A = +ma[1]; if (mb) B = +mb[1]; } else if (l[0] === '+') valid.add(A++); else if (l[0] === '-') validOld.add(B++); else { valid.add(A++); B++; } });
|
|
165
|
+
for (const p of inner.matchAll(/<doc-pin\b([^>]*)>([\s\S]*?)<\/doc-pin>/g)) { const pa = attrs(p[1]); if (wc(stripTags(p[2])) > 20) warn(`${at}: pin at line ${pa.line || pa.old} is ${wc(stripTags(p[2]))} words — pins locate (a clause or two); the argument goes in prose or a numbered risk it links to`);
|
|
166
|
+
if (!pa.line && !pa.old) err(`${at}: <doc-pin> inside doc-code needs line="" (file line number as shown in the gutter${isDiff ? '; old="N" for a removed line' : ''})`);
|
|
167
|
+
else if (pa.line && body && !valid.has(+pa.line)) err(`${at}: <doc-pin line="${pa.line}"> — no such line in this block (gutter shows ${[...valid][0]}–${[...valid].pop()}${isDiff ? ', new-side numbers; use old="N" to pin a removed line' : ''})`);
|
|
168
|
+
else if (pa.old && !validOld.has(+pa.old)) err(`${at}: <doc-pin old="${pa.old}"> — no removed line with that old-side number in this block`); } }
|
|
169
|
+
}
|
|
170
|
+
else if (tag === 'doc-mock') { if (!/<template[\s>]/i.test(inner)) err(`${at}: needs a <template>…</template> child holding the mock's HTML`); for (const p of inner.matchAll(/<doc-pin\b([^>]*)>/g)) { const pa = attrs(p[1]); if (pa.ref) { if (!new RegExp(`data-ref=["']${pa.ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`).test(inner)) err(`${at}: <doc-pin ref="${pa.ref}"> — no element with data-ref="${pa.ref}" inside this mock's <template>`); } else if (!/^\d+(\.\d+)?%?\s*,\s*\d+(\.\d+)?%?$/.test(pa.at || '')) err(`${at}: <doc-pin> inside doc-mock needs ref="data-ref-name" (preferred) or at="x%,y%"`); }
|
|
171
|
+
const w = +(a.w || a.width || { phone: 390, browser: 1024, terminal: 640, desktop: 900, none: 600 }[a.frame || 'browser'] || 800);
|
|
172
|
+
const ctx2k = html.slice(Math.max(0, idx - 400), idx); const inCols = /<div class="[^"]*\bcols\b[^"]*">(?:(?!<\/div>)[\s\S])*$/.test(ctx2k);
|
|
173
|
+
if ((a.frame === 'terminal') && w > 520 && !('thumbnail' in a)) warn(`${at}: terminal mock w=${w} — on a phone that's ~${Math.round(390 / w * 13)}px text; ≤480 (≈55 cols) stays readable, or add thumbnail to accept`);
|
|
174
|
+
else if (w >= 800 && !('thumbnail' in a)) warn(`${at}: ${a.frame || 'browser'} mock w=${w} renders at ~${Math.round(350 / w * 100)}% on a phone — fine as an overview (add thumbnail to say so), but pair it with a narrow crop (w≤480 frame=none) of the part that matters${inCols ? '; and it is inside .cols, which halves it again on desktop' : ''}`);
|
|
175
|
+
else if (inCols && w > 600) warn(`${at}: w=${w} mock inside .cols — .cols is for mocks ≤600 wide; stack them or use .storyboard`); }
|
|
176
|
+
else if (tag === 'doc-shot') { if (!a.src) err(`${at}: needs src=""`); else if (!/^(data:|https?:)/.test(a.src) && !findFile(a.src)) err(`${at}: src="${a.src}" not found`); }
|
|
177
|
+
else if (tag === 'doc-draft') { if (!blockSrc(inner).trim()) err(`${at}: empty — put the editable text inside <script type="text/plain">`); if (!a.id) warn(`${at}: give it an id so edits survive a reload`); }
|
|
178
|
+
else if (tag === 'doc-quote') { if (!a.via) warn(`${at}: add via="prompt|slack|github|transcript|doc|tools|…"`); if (!inner.trim()) err(`${at}: empty quote`); if (/[{}]/.test(a.from || '')) warn(`${at}: from="${a.from}" contains braces — from= is the literal name/handle the source shows; put role/agent context in where=`);
|
|
179
|
+
if (a.via === 'slack' && a.href && /\/archives\/[A-Z0-9]+\/?$/.test(a.href)) warn(`${at}: href links the channel, not the message — use the permalink (…/p<ts>)`);
|
|
180
|
+
if (/\(|:\d+\b/.test(a.from || '')) warn(`${at}: from="${a.from}" — from is the bare name/handle; role, file:line or context go in where=`);
|
|
181
|
+
const body = stripTags(inner).replace(/\s+/g, ' ').trim(); if (body.length > 40) { if (quoteSeen.has(body)) warn(`${at}: same quote text already appears at line ${quoteSeen.get(body)} — quote it once, reference it after`); else quoteSeen.set(body, lineOf(idx)); } }
|
|
182
|
+
else if (tag === 'doc-ask') {
|
|
183
|
+
if (!a.id) warn(`${at}: add an id — it anchors the TOC entry and the response`);
|
|
184
|
+
if (!/<(p|h3|h4)[\s>]/i.test(inner) && !a.q) err(`${at}: needs a question — first <p> child (or q="")`);
|
|
185
|
+
const ctrls = [...inner.matchAll(/<(input|textarea|select|ol)\b([^>]*)>/gi)].map((m) => ({ tag: m[1].toLowerCase(), ...attrs(m[2]) }));
|
|
186
|
+
const named = ctrls.filter((c) => c.name || (c.tag === 'ol' && c['data-name']));
|
|
187
|
+
if (!named.length) err(`${at}: no named controls — use <label><input type=radio name=… value=…> …</label>, checkboxes, <textarea name>, <input type=range name>, or <ol class=rank data-name>`);
|
|
188
|
+
const radios = named.filter((c) => c.type === 'radio'); const groups = [...new Set(radios.map((r) => r.name))];
|
|
189
|
+
groups.forEach((g) => { const rs = radios.filter((r) => r.name === g); if (!rs.some((r) => 'checked' in r)) warn(`${at}: radio group "${g}" has no checked option — pre-select your recommendation so "no change" is an answer`); if (rs.some((r) => !r.value)) err(`${at}: every radio in "${g}" needs a value`); if (names.has(g)) err(`${at}: control name "${g}" is used by an earlier doc-ask`); });
|
|
190
|
+
named.forEach((c) => names.add(c.name || c['data-name']));
|
|
191
|
+
if (ctrls.some((c) => c.tag === 'input' && !c.type)) warn(`${at}: <input> without type`);
|
|
192
|
+
for (const sm of inner.matchAll(/<small>([\s\S]*?)<\/small>/g)) if (wc(stripTags(sm[1])) > 16) { warn(`${at}: an option's <small> is ${wc(stripTags(sm[1]))} words — ≤ ~12; the trade-off is argued once in the section, the option just names it`); break; }
|
|
193
|
+
const q = inner.match(/<(p|h3|h4)[^>]*>([\s\S]*?)<\/\1>/i); if (q && wc(stripTags(q[2])) > 25) warn(`${at}: the question is ${wc(stripTags(q[2]))} words — keep the first <p> to the question (≤ ~15 words) and put context in a second <p>`);
|
|
194
|
+
if (lastAskEnd >= 0 && !html.slice(lastAskEnd, idx).replace(/<[^>]+>/g, '').trim()) warn(`${at}: directly follows another doc-ask with nothing between — asks belong where their consequence is discussed, not stacked`);
|
|
195
|
+
lastAskEnd = idx + whole.length;
|
|
196
|
+
}
|
|
197
|
+
else if (tag === 'doc-pin' && !/doc-(code|mock|shot)/.test(html.slice(Math.max(0, idx - 3000), idx).split('</doc-').pop() ? '' : '')) { /* checked inside parents */ }
|
|
198
|
+
} catch (e) { err(`${at}: ${e.message}`); }
|
|
199
|
+
return whole;
|
|
200
|
+
});
|
|
201
|
+
for (const m of html.matchAll(/data-if=["']([^"']+)["']/g)) m[1].split(/\s*&&\s*/).forEach((c) => { const n = c.replace(/^!/, '').split(/[=!~]/)[0].trim(); if (!names.has(n)) err(`line ${lineOf(m.index)}: data-if="${m[1]}" — no control named "${n}"`); });
|
|
202
|
+
if (/<doc-pin\b/.test(html.replace(/<doc-(code|mock|shot|schema)\b[\s\S]*?<\/doc-\1>/g, ''))) err('a <doc-pin> sits outside any doc-code / doc-mock / doc-shot');
|
|
203
|
+
|
|
204
|
+
/* ── doc-plan: the shape of the tree ── */
|
|
205
|
+
if (/<doc-plan\b/.test(html)) {
|
|
206
|
+
const flat = html.replace(/<!--[\s\S]*?-->/g, '').replace(/<(script|template|style)\b[\s\S]*?<\/\1>/gi, '').replace(/(<doc-(machine|ask|calls|mock|note)\b[^>]*>)[\s\S]*?(<\/doc-\2>)/gi, '$1$3');
|
|
207
|
+
const root = { no: '', kids: [], ex: [], l: 0 }; const stack = [root]; let inPlan = 0;
|
|
208
|
+
for (const t of flat.matchAll(/<(\/?)(doc-plan|doc-claim)\b([^>]*)>|<(doc-(?:mock|shot|machine|calls|schema|code|flow|seq|tree|quote))\b|<(doc-ask)\b|<p\b[^>]*>([\s\S]*?)<\/p>/g)) {
|
|
209
|
+
const top = stack[stack.length - 1];
|
|
210
|
+
if (t[2] === 'doc-plan') { inPlan += t[1] ? -1 : 1; continue; }
|
|
211
|
+
if (t[2] === 'doc-claim') { if (t[1]) { if (stack.length > 1) stack.pop(); else err('a </doc-claim> closes nothing'); continue; }
|
|
212
|
+
if (!inPlan) err('a <doc-claim> sits outside any <doc-plan>');
|
|
213
|
+
const a = attrs(t[3]); const n = { a, kids: [], ex: [], asks: 0, claim: null, l: top.l + 1 }; n.no = a.aux ? a.aux : (top.no && !top.a?.aux ? top.no + '.' : '') + (top.kids.filter((k) => !k.a.aux).length + 1); top.kids.push(n); stack.push(n); continue; }
|
|
214
|
+
if (stack.length === 1) continue;
|
|
215
|
+
if (t[4]) top.ex.push(t[4]); else if (t[5]) top.asks++; else if (t[6] != null && top.claim == null && !top.ex.length && !top.kids.length) top.claim = stripTags(t[6]).replace(/\s+/g, ' ').trim();
|
|
216
|
+
}
|
|
217
|
+
if (stack.length > 1) err(`${stack.length - 1} <doc-claim> left open — every claim needs its </doc-claim>`);
|
|
218
|
+
const walk = (n) => { const at = `claim ${n.no}`;
|
|
219
|
+
if (n.claim == null && !n.a.at) err(`${at}: no claim — the first child must be a <p> with one sentence (or give it at="path:line")`);
|
|
220
|
+
if (n.claim && wc(n.claim) > 16) warn(`${at}: the claim is ${wc(n.claim)} words — one short sentence (≤ ~12) that can be true or false`);
|
|
221
|
+
if (n.claim && n.l <= 2 && !n.a.aux && !/[.?!]$/.test(n.claim)) warn(`${at}: "${n.claim.slice(0, 40)}" — write a full sentence with a verb, not a heading`);
|
|
222
|
+
if (n.ex.length > 1) warn(`${at}: ${n.ex.length} exhibits (${n.ex.join(', ')}) — one per claim; give the others their own child claims`);
|
|
223
|
+
if (!n.ex.length && !n.kids.length && n.a.aux !== 'scope') warn(`${at}: nothing under it — add the exhibit that proves it`);
|
|
224
|
+
if (n.kids.length > 5) warn(`${at}: ${n.kids.length} child claims — 5 at most; group them`);
|
|
225
|
+
if (n.l > 3) warn(`${at}: level ${n.l} — three levels at most (what › how › where)`);
|
|
226
|
+
n.kids.forEach(walk); };
|
|
227
|
+
const tops = root.kids.filter((k) => !k.a.aux); if (tops.length > 5) warn(`doc-plan: ${tops.length} top-level claims — 5 at most, plus aux="shared" and aux="scope"`);
|
|
228
|
+
if (root.kids.length && !root.kids.some((k) => k.a.aux === 'scope')) warn('doc-plan: no <doc-claim aux="scope"> — end with what is not changing');
|
|
229
|
+
const i = root.kids.findIndex((k) => k.a.aux); if (i >= 0 && root.kids.slice(i).some((k) => !k.a.aux)) warn('doc-plan: aux claims go last');
|
|
230
|
+
root.kids.forEach(walk);
|
|
231
|
+
const nAsk = (flat.match(/<doc-ask\b/g) || []).length; if (nAsk > 6) warn(`doc-plan: ${nAsk} decisions — 2 to 5; ask only about forks that change what you build, and default the rest`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
for (const m of html.matchAll(/<doc-changes\b([^>]*)>/g)) { const a = attrs(m[1]); if (!['new', 'changed', 'deleted'].some((k) => parseInt(a[k], 10) > 0)) warn(`line ${lineOf(m.index)} <doc-changes>: give new="N", changed="N" or deleted="N" (files) — with none it draws nothing`); }
|
|
235
|
+
|
|
236
|
+
if (/<doc-plan\b/.test(html)) { // a plan starts with a title, not a label line or a goal sentence
|
|
237
|
+
const k = html.match(/<p\s+class=["']?kicker\b/i); if (k) warn(`line ${lineOf(k.index)}: a plan has no label line above its title — remove <p class="kicker">; the page hides it`);
|
|
238
|
+
const m = html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i); const t = m ? stripTags(m[1]).replace(/\s+/g, ' ').trim() : '';
|
|
239
|
+
if (t && (wc(t) > 8 || /[.!?](\s|$)/.test(t))) warn(`line ${lineOf(m.index)}: the <h1> of a plan is a title, not a sentence — name the change and the place in 3 to 7 words ("Scheduling Sent Messages in PostBox"); the level-1 claims say what changes`);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/* ── words: the blocks are the document; prose only joins them ── */
|
|
243
|
+
{ const main = (html.match(/<main[\s\S]*<\/main>/i) || [html])[0];
|
|
244
|
+
const blocks = (main.match(/<doc-(code|flow|seq|schema|tree|calls|machine|mock|shot|ask|draft)\b/g) || []).length;
|
|
245
|
+
const bare = main.replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi, ' ').replace(/<(doc-(?:code|flow|seq|schema|tree|calls|machine|mock|shot|ask|draft|quote))\b[\s\S]*?<\/\1>/gi, ' ');
|
|
246
|
+
let total = 0, long = 0, longest = 0, slow = 0;
|
|
247
|
+
for (const m of bare.matchAll(/<(p|li|dd|doc-note)\b[^>]*>([\s\S]*?)<\/\1>/gi)) { const t = stripTags(m[2]).replace(/\s+/g, ' ').trim(); const n = wc(t); total += n; if (n > 40) { long++; longest = Math.max(longest, n); } t.split(/(?<=[.!?])\s+/).forEach((sn) => { if (wc(sn) > 25) slow++; }); }
|
|
248
|
+
if (long) warn(`${long} paragraph${long > 1 ? 's' : ''} over 40 words (longest ${longest}) — two short sentences, then a block; move the rest into a caption, a pin or a table`);
|
|
249
|
+
if (slow) warn(`${slow} sentence${slow > 1 ? 's' : ''} over 25 words — split them; one idea per sentence`);
|
|
250
|
+
if (total > 350 || (blocks && total / blocks > 45)) warn(`${total} words of prose for ${blocks} block${blocks === 1 ? '' : 's'} — aim for ≤ 350 words and ≤ ~30 per block; cut, or show it as a block`);
|
|
251
|
+
// ASD-STE100 (Simplified Technical English). This is a partial check: it knows a few common unapproved words and the countable writing rules, not the full dictionary.
|
|
252
|
+
const STE = { utilize: 'use', utilizes: 'uses', leverage: 'use', leverages: 'uses', facilitate: 'help', facilitates: 'helps', 'in order to': 'to', subsequently: 'then', aforementioned: 'this', 'prior to': 'before', additionally: 'also', furthermore: 'also', however: 'but', comprehensive: 'full', robust: 'strong', seamless: 'smooth', seamlessly: 'smoothly', numerous: 'many', commence: 'start', commences: 'starts', begin: 'start', begins: 'starts', terminate: 'stop', terminates: 'stops', demonstrate: 'show', demonstrates: 'shows', indicate: 'show', indicates: 'shows', ensure: 'make sure', ensures: 'makes sure', verify: 'make sure', verifies: 'makes sure', perform: 'do', performs: 'does', 'carry out': 'do', 'carries out': 'does', obtain: 'get', obtains: 'gets', provide: 'give', provides: 'gives', should: 'must', shall: 'must', might: 'can', 'with respect to': 'about', 'due to the fact that': 'because' };
|
|
253
|
+
const prose = stripTags(bare.replace(/<(code|kbd|pre)\b[\s\S]*?<\/\1>/gi, ' ')); const text = prose.toLowerCase();
|
|
254
|
+
const hits = Object.keys(STE).filter((w) => new RegExp(`\\b${w}\\b`).test(text)); if (/[a-z,] may\b/.test(prose)) { hits.push('may'); STE.may = 'can'; }
|
|
255
|
+
if (hits.length) warn(`ASD-STE100 words: ${hits.slice(0, 8).map((w) => `"${w}" → "${STE[w]}"`).join(', ')}${hits.length > 8 ? ` … ${hits.length - 8} more` : ''}`);
|
|
256
|
+
const contr = [...new Set(text.match(/\b(?:\w+n['’]t|(?:it|that|there|here|what|let|who)['’]s|\w+['’](?:re|ve|ll))\b/g) || [])];
|
|
257
|
+
if (contr.length) warn(`ASD-STE100: no contractions — ${contr.slice(0, 6).join(', ')}`);
|
|
258
|
+
const perfect = [...new Set(text.match(/\b(?:has|have|had) (?:been|already|not|never|just) \w+|\b(?:has|have|had) \w+ed\b/g) || [])];
|
|
259
|
+
if (perfect.length) warn(`ASD-STE100: use simple tenses, not "has/have + verb" — ${perfect.slice(0, 4).map((x) => `"${x}"`).join(', ')}`);
|
|
260
|
+
const passive = [...new Set(text.match(/\b(?:is|are|was|were|be|been|being) (?:\w+ed|written|sent|made|done|shown|taken|given|kept|held|read|run|set|put|built|chosen) by\b/g) || [])];
|
|
261
|
+
if (passive.length) warn(`ASD-STE100: use the active voice — ${passive.slice(0, 4).map((x) => `"${x}"`).join(', ')} (say who does it first)`);
|
|
262
|
+
let six = 0; for (const m of bare.matchAll(/<(p|li|dd|doc-note)\b[^>]*>([\s\S]*?)<\/\1>/gi)) if (stripTags(m[2]).split(/(?<=[.!?])\s+/).filter((x) => x.trim()).length > 6) six++;
|
|
263
|
+
if (six) warn(`ASD-STE100: ${six} paragraph${six > 1 ? 's' : ''} with more than 6 sentences — split`); }
|
|
264
|
+
|
|
265
|
+
/* ── inline assets ── */
|
|
266
|
+
let packed = html; let inlined = 0;
|
|
267
|
+
if (!lintOnly) {
|
|
268
|
+
packed = packed.replace(/<link\b[^>]*href=["']([^"']*htmlplan\.css)["'][^>]*>/i, (m, href) => { const f = findFile(href) || resolve(here, 'htmlplan.css'); inlined++; return `<style data-htmlplan>\n${readFileSync(f, 'utf8')}\n</style>`; });
|
|
269
|
+
packed = packed.replace(/<link\b[^>]*rel=["']stylesheet["'][^>]*href=["']([^"':]+\.css)["'][^>]*>/gi, (m, href) => { const f = findFile(href); if (!f) { warn(`stylesheet ${href} not found — left as a link`); return m; } inlined++; return `<style>/* ${basename(href)} */\n${readFileSync(f, 'utf8')}\n</style>`; }); // any other local stylesheet
|
|
270
|
+
packed = packed.replace(/<script\b[^>]*src=["']([^"']*htmlplan\.js)["'][^>]*>\s*<\/script>/i, (m, src) => { const f = findFile(src) || resolve(here, 'htmlplan.js'); inlined++; return `<script data-htmlplan>\n${readFileSync(f, 'utf8').replace(/<\/script/gi, '<\\/script')}\n</script>`; });
|
|
271
|
+
const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webm': 'video/webm' };
|
|
272
|
+
packed = packed.replace(/(<(?:img|doc-shot|video|source)\b[^>]*?\ssrc=["'])([^"']+)(["'])/gi, (m, pre, src, post) => {
|
|
273
|
+
if (/^(data:|https?:|#)/.test(src)) return m; const f = findFile(src); if (!f) { warn(`asset ${src} not found — left as-is`); return m; }
|
|
274
|
+
const size = statSync(f).size; if (size > 6e6) { warn(`${src} is ${(size / 1e6).toFixed(1)} MB — not inlining; the packed file will need it alongside`); return m; }
|
|
275
|
+
inlined++; return `${pre}data:${MIME[extname(f).toLowerCase()] || 'application/octet-stream'};base64,${readFileSync(f).toString('base64')}${post}`;
|
|
276
|
+
});
|
|
277
|
+
if (!/data-htmlplan-packed/.test(packed)) packed = packed.replace(/<html\b/i, '<html data-htmlplan-packed');
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/* ── report ── */
|
|
281
|
+
const rel = (p) => relative(process.cwd(), p) || p;
|
|
282
|
+
if (!quiet) {
|
|
283
|
+
console.log(`\n${basename(inPath)}`);
|
|
284
|
+
info.forEach((m) => console.log(' · ' + m));
|
|
285
|
+
warns.forEach((m) => console.log(' ⚠ ' + m));
|
|
286
|
+
errors.forEach((m) => console.log(' ✗ ' + m));
|
|
287
|
+
}
|
|
288
|
+
if (errors.length) { console.log(`\n✗ ${errors.length} error(s), ${warns.length} warning(s) — fix and re-run.`); process.exit(1); }
|
|
289
|
+
if (lintOnly) { console.log(`✓ lint clean${warns.length ? ` (${warns.length} warning${warns.length > 1 ? 's' : ''})` : ''}`); process.exit(0); }
|
|
290
|
+
writeFileSync(outPath, packed);
|
|
291
|
+
if (reads.size && (!quiet || argv.includes('--artifact'))) console.log(` code from ${reads.size} file${reads.size > 1 ? 's' : ''} is now inside the page: ${[...reads].sort().join(', ')}`);
|
|
292
|
+
if (argv.includes('--artifact')) { // the Artifact tool wraps the page in its own <html><head><body>: publish content only
|
|
293
|
+
const bodyAttrs = attrs((packed.match(/<body\b([^>]*)>/i) || [])[1] || ''); const data = Object.fromEntries(Object.entries(bodyAttrs).filter(([k]) => k.startsWith('data-')).map(([k, v]) => [k.slice(5).replace(/-(\w)/g, (m, c) => c.toUpperCase()), v]));
|
|
294
|
+
let art = packed.replace(/<!doctype[^>]*>\s*/i, '').replace(/<\/?html\b[^>]*>\s*/gi, '').replace(/<meta\b[^>]*charset[^>]*>\s*/i, '').replace(/<\/?head\b[^>]*>\s*/gi, '').replace(/<\/?body\b[^>]*>\s*/gi, '');
|
|
295
|
+
if (Object.keys(data).length) art = art.replace(/<script data-htmlplan>/, `<script>Object.assign(document.body.dataset, ${JSON.stringify(data)});</script>\n<script data-htmlplan>`);
|
|
296
|
+
const ti = (art.match(/<title>([^<]*)<\/title>/i) || [])[1] || ''; if (/[:—–]|\s-\s/.test(ti) || wc(ti) > 5) console.log(` ⚠ <title> "${ti.trim()}" — a published artifact is named like a document: 2–4 words, no "Plan:" prefix, no explainer after a dash`);
|
|
297
|
+
const artPath = outPath.replace(/(\.packed)?\.html?$/, '.artifact.html'); writeFileSync(artPath, art);
|
|
298
|
+
console.log(`✓ ${rel(artPath)} publish this one with the Artifact tool`);
|
|
299
|
+
}
|
|
300
|
+
console.log(`✓ ${rel(outPath)} ${(Buffer.byteLength(packed) / 1024).toFixed(0)} KB · ${inlined} asset(s) inlined${warns.length ? ` · ${warns.length} warning(s)` : ''}`);
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-vscode-mode host — 统一 AI JSON 任务层(22-agent-tools-and-commit)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成模块:AI 整理、AI 提交信息、后续 AI 复核都是「系统指令 + 数据 prompt →
|
|
5
|
+
* 严格 JSON」同一形状。之前这套流式汇聚/超时/失败分类内联在 svnTriage 里,
|
|
6
|
+
* 第二个任务只能复制一遍;抽出来后失败文案与超时口径只有一份。
|
|
7
|
+
*
|
|
8
|
+
* 口径:一次性非会话流式调用(llm.of → taskRouteOf),只收 text-delta;
|
|
9
|
+
* 适配器失败走 finish(error/aborted) 而非抛异常;任何失败都归一成 code + 可读文案。
|
|
10
|
+
* @author ddj 2026年11月15号
|
|
11
|
+
*/
|
|
12
|
+
import type { Ctx } from '../store.js'
|
|
13
|
+
import type { AiConfigView } from '../shared/ai.js'
|
|
14
|
+
import type { LlmRuntimeLike, StreamChunk } from './llmTypes.js'
|
|
15
|
+
import { llmOf, taskRouteOf } from './inline.js'
|
|
16
|
+
|
|
17
|
+
/** AI 任务失败分类(client 据此给不同可操作提示)。 */
|
|
18
|
+
export type LlmTaskCode = 'UNAVAILABLE' | 'NO_MODEL' | 'TIMEOUT' | 'STREAM' | 'PARSE' | 'EMPTY'
|
|
19
|
+
|
|
20
|
+
/** 一次 JSON 任务请求。 */
|
|
21
|
+
export interface LlmTaskRequest {
|
|
22
|
+
/** 系统指令(输出契约 + 硬约束)。 */
|
|
23
|
+
system: string
|
|
24
|
+
/** 用户段(数据;不含任何可执行指令)。 */
|
|
25
|
+
prompt: string
|
|
26
|
+
/** 超时(毫秒)。 */
|
|
27
|
+
timeoutMs: number
|
|
28
|
+
/** 输出 token 上限。 */
|
|
29
|
+
maxTokens: number
|
|
30
|
+
/** 温度(缺省 0.2)。 */
|
|
31
|
+
temperature?: number
|
|
32
|
+
/** 会话身份(provider 路由用;如 opencode-go 的 x-opencode-session)。 */
|
|
33
|
+
sessionId?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 任务结果(成功带解析后的对象与模型标识)。 */
|
|
37
|
+
export type LlmTaskOutcome =
|
|
38
|
+
| { ok: true; raw: unknown; text: string; model: string; elapsedMs: number }
|
|
39
|
+
| { ok: false; code: LlmTaskCode; error: string; model?: string }
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 模型流失败 → 可操作文案(未注册 provider 单独指引,不要把底层错误码直接甩给用户)。
|
|
43
|
+
* @author ddj 2026年11月15号
|
|
44
|
+
* @param label provider/model @param kind finish 原因 @param failure 适配器失败细节
|
|
45
|
+
* @returns 分类与文案
|
|
46
|
+
*/
|
|
47
|
+
function streamFailureOf(
|
|
48
|
+
label: string,
|
|
49
|
+
kind: string,
|
|
50
|
+
failure?: { code?: string; message?: string },
|
|
51
|
+
): { code: LlmTaskCode; error: string } {
|
|
52
|
+
const detail = failure?.code ?? kind
|
|
53
|
+
const message = failure?.message ?? '模型调用失败'
|
|
54
|
+
const text = detail + ' ' + message
|
|
55
|
+
if (/MissingSessionID|x-opencode-session/i.test(text)) {
|
|
56
|
+
return {
|
|
57
|
+
code: 'NO_MODEL',
|
|
58
|
+
error: '任务模型 ' + label + ' 要求会话身份(' + detail + '):插件已带当前会话仍被拒时,请在「设置 → AI」换一个支持一次性调用的模型',
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (/NO_ADAPTER|no adapter registered|未注册|not registered/i.test(text)) {
|
|
62
|
+
return {
|
|
63
|
+
code: 'NO_MODEL',
|
|
64
|
+
error: '任务模型 ' + label + ' 在宿主未注册(' + detail + '):请在「设置 → AI」里换一个可用模型,或把任务模型留空以跟随补全配置',
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (kind === 'aborted') return { code: 'STREAM', error: '任务模型 ' + label + ' 调用被中断:' + message }
|
|
68
|
+
return { code: 'STREAM', error: '任务模型 ' + label + ' 调用失败(' + detail + '):' + message }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 从模型输出里取 JSON 对象(剥围栏 → 首个 { 至末个 } → parse)。
|
|
73
|
+
* @author ddj 2026年11月15号
|
|
74
|
+
* @param text 模型输出原文
|
|
75
|
+
* @returns 解析出的对象
|
|
76
|
+
*/
|
|
77
|
+
export function parseJsonObject(text: string): unknown {
|
|
78
|
+
const raw = String(text ?? '')
|
|
79
|
+
const start = raw.indexOf('{')
|
|
80
|
+
const end = raw.lastIndexOf('}')
|
|
81
|
+
if (start < 0 || end <= start) throw new Error('AI 输出不含 JSON 对象:' + raw.slice(0, 200))
|
|
82
|
+
const body = raw.slice(start, end + 1)
|
|
83
|
+
try {
|
|
84
|
+
return JSON.parse(body)
|
|
85
|
+
} catch (error) {
|
|
86
|
+
throw new Error('AI 输出无法解析为 JSON:' + String(error) + '(原文摘要:' + body.slice(0, 200) + ')')
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 执行一次 JSON 任务(不抛错:所有失败都归一成 §{ ok:false, code }§)。
|
|
92
|
+
* @author ddj 2026年11月15号
|
|
93
|
+
* @param ctx DSH 上下文
|
|
94
|
+
* @param cfg AI 配置(任务模型优先,回落补全配置)
|
|
95
|
+
* @param request 任务请求
|
|
96
|
+
* @returns 任务结果
|
|
97
|
+
*/
|
|
98
|
+
export async function runJsonTask(ctx: Ctx, cfg: AiConfigView, request: LlmTaskRequest): Promise<LlmTaskOutcome> {
|
|
99
|
+
const llm: LlmRuntimeLike | null = llmOf(ctx)
|
|
100
|
+
if (!llm) return { ok: false, code: 'UNAVAILABLE', error: 'llm 服务不可用(请检查 DSH 模型配置)' }
|
|
101
|
+
const route = await taskRouteOf(llm, cfg)
|
|
102
|
+
if (!route) return { ok: false, code: 'NO_MODEL', error: '未找到可用模型(请检查 DSH 模型配置)' }
|
|
103
|
+
const label = route.provider + '/' + route.model
|
|
104
|
+
|
|
105
|
+
const controller = new AbortController()
|
|
106
|
+
let timedOut = false
|
|
107
|
+
const timer = setTimeout(() => {
|
|
108
|
+
timedOut = true
|
|
109
|
+
controller.abort(new Error('timeout'))
|
|
110
|
+
}, request.timeoutMs)
|
|
111
|
+
|
|
112
|
+
const startedAt = Date.now()
|
|
113
|
+
try {
|
|
114
|
+
const stream = llm.stream({
|
|
115
|
+
provider: route.provider,
|
|
116
|
+
model: route.model,
|
|
117
|
+
...(route.effort ? { reasoningEffort: route.effort } : {}),
|
|
118
|
+
messages: [
|
|
119
|
+
{ role: 'user', content: [{ type: 'text', text: request.prompt }], source: { kind: 'user' } } as never,
|
|
120
|
+
],
|
|
121
|
+
system: request.system,
|
|
122
|
+
temperature: request.temperature ?? 0.2,
|
|
123
|
+
maxTokens: request.maxTokens,
|
|
124
|
+
// 会话身份:部分 provider(如 opencode-go)据此生成路由头,缺省会 400 MissingSessionID
|
|
125
|
+
...(request.sessionId ? { sessionId: request.sessionId } : {}),
|
|
126
|
+
// 不传 stop:llm-pi-ai 等适配器不支持该选项(UNSUPPORTED_OPTION 直接 error finish)
|
|
127
|
+
signal: controller.signal,
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
let text = ''
|
|
131
|
+
let failNote: { code: LlmTaskCode; error: string } | null = null
|
|
132
|
+
for await (const chunk of stream) {
|
|
133
|
+
const item = chunk as StreamChunk
|
|
134
|
+
if (item.type === 'text-delta') {
|
|
135
|
+
text += item.text
|
|
136
|
+
} else if (item.type === 'finish') {
|
|
137
|
+
const kind = (item.reason as { kind?: string })?.kind
|
|
138
|
+
if (kind === 'error' || kind === 'aborted') {
|
|
139
|
+
const failure = (item.reason as { failure?: { code?: string; message?: string } }).failure
|
|
140
|
+
failNote = streamFailureOf(label, kind, failure)
|
|
141
|
+
}
|
|
142
|
+
break
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (failNote) return { ok: false, code: failNote.code, error: failNote.error, model: label }
|
|
146
|
+
if (!text.trim()) return { ok: false, code: 'EMPTY', error: '任务模型 ' + label + ' 没有返回任何内容', model: label }
|
|
147
|
+
let raw: unknown
|
|
148
|
+
try {
|
|
149
|
+
raw = parseJsonObject(text)
|
|
150
|
+
} catch (error) {
|
|
151
|
+
return {
|
|
152
|
+
ok: false,
|
|
153
|
+
code: 'PARSE',
|
|
154
|
+
error: '任务模型 ' + label + ' 输出不是合法 JSON:' + String(error instanceof Error ? error.message : error),
|
|
155
|
+
model: label,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
ok: true,
|
|
160
|
+
raw,
|
|
161
|
+
text,
|
|
162
|
+
model: route.provider + '/' + route.model,
|
|
163
|
+
elapsedMs: Date.now() - startedAt,
|
|
164
|
+
}
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (timedOut) {
|
|
167
|
+
return {
|
|
168
|
+
ok: false,
|
|
169
|
+
code: 'TIMEOUT',
|
|
170
|
+
error: '任务模型 ' + label + ' 超时(' + Math.round(request.timeoutMs / 1000) + 's):可在设置页调低任务模型思考强度或换更快模型',
|
|
171
|
+
model: label,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { ok: false, code: 'STREAM', error: '任务模型 ' + label + ' 调用失败:' + String(error instanceof Error ? error.message : error), model: label }
|
|
175
|
+
} finally {
|
|
176
|
+
clearTimeout(timer)
|
|
177
|
+
}
|
|
178
|
+
}
|
package/src/ai/llmTypes.ts
CHANGED
|
@@ -36,6 +36,12 @@ export interface GenerateOptions {
|
|
|
36
36
|
maxTokens?: number
|
|
37
37
|
stop?: string[]
|
|
38
38
|
signal?: AbortSignal
|
|
39
|
+
/**
|
|
40
|
+
* 会话身份(provider 路由用):pi-ai 会把它转交 provider,
|
|
41
|
+
* 例如 opencode-go 需要据它发出 `x-opencode-session` 头,否则返回 MissingSessionID。
|
|
42
|
+
* 一次性调用传当前会话 id 即可(缺省则不带)。
|
|
43
|
+
*/
|
|
44
|
+
sessionId?: string
|
|
39
45
|
}
|
|
40
46
|
|
|
41
47
|
/** 流块:本插件消费 text-delta / finish(其余忽略)。 */
|