@lumyne/omni-cli 0.0.0-stage → 0.3.1
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/INSTALL.md +11 -0
- package/README.md +38 -2
- package/UPDATE.md +17 -0
- package/bin/omni.mjs +47 -0
- package/capabilities.json +2231 -0
- package/lib/core.mjs +62 -0
- package/lib/database.mjs +35 -0
- package/lib/lifecycle.mjs +99 -0
- package/lib/local-agent.mjs +30 -0
- package/lib/management.mjs +42 -0
- package/lib/market.mjs +192 -0
- package/lib/project-artifact.mjs +25 -0
- package/lib/project-edit.mjs +33 -0
- package/lib/project-execution.mjs +33 -0
- package/lib/project-read.mjs +10 -0
- package/package.json +39 -4
- package/schema/tenant-001.sql +119 -0
- package/schema/tenant-002.sql +12 -0
- package/schema/tenant-003.sql +6 -0
- package/schema/tenant-004.sql +137 -0
- package/skills/omni-data/SKILL.md +40 -0
- package/skills/omni-data/adapters/generic.json +25 -0
- package/skills/omni-data/agents/openai.yaml +3 -0
- package/skills/omni-data/capabilities.json +42 -0
- package/skills/omni-data/references/daily-metrics.md +11 -0
- package/skills/omni-data/references/management.md +15 -0
- package/skills/omni-data/references/market.md +20 -0
- package/skills/omni-project/SKILL.md +68 -0
- package/skills/omni-project/adapters/generic.json +25 -0
- package/skills/omni-project/agents/openai.yaml +3 -0
- package/skills/omni-project/capabilities.json +42 -0
- package/skills/omni-project/references/queries.md +24 -0
package/lib/core.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
export class OmniError extends Error{constructor(code,message,details={}){super(message);this.code=code;this.details=details;}}
|
|
6
|
+
export const fail=(code,message,details)=>{throw new OmniError(code,message,details);};
|
|
7
|
+
export function sha(value){return createHash('sha256').update(value).digest('hex');}
|
|
8
|
+
export function privateJson(file){const stat=fs.lstatSync(file);if(!stat.isFile()||stat.isSymbolicLink()||(process.platform!=='win32'&&(stat.mode&0o077)))fail('UNSAFE_CONFIG','配置文件必须为当前用户可读写的私有普通文件');if(typeof process.getuid==='function'&&stat.uid!==process.getuid())fail('UNSAFE_CONFIG','配置文件所有者不匹配');return JSON.parse(fs.readFileSync(file,'utf8'));}
|
|
9
|
+
export function profilePath(profile='stable'){
|
|
10
|
+
if(!['dev','stable'].includes(profile))fail('INVALID_PROFILE','profile 只能是 dev 或 stable');
|
|
11
|
+
const base=process.platform==='darwin'?path.join(os.homedir(),'Library','Application Support'):process.platform==='win32'?process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'):process.env.XDG_CONFIG_HOME||path.join(os.homedir(),'.config');
|
|
12
|
+
return path.join(base,profile==='dev'?'Shanhai OMNI Dev':'Shanhai OMNI','agent-connection.json');
|
|
13
|
+
}
|
|
14
|
+
export function connection(options){let file=options.config;if(!file){if(options.profile&&options.profile!=='auto')file=profilePath(options.profile);else{const candidates=['dev','stable'].map(p=>profilePath(p)).filter(p=>fs.existsSync(p));if(candidates.length>1)fail('PROFILE_REQUIRED','开发版和安装版均有账号连接,请明确 --profile dev 或 stable');file=candidates[0]||profilePath('stable');}}if(!fs.existsSync(file))fail('AUTH_REQUIRED','请先在对应桌面版本登录,即可连接同机插件');const data=privateJson(file);if(data.owner!=='omni-agent-connection'||data.schemaVersion!==1||typeof data.sessionToken!=='string'||data.sessionToken.length<20)fail('INVALID_CONFIG','桌面授权合同不匹配');for(const name of ['authUrl','dataServiceUrl']){const url=new URL(data[name]);if(url.protocol!=='https:'||url.username||url.password||url.pathname!=='/'||url.search||url.hash)fail('INVALID_CONFIG','服务地址必须为无凭证的 HTTPS 源');}return data;}
|
|
15
|
+
export async function jsonRequest(url,{token,method='GET',body,shops,fetchImpl=fetch}={}){
|
|
16
|
+
let response;
|
|
17
|
+
try{response=await fetchImpl(url,{method,redirect:'error',signal:AbortSignal.timeout(15000),headers:{Authorization:'Bearer '+token,...(body?{'Content-Type':'application/json'}:{}),...(shops?{'X-Omni-Shop-Ids':JSON.stringify(shops)}:{})},body:body?JSON.stringify(body):undefined});}catch{fail(method==='POST'?'WRITE_OUTCOME_UNKNOWN':'SERVICE_UNAVAILABLE',method==='POST'?'写入结果未知,请查询数据确认后再决定重试':'无法连接在线服务');}
|
|
18
|
+
const reader=response.body?.getReader();let size=0;const chunks=[];if(reader)while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>20_000_000){await reader.cancel();fail('RESPONSE_TOO_LARGE','请缩小读取范围');}chunks.push(Buffer.from(value));}
|
|
19
|
+
let data;try{data=JSON.parse(Buffer.concat(chunks).toString('utf8'));}catch{fail('INVALID_RESPONSE','服务返回格式不匹配');}
|
|
20
|
+
if(!response.ok)fail(response.status===401?'AUTH_REQUIRED':response.status===403?'PERMISSION_REQUIRED':'SERVICE_ERROR',typeof data.error==='string'?data.error:'服务请求失败',{status:response.status,serviceCode:data.code,serviceDetails:data.details});return data;
|
|
21
|
+
}
|
|
22
|
+
export async function session(config,fetchImpl=fetch){const result=await jsonRequest(config.authUrl+'/v1/auth/session',{token:config.sessionToken,fetchImpl});if(result.active!==true||!result.user?.enterpriseId)fail('AUTH_REQUIRED','账号授权已失效');return result.user;}
|
|
23
|
+
export function validateDaily(doc,project){
|
|
24
|
+
if(!doc||doc.format!=='project-daily-review-v1'||doc.project_id!==project||!['simulated','declared-real','unverified'].includes(doc.mode))fail('INVALID_DATA','需要带项目 ID 与资料性质的 project-daily-review-v1 文档');
|
|
25
|
+
if(!doc.config||typeof doc.config.metric!=='string'||!doc.config.metric||typeof doc.config.unit!=='string'||!doc.collection||typeof doc.collection.itemId!=='string'||!doc.collection.itemId)fail('INVALID_DATA','缺少指标、单位或平台商品编号');
|
|
26
|
+
if(!Array.isArray(doc.snapshots)||!doc.snapshots.length||doc.snapshots.length>10000)fail('INVALID_DATA','需要 1 至 10000 行日指标');
|
|
27
|
+
const dates=new Set();for(const row of doc.snapshots){if(!/^\d{4}-\d{2}-\d{2}$/.test(row.date)||new Date(row.date).toISOString().slice(0,10)!==row.date||dates.has(row.date)||typeof row.value!=='number'||!Number.isFinite(row.value)||!Number.isFinite(Date.parse(row.collectedAt)))fail('INVALID_DATA','日期、数值、采集时间不合法或日期重复');dates.add(row.date);}
|
|
28
|
+
return {format:doc.format,rows:doc.snapshots.length,mode:doc.mode};
|
|
29
|
+
}
|
|
30
|
+
export function validateDocument(doc,project){
|
|
31
|
+
if(doc?.format==='project-daily-review-v1')return validateDaily(doc,project);
|
|
32
|
+
if(doc?.project_id!==project||!['simulated','manual','real','declared-real','unverified'].includes(doc.mode))fail('INVALID_DATA','需要匹配的项目与资料性质');
|
|
33
|
+
if(doc.format==='product-incubation-v1'){if(typeof doc.itemId!=='string'||!['unassigned','test','incubate','scale'].includes(doc.tier)||!['simulated','declared-real','unverified'].includes(doc.dataMode))fail('INVALID_DATA','商品分组格式不完整');return {format:doc.format,rows:1,mode:doc.mode};}
|
|
34
|
+
if(doc.format==='growth-finance-v1'){if(!doc.start||!doc.end||!['shop','item'].includes(doc.scope?.type)||!doc.scope.id||doc.currency!=='CNY'||doc.revenueBasis!=='gross_paid'||doc.refundBasis!=='paid_order_cohort'||!doc.source||!doc.costPolicy||Object.values(doc.amounts||{}).some(v=>!/^\d{1,10}(\.\d{1,2})?$/.test(v)))fail('INVALID_DATA','核算文档的期间、范围、来源或金额格式不完整');return {format:doc.format,rows:1,mode:doc.mode};}
|
|
35
|
+
if(doc.format==='omni-shop-sales-v1'){if(!doc.shopId||!Array.isArray(doc.snapshots)||!doc.snapshots.length||doc.snapshots.some(r=>!/^\d{4}-\d{2}-\d{2}$/.test(r.date)||typeof r.paid!=='number'||r.paid<0||!Number.isFinite(r.paid)))fail('INVALID_DATA','店铺销售账本缺少店铺、日期或金额');return {format:doc.format,rows:doc.snapshots.length,mode:doc.mode};}
|
|
36
|
+
fail('UNSUPPORTED_SCHEMA','数据结构尚未支持,请查询 data schema');
|
|
37
|
+
}
|
|
38
|
+
export async function business(command,options,{fetchImpl=fetch}={}){
|
|
39
|
+
const config=connection(options),user=await session(config,fetchImpl);const call=(p,extra={})=>jsonRequest(config.dataServiceUrl+p,{token:config.sessionToken,fetchImpl,...extra});
|
|
40
|
+
if(command==='status')return {user,connected:true,profile:options.profile||config.profile||'auto'};
|
|
41
|
+
if(command==='shops')return call('/v1/enterprise/shops');
|
|
42
|
+
if(command==='projects')return call('/api/workbench');
|
|
43
|
+
if(!options.project||!/^[A-Za-z0-9_-]{1,100}$/.test(options.project))fail('INVALID_INPUT','需要明确 project ID');
|
|
44
|
+
const project='/api/workbench/'+encodeURIComponent(options.project);
|
|
45
|
+
if(command==='datasets')return call(project+'/datasets',options.shop?{shops:[options.shop]}:{});
|
|
46
|
+
if(command!=='write')fail('INVALID_COMMAND','不支持的业务操作');
|
|
47
|
+
if(!user.permissions?.writeData)fail('PERMISSION_REQUIRED','当前账号没有数据写入权限');
|
|
48
|
+
if(!options.shop||!/^[a-f0-9-]{36}$/i.test(options.shop))fail('INVALID_INPUT','写入需要明确 shop ID');
|
|
49
|
+
if(user.role!=='owner'&&!user.shopIds?.includes(options.shop))fail('PERMISSION_REQUIRED','当前账号没有该店铺权限');
|
|
50
|
+
if(!options.file||!options.source?.trim())fail('INVALID_INPUT','写入需要 file 和 source');
|
|
51
|
+
const stat=fs.statSync(options.file);if(!stat.isFile()||stat.size>1_800_000)fail('INVALID_DATA','输入须为 1.8MB 以内的 JSON 文件');const raw=fs.readFileSync(options.file),doc=JSON.parse(raw.toString('utf8'));const summary=validateDocument(doc,options.project);if(doc.shopId&&doc.shopId!==options.shop)fail('INVALID_DATA','文档店铺与目标不一致');const digest=sha(raw);
|
|
52
|
+
const shops=await call('/v1/enterprise/shops');if(!shops.shops.some(s=>s.id===options.shop))fail('PERMISSION_REQUIRED','目标店铺不可访问');await call(project);
|
|
53
|
+
if(options['dry-run'])return {validated:true,written:false,project:options.project,shop:options.shop,sha256:digest,...summary};
|
|
54
|
+
// A matching immutable source is reused. Unknown network outcomes must be inspected,
|
|
55
|
+
// never blindly retried; the server remains authoritative for transaction acceptance.
|
|
56
|
+
const current=await call(project+'/datasets',{shops:[options.shop]});const prior=current.datasets.find(d=>d.sha===digest);
|
|
57
|
+
if(prior)return {written:false,reused:true,id:prior.id,sha256:digest};
|
|
58
|
+
if(!options.yes)fail('PERMISSION_REQUIRED','写入需要 --yes,表示调用方已获得本次写入授权');
|
|
59
|
+
const result=await call(project+'/file',{method:'POST',shops:[options.shop],body:{name:path.basename(options.file),kind:'analysis',source:options.source,base64:raw.toString('base64')}});
|
|
60
|
+
const verified=await call(project+'/datasets',{shops:[options.shop]});const accepted=verified.datasets.find(d=>d.id===result.id&&d.sha===digest);if(!accepted)fail('OUTPUT_CONTRACT_FAILED','服务已返回写入结果,但数据回验失败,请先核查记录',{id:result.id});
|
|
61
|
+
return {written:true,verified:true,id:result.id,sha256:digest,...summary};
|
|
62
|
+
}
|
package/lib/database.mjs
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {privateJson,fail,sha,connection,session} from './core.mjs';
|
|
5
|
+
const {Client,escapeIdentifier:ident,escapeLiteral:literal}=pg;
|
|
6
|
+
const safe=value=>{if(typeof value!=='string'||!/^[a-z][a-z0-9_]{1,55}$/i.test(value))fail('INVALID_DATABASE_CONFIG','数据库与角色名不合法');return value;};
|
|
7
|
+
export async function initialize(options){
|
|
8
|
+
if(!options.yes||!options.file)fail('PERMISSION_REQUIRED','初始化需要明确私有配置文件及 --yes');
|
|
9
|
+
const account=await session(connection(options));if(!account.permissions.configureStorage)fail('PERMISSION_REQUIRED','当前账号没有数据库配置权限');
|
|
10
|
+
const input=privateJson(options.file);if(!input.host||!input.adminUsername||!input.adminPassword||!input.runtimePassword||input.runtimePassword.length<16)fail('INVALID_DATABASE_CONFIG','需要管理员连接与至少16位运行角色密码');
|
|
11
|
+
const database=safe(input.database),role=safe(input.runtimeUsername);if(role===input.adminUsername)fail('UNSAFE_DATABASE_ROLE','运行角色须独立于管理员');
|
|
12
|
+
const base={host:input.host,port:input.port||5432,user:input.adminUsername,password:input.adminPassword,ssl:input.sslMode==='disable'?false:{rejectUnauthorized:true},connectionTimeoutMillis:6000,statement_timeout:30000};
|
|
13
|
+
const admin=new Client({...base,database:'postgres'});let db;await admin.connect();
|
|
14
|
+
try{
|
|
15
|
+
if(!(await admin.query('SELECT 1 FROM pg_database WHERE datname=$1',[database])).rowCount)await admin.query(`CREATE DATABASE ${ident(database)}`);
|
|
16
|
+
db=new Client({...base,database});await db.connect();
|
|
17
|
+
const present=(await db.query("SELECT to_regclass('public.omni_schema_migrations') present")).rows[0].present;
|
|
18
|
+
if(!present&&(await db.query("SELECT 1 FROM pg_tables WHERE schemaname='public'")).rowCount)fail('DATABASE_NOT_EMPTY','目标包含其他数据,拒绝初始化');
|
|
19
|
+
if(present){const identity=(await db.query('SELECT enterprise_id FROM omni_tenant_identity WHERE singleton')).rows[0];if(identity?.enterprise_id!==account.enterpriseId)fail('TENANT_MISMATCH','目标数据库不属于当前企业');}
|
|
20
|
+
await db.query('BEGIN');
|
|
21
|
+
await db.query('CREATE TABLE IF NOT EXISTS omni_schema_migrations(version text PRIMARY KEY,sha256 text NOT NULL,applied timestamptz NOT NULL DEFAULT now())');
|
|
22
|
+
const directory=path.resolve(import.meta.dirname,'../schema');
|
|
23
|
+
for(const name of fs.readdirSync(directory).filter(n=>/^tenant-\d+\.sql$/.test(n)).sort()){
|
|
24
|
+
const sql=fs.readFileSync(path.join(directory,name),'utf8'),version=name.slice(0,-4),digest=sha(sql),old=(await db.query('SELECT sha256 FROM omni_schema_migrations WHERE version=$1',[version])).rows[0];
|
|
25
|
+
if(old){if(old.sha256!==digest)fail('MIGRATION_CHANGED','已有迁移校验和不一致');continue;}await db.query(sql);await db.query('INSERT INTO omni_schema_migrations(version,sha256) VALUES($1,$2)',[version,digest]);
|
|
26
|
+
}
|
|
27
|
+
await db.query('INSERT INTO omni_tenant_identity(singleton,enterprise_id) VALUES(true,$1) ON CONFLICT(singleton) DO NOTHING',[account.enterpriseId]);
|
|
28
|
+
const exists=(await db.query('SELECT rolsuper,rolbypassrls FROM pg_roles WHERE rolname=$1',[role])).rows[0];
|
|
29
|
+
if(exists){if(exists.rolsuper||exists.rolbypassrls)fail('UNSAFE_DATABASE_ROLE','已有运行角色权限过高');const runtime=new Client({...base,user:role,password:input.runtimePassword,database});try{await runtime.connect();const identity=(await runtime.query('SELECT enterprise_id FROM omni_tenant_identity')).rows[0];if(identity?.enterprise_id!==account.enterpriseId)fail('TENANT_MISMATCH','运行角色归属不匹配');}finally{await runtime.end();}}
|
|
30
|
+
else await db.query(`CREATE ROLE ${ident(role)} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS PASSWORD ${literal(input.runtimePassword)}`);
|
|
31
|
+
await db.query(`REVOKE ALL ON DATABASE ${ident(database)} FROM PUBLIC`);await db.query(`GRANT CONNECT ON DATABASE ${ident(database)} TO ${ident(role)}`);
|
|
32
|
+
await db.query('REVOKE CREATE ON SCHEMA public FROM PUBLIC');await db.query(`GRANT USAGE ON SCHEMA public TO ${ident(role)}`);await db.query(`GRANT SELECT,INSERT,UPDATE ON ALL TABLES IN SCHEMA public TO ${ident(role)}`);await db.query(`REVOKE INSERT,UPDATE,DELETE ON omni_schema_migrations FROM ${ident(role)}`);await db.query(`REVOKE INSERT,UPDATE ON omni_tenant_identity FROM ${ident(role)}`);await db.query(`GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA public TO ${ident(role)}`);await db.query('COMMIT');
|
|
33
|
+
return {initialized:true,enterpriseId:account.enterpriseId,database,runtimeUsername:role,schemaVersion:'tenant-004',dataMigrated:false};
|
|
34
|
+
}catch(error){if(db)await db.query('ROLLBACK').catch(()=>{});throw error;}finally{await db?.end();await admin.end();}
|
|
35
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import {createRequire} from 'node:module';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {spawnSync} from 'node:child_process';
|
|
6
|
+
import {randomUUID} from 'node:crypto';
|
|
7
|
+
import {sha,fail,privateJson} from './core.mjs';
|
|
8
|
+
const receiptName='.omni-managed.json';
|
|
9
|
+
const previousPackage='@petercjl/omni-cli';
|
|
10
|
+
export const root=path.resolve(import.meta.dirname,'..');
|
|
11
|
+
export const manifest=JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8'));
|
|
12
|
+
export function skillSource(name='omni-data'){if(!manifest.agentPackage.skills.includes(name))fail('SKILL_NOT_FOUND','包中没有该 Skill');return path.join(root,'skills',name);}
|
|
13
|
+
export const source=skillSource();
|
|
14
|
+
function tree(directory,prefix=''){const result={};for(const item of fs.readdirSync(directory,{withFileTypes:true})){const name=prefix+item.name;if(item.isSymbolicLink())fail('UNSAFE_SOURCE','包内容不能包含符号链接');if(item.isDirectory())Object.assign(result,tree(path.join(directory,item.name),name+'/'));else if(item.isFile())result[name]=fs.readFileSync(path.join(directory,item.name));}return result;}
|
|
15
|
+
export function packageFiles(){
|
|
16
|
+
const files={'package.json':fs.readFileSync(path.join(root,'package.json'))};
|
|
17
|
+
for(const name of ['bin','lib','skills','schema'])for(const [rel,bytes] of Object.entries(tree(path.join(root,name))))files[name+'/'+rel]=bytes;
|
|
18
|
+
for(const name of ['capabilities.json','README.md','INSTALL.md','UPDATE.md'])files[name]=fs.readFileSync(path.join(root,name));
|
|
19
|
+
const seen=new Map();
|
|
20
|
+
function dependency(name,from){const require=createRequire(path.join(from,'package.json'));let directory=path.dirname(require.resolve(name));while(directory!==path.dirname(directory)){const file=path.join(directory,'package.json');if(fs.existsSync(file)&&JSON.parse(fs.readFileSync(file,'utf8')).name===name)break;directory=path.dirname(directory);}const pkg=JSON.parse(fs.readFileSync(path.join(directory,'package.json'),'utf8'));if(seen.has(name)){if(seen.get(name)!==pkg.version)fail('DEPENDENCY_CONFLICT','运行时依赖版本冲突');return;}seen.set(name,pkg.version);for(const [rel,bytes]of Object.entries(tree(directory))){if(rel.startsWith('node_modules/'))continue;files['node_modules/'+name+'/'+rel]=bytes;}for(const child of Object.keys(pkg.dependencies||{}))dependency(child,directory);}
|
|
21
|
+
for(const name of Object.keys(manifest.dependencies||{}))dependency(name,root);
|
|
22
|
+
return files;
|
|
23
|
+
}
|
|
24
|
+
export function targetOf(options){if(typeof options.agent!=='string'||!/^[a-z][a-z0-9-]{0,63}$/.test(options.agent))fail('INVALID_AGENT','请明确当前 Agent 的有效名称');if(!options.target||!path.isAbsolute(options.target))fail('TARGET_REQUIRED','当前 Agent 必须提供自己已解析的绝对 Skill 目录 --target');const target=path.resolve(options.target),ownRuntime=root===path.join(target,'.runtime');if(target===path.parse(target).root||target===os.homedir()||target===root||target.startsWith(root+path.sep)||(root.startsWith(target+path.sep)&&!ownRuntime))fail('UNSAFE_TARGET','Skill 目标不能覆盖包源码或用户根目录');return target;}
|
|
25
|
+
export function status(options){
|
|
26
|
+
const name=options.name||'omni-data',source=skillSource(name),target=targetOf(options),base={ok:true,name,package:manifest.name,version:manifest.version,target,installed:false,managed:false,current:false,edited:[],verification:{verified:false,algorithm:'sha256'},recovery:{required:false},hostDiscovery:{authority:'host',status:'pending'}};
|
|
27
|
+
if(!fs.existsSync(target))return base;
|
|
28
|
+
if(fs.lstatSync(target).isSymbolicLink()||!fs.lstatSync(target).isDirectory())fail('UNMANAGED_TARGET','目标须为独立普通目录');
|
|
29
|
+
const file=path.join(target,receiptName);if(!fs.existsSync(file))fail('UNMANAGED_TARGET','目标已有非托管内容,已保留');
|
|
30
|
+
const receipt=JSON.parse(fs.readFileSync(file,'utf8'));if((receipt.name||'omni-data')!==name||![manifest.name,previousPackage].includes(receipt.package)||receipt.agent!==options.agent||receipt.target!==target||!receipt.hashes||typeof receipt.hashes!=='object')fail('UNMANAGED_TARGET','目标归属或回执不匹配');
|
|
31
|
+
const missing=[],edited=[];for(const [name,digest] of Object.entries(receipt.hashes)){const p=path.resolve(target,name);if(!p.startsWith(target+path.sep))fail('INVALID_RECEIPT','回执路径越界');if(!fs.existsSync(p)){missing.push(name);continue;}const stat=fs.lstatSync(p);if(!stat.isFile()||stat.isSymbolicLink()||sha(fs.readFileSync(p))!==digest)edited.push(name);}
|
|
32
|
+
const actual=tree(target);const foreign=Object.keys(actual).filter(name=>name!==receiptName&&!receipt.hashes[name]&&!name.startsWith('agents/'));
|
|
33
|
+
const expected=Object.fromEntries(Object.entries(tree(source)).filter(([n])=>!n.startsWith('agents/')).map(([n,v])=>[n,sha(v)]));for(const [n,d]of Object.entries(packageFiles()))expected['.runtime/'+n]=sha(d);
|
|
34
|
+
const current=!missing.length&&!edited.length&&!foreign.length&&receipt.package===manifest.name&&receipt.version===manifest.version&&JSON.stringify(Object.entries(receipt.hashes).sort())===JSON.stringify(Object.entries(expected).sort());
|
|
35
|
+
return {...base,installed:true,managed:true,current,edited:[...edited,...foreign],missing,installedPackage:receipt.package,installedVersion:receipt.version,verification:{verified:!missing.length&&!edited.length&&!foreign.length,algorithm:'sha256'},runtimeEntry:path.join(target,'.runtime','bin','omni.mjs')};
|
|
36
|
+
}
|
|
37
|
+
export function install(options){
|
|
38
|
+
const source=skillSource(options.name);const prior=status(options);if(prior.edited.length)fail('LOCAL_EDITS','托管内容已被本地修改,已保留',{edited:prior.edited});if(prior.current)return {...prior,changed:false};
|
|
39
|
+
const target=prior.target,parent=path.dirname(target);fs.mkdirSync(parent,{recursive:true});const lock=target+'.omni-lock';let fd;try{fd=fs.openSync(lock,'wx',0o600);}catch{fail('LOCKED','该目标正在维护;请先检查原操作');}
|
|
40
|
+
let stage,backup,replaced;
|
|
41
|
+
try{
|
|
42
|
+
const again=status(options);if(again.edited.length)fail('LOCAL_EDITS','目标已在检查后变化');
|
|
43
|
+
stage=fs.mkdtempSync(path.join(parent,'.omni-stage-'));const content=tree(source);for(const[n,bytes]of Object.entries(packageFiles()))content['.runtime/'+n]=bytes;
|
|
44
|
+
const hashes={};for(const[name,bytes]of Object.entries(content)){const file=path.join(stage,name);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,bytes,{flag:'wx',mode:name.endsWith('.mjs')?0o755:0o644});if(!name.startsWith('agents/'))hashes[name]=sha(bytes);}
|
|
45
|
+
if(prior.installed&&fs.existsSync(path.join(target,'agents'))){fs.cpSync(path.join(target,'agents'),path.join(stage,'agents'),{recursive:true,dereference:false});}
|
|
46
|
+
fs.writeFileSync(path.join(stage,receiptName),JSON.stringify({name:options.name||'omni-data',package:manifest.name,version:manifest.version,agent:options.agent,target,hashes},null,2),{flag:'wx',mode:0o600});
|
|
47
|
+
if(fs.existsSync(target)){const backupRoot=path.join(parent,'.omni-backups');fs.mkdirSync(backupRoot,{recursive:true,mode:0o700});backup=path.join(backupRoot,randomUUID());fs.cpSync(target,backup,{recursive:true,errorOnExist:true,force:false});try{replaced=path.join(parent,'.omni-replaced-'+randomUUID());fs.renameSync(target,replaced);}catch(error){if(!['EPERM','EACCES','EBUSY'].includes(error.code))throw error;replaced=null;for(const[name,bytes]of Object.entries(content)){if(name.startsWith('agents/'))continue;const file=path.join(target,name);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,bytes);}fs.copyFileSync(path.join(stage,receiptName),path.join(target,receiptName));fs.rmSync(stage,{recursive:true});stage=null;}}
|
|
48
|
+
if(stage)fs.renameSync(stage,target);
|
|
49
|
+
const checked=status(options);if(!checked.current)fail('VERIFY_FAILED','安装回验未通过',{backup});if(replaced)fs.rmSync(replaced,{recursive:true});return {...checked,changed:true,backup:backup||null,...(again.installedPackage===previousPackage?{migratedFrom:previousPackage}:{})};
|
|
50
|
+
}finally{fs.closeSync(fd);fs.unlinkSync(lock);}
|
|
51
|
+
}
|
|
52
|
+
function cacheRoot(){return process.env.OMNI_CLI_STATE_DIR||path.join(os.homedir(),'.omni-cli');}
|
|
53
|
+
export function recoverInstall(options){
|
|
54
|
+
const prior=status(options);if(prior.edited.length)fail('LOCAL_EDITS','恢复前检测到本地修改,已保留');
|
|
55
|
+
if(!options.yes)fail('PERMISSION_REQUIRED','恢复安装需要 --yes');
|
|
56
|
+
if(!options.candidate||!path.isAbsolute(options.candidate))fail('CANDIDATE_REQUIRED','请提供原操作返回的绝对 candidate 路径');
|
|
57
|
+
const candidate=path.resolve(options.candidate),relative=path.relative(cacheRoot(),candidate);
|
|
58
|
+
const [stage,...rest]=relative.split(path.sep);
|
|
59
|
+
if(!/^candidate-.+$/.test(stage)||rest.join('/')!=='node_modules/'+manifest.name||!fs.existsSync(candidate)||fs.realpathSync(candidate)!==path.join(fs.realpathSync(cacheRoot()),relative))fail('INVALID_CANDIDATE','恢复仅接受原更新缓存中的普通候选包');
|
|
60
|
+
const pkg=JSON.parse(fs.readFileSync(path.join(candidate,'package.json')));
|
|
61
|
+
if(pkg.name!==manifest.name||!/^\d+\.\d+\.\d+$/.test(pkg.version))fail('VERSION_MISMATCH','候选身份不匹配');
|
|
62
|
+
const out=spawnSync(process.execPath,[path.join(candidate,'bin/omni.mjs'),'skill','update','--name',options.name||'omni-data','--target',prior.target,'--agent',options.agent,'--json'],{encoding:'utf8',timeout:30000});
|
|
63
|
+
if(out.status!==0)fail('SKILL_SYNC_FAILED','候选恢复失败,原安装与候选保留',{candidate});
|
|
64
|
+
return {...JSON.parse(out.stdout),recovered:true,candidate};
|
|
65
|
+
}
|
|
66
|
+
export function updateNotification(result){
|
|
67
|
+
const next={...result};
|
|
68
|
+
delete next.notice;delete next.action;delete next.confirmationRequired;
|
|
69
|
+
if(next.checked&&next.published&&/^\d+\.\d+\.\d+$/.test(next.latest||'')){
|
|
70
|
+
const current=manifest.version.split('.').map(Number),latest=next.latest.split('.').map(Number);
|
|
71
|
+
const index=latest.findIndex((part,i)=>part!==current[i]);
|
|
72
|
+
next.available=index>=0&&latest[index]>current[index];
|
|
73
|
+
}
|
|
74
|
+
if(next.available&&next.checked){
|
|
75
|
+
next.notice=`山海 OMNI 插件有新版本 ${next.latest}。确认后由当前 Agent 更新插件及配套 Skill;本次继续使用当前版本。`;
|
|
76
|
+
next.action='ask-user-before-update';next.confirmationRequired=true;
|
|
77
|
+
}
|
|
78
|
+
return next;
|
|
79
|
+
}
|
|
80
|
+
export async function checkUpdate({automatic=false}={}){
|
|
81
|
+
if(automatic&&process.env.OMNI_UPDATE_CHECK==='0')return {checked:false,reason:'disabled'};
|
|
82
|
+
const dir=cacheRoot();fs.mkdirSync(dir,{recursive:true,mode:0o700});const file=path.join(dir,'update-lumyne.json');let old;
|
|
83
|
+
if(fs.existsSync(file)){old=privateJson(file);if(typeof old.checkedAt!=='number')fail('INVALID_UPDATE_CACHE','更新缓存需要维护检查');if(automatic&&Date.now()-old.checkedAt<86400000)return updateNotification({...old,cached:true});}
|
|
84
|
+
let fd;try{fd=fs.openSync(path.join(dir,'update.lock'),'wx',0o600);}catch{return {checked:false,reason:'in-progress'};}
|
|
85
|
+
try{
|
|
86
|
+
let result;try{const response=await fetch('https://registry.npmjs.org/'+encodeURIComponent(manifest.name)+'/latest',{signal:AbortSignal.timeout(1800),redirect:'error'});if(response.status===404)result={checked:true,published:false};else{if(!response.ok)throw Error();const pkg=await response.json();if(!/^\d+\.\d+\.\d+$/.test(pkg.version))throw Error();result={checked:true,published:true,latest:pkg.version,available:pkg.version.split('.').reduce((n,v,i)=>n+Number(v)*1000000**(2-i),0)>manifest.version.split('.').reduce((n,v,i)=>n+Number(v)*1000000**(2-i),0)};}}catch{result={checked:false,reason:'registry-unavailable',retained:true};}
|
|
87
|
+
result.checkedAt=Date.now();if(old)fs.copyFileSync(file,path.join(dir,'update.previous-'+randomUUID()+'.json'),fs.constants.COPYFILE_EXCL);fs.writeFileSync(file,JSON.stringify(result),{mode:0o600});return updateNotification(result);
|
|
88
|
+
}finally{fs.closeSync(fd);fs.unlinkSync(path.join(dir,'update.lock'));}
|
|
89
|
+
}
|
|
90
|
+
export function updateInstall(options){
|
|
91
|
+
const prior=status(options);if(prior.edited.length)fail('LOCAL_EDITS','更新前检测到本地修改,已保留');if(!options.yes)fail('PERMISSION_REQUIRED','更新安装需要 --yes');
|
|
92
|
+
if(!/^\d+\.\d+\.\d+$/.test(options.version||''))fail('VERSION_REQUIRED','更新需提供经核实的精确 --version');
|
|
93
|
+
const dir=cacheRoot();fs.mkdirSync(dir,{recursive:true,mode:0o700});const stage=fs.mkdtempSync(path.join(dir,'candidate-'));const candidates=[process.env.npm_execpath,path.join(path.dirname(process.execPath),'node_modules/npm/bin/npm-cli.js'),path.join(path.dirname(process.execPath),'../lib/node_modules/npm/bin/npm-cli.js')].filter(Boolean);if(process.platform!=='win32'){for(const dir of (process.env.PATH||'').split(path.delimiter)){const file=path.join(dir,'npm');if(fs.existsSync(file))candidates.push(fs.realpathSync(file));}}const npmEntry=candidates.find(file=>/npm-cli\.js$/.test(file)&&fs.existsSync(file));if(!npmEntry)fail('DEPENDENCY_MISSING','需要当前 Node.js 环境可执行的 npm CLI');
|
|
94
|
+
const result=spawnSync(process.execPath,[npmEntry,'install','--prefix',stage,'--ignore-scripts','--no-audit','--no-fund',options.tarball||manifest.name+'@'+options.version],{encoding:'utf8',timeout:120000});
|
|
95
|
+
if(result.status!==0)fail('PACKAGE_ACQUISITION_FAILED','候选包获取失败,原安装保留',{candidate:stage});
|
|
96
|
+
const candidate=path.join(stage,'node_modules',...manifest.name.split('/'));const pkg=JSON.parse(fs.readFileSync(path.join(candidate,'package.json'),'utf8'));if(pkg.version!==options.version||pkg.name!==manifest.name)fail('VERSION_MISMATCH','候选版本不匹配');
|
|
97
|
+
const out=spawnSync(process.execPath,[path.join(candidate,'bin','omni.mjs'),'skill','update','--name',options.name||'omni-data','--target',prior.target,'--agent',options.agent,'--json'],{encoding:'utf8',timeout:30000});
|
|
98
|
+
if(out.status!==0)fail('SKILL_SYNC_FAILED','候选已获取,Skill 同步失败;保留原安装与候选以便恢复',{candidate});return {...JSON.parse(out.stdout),candidate,activation:'selected-skill-runtime',bootstrapRetained:true};
|
|
99
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {status,manifest} from './lifecycle.mjs';
|
|
5
|
+
import {connection,session,privateJson,fail} from './core.mjs';
|
|
6
|
+
|
|
7
|
+
export function verifyAgentSetup(options){
|
|
8
|
+
const targets={'omni-data':options['data-skill-target'],'omni-project':options['project-skill-target']};
|
|
9
|
+
if(!Object.values(targets).some(Boolean))return undefined; // Existing binding challenges retain their original contract.
|
|
10
|
+
const skills=Object.entries(targets).map(([name,target])=>{
|
|
11
|
+
if(!target)fail('SETUP_REQUIRED','需要提供两份配套 Skill 的实际安装目录');
|
|
12
|
+
const result=status({agent:options.agent,name,target});
|
|
13
|
+
if(!result.current||!result.verification.verified)fail('SETUP_REQUIRED','请先完整安装并校验配套 Skill',{skill:name});
|
|
14
|
+
return {name,current:true,version:result.installedVersion};
|
|
15
|
+
});
|
|
16
|
+
return {package:manifest.name,version:manifest.version,skills};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function confirmLocalAgent(options,{fetchImpl=fetch}={}){
|
|
20
|
+
const setup=verifyAgentSetup(options);
|
|
21
|
+
await session(connection(options),fetchImpl);
|
|
22
|
+
const base=process.platform==='darwin'?path.join(os.homedir(),'Library/Application Support'):process.platform==='win32'?process.env.APPDATA:path.join(os.homedir(),'.config');
|
|
23
|
+
const directories=options.config?[path.dirname(path.resolve(options.config))]:options.profile?[path.join(base,options.profile==='dev'?'Shanhai OMNI Dev':'Shanhai OMNI')]:['Shanhai OMNI Dev','Shanhai OMNI'].map(n=>path.join(base,n)).filter(p=>fs.existsSync(path.join(p,'agent-connection.json')));
|
|
24
|
+
if(directories.length!==1)fail('PROFILE_REQUIRED','请指定山海连接 profile');
|
|
25
|
+
const file=path.join(directories[0],'project-agent-host.json');if(!fs.existsSync(file))fail('DESKTOP_REQUIRED','请打开对应山海桌面并发起绑定');
|
|
26
|
+
const host=privateJson(file);if(host.owner!=='omni-project-agent-host'||host.version!==1||!Number.isInteger(host.port)||host.port<1||host.port>65535||!Number.isInteger(host.pid)||!/^[a-f0-9]{64}$/.test(host.token))fail('INVALID_CONFIG','本机绑定端点无效');
|
|
27
|
+
try{process.kill(host.pid,0);}catch{fail('DESKTOP_REQUIRED','绑定端点已过期,请重新打开山海');}
|
|
28
|
+
const response=await fetchImpl(`http://127.0.0.1:${host.port}/confirm`,{method:'POST',redirect:'error',signal:AbortSignal.timeout(5000),headers:{Authorization:'Bearer '+host.token,'Content-Type':'application/json'},body:JSON.stringify({agent:options.agent,challenge:options.challenge,conversationId:options['conversation-id'],...(setup?{setup}:{})})});
|
|
29
|
+
const value=await response.json();if(!response.ok||!value.ok)fail(value.code||'BINDING_FAILED',value.error||'绑定失败');return value;
|
|
30
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {connection,session,jsonRequest,fail,privateJson} from './core.mjs';
|
|
4
|
+
export async function manage(command,options,{fetchImpl=fetch}={}){
|
|
5
|
+
const config=connection(options),user=await session(config,fetchImpl);const call=(p,extra={})=>jsonRequest(config.dataServiceUrl+p,{token:config.sessionToken,fetchImpl,...extra});
|
|
6
|
+
if(command==='data schema')return call('/v1/enterprise/schema');
|
|
7
|
+
if(command==='database status'||command==='database check')return call('/v1/enterprise/storage');
|
|
8
|
+
if(command==='shop list')return call('/v1/enterprise/shops');
|
|
9
|
+
if(command==='product list')return call('/v1/enterprise/products');
|
|
10
|
+
if(command==='member list')return call('/v1/enterprise/members');
|
|
11
|
+
if(command==='data read'){
|
|
12
|
+
if(!/^[\w-]{1,100}$/.test(options.project||'')||!/^[\w-]{1,100}$/.test(options.dataset||''))fail('INVALID_INPUT','读取明细需要 project 和 dataset ID');
|
|
13
|
+
const page=Number(options.page||1);if(!Number.isInteger(page)||page<1)fail('INVALID_INPUT','page 须为正整数');
|
|
14
|
+
return call(`/api/workbench/${options.project}/datasets/${options.dataset}?page=${page}`,options.shop?{shops:[options.shop]}:{});
|
|
15
|
+
}
|
|
16
|
+
if(!options.file)fail('INVALID_INPUT','需要 --file 指向明确的 JSON 输入文件');
|
|
17
|
+
const secret=command.startsWith('database')||command.startsWith('member');const body=secret?privateJson(options.file):JSON.parse(fs.readFileSync(options.file,'utf8'));
|
|
18
|
+
if(command==='database configure'||command==='database validate'){
|
|
19
|
+
if(!user.permissions.configureStorage)fail('PERMISSION_REQUIRED','当前账号没有数据库配置权限');
|
|
20
|
+
const current=await call('/v1/enterprise/storage');
|
|
21
|
+
const dry=options['dry-run']||command==='database validate';if(!dry&&!options.yes)fail('PERMISSION_REQUIRED','激活数据库配置需要 --yes');
|
|
22
|
+
return call('/v1/enterprise/storage/'+(dry?'validate':'configure'),{method:'POST',body:{...body,expectedRevision:options['expected-revision']===undefined?current.revision:Number(options['expected-revision'])}});
|
|
23
|
+
}
|
|
24
|
+
if(!options.yes)fail('PERMISSION_REQUIRED','本次写操作需要 --yes');
|
|
25
|
+
if(command==='project create')return call('/api/workbench',{method:'POST',body:{name:body.name,simulated:body.mode==='simulated'}});
|
|
26
|
+
if(command==='project update'){if(!/^[\w-]{1,100}$/.test(body.id||''))fail('INVALID_INPUT','更新项目需要 id');return call('/v1/enterprise/projects/'+body.id,{method:'POST',body:{name:body.name}});}
|
|
27
|
+
if(command==='shop create')return call('/v1/enterprise/shops',{method:'POST',body});
|
|
28
|
+
if(command==='shop update'){
|
|
29
|
+
if(!/^[a-f0-9-]{36}$/i.test(body.id||''))fail('INVALID_INPUT','更新店铺需要 id');
|
|
30
|
+
return call('/v1/enterprise/shops/'+body.id,{method:'POST',body});
|
|
31
|
+
}
|
|
32
|
+
if(command==='member create')return call('/v1/enterprise/members',{method:'POST',body});
|
|
33
|
+
if(command==='member update'){if(!/^[a-f0-9-]{36}$/i.test(body.id||''))fail('INVALID_INPUT','成员更新需要 id');return call('/v1/enterprise/members/'+body.id,{method:'POST',body});}
|
|
34
|
+
if(command==='product save'){
|
|
35
|
+
const products=await call('/v1/enterprise/products');const product=products.products.find(p=>p.project_id===body.projectId);if(!product)fail('PROJECT_NOT_FOUND','当前账号无法访问该项目');
|
|
36
|
+
const payload={...body,productId:product.product_id};delete payload.projectId;delete payload.imageFile;
|
|
37
|
+
if(body.imageFile){const file=path.resolve(path.dirname(path.resolve(options.file)),body.imageFile),stat=fs.statSync(file);if(!stat.isFile()||stat.size>350000)fail('INVALID_IMAGE','商品图片须为 350KB 内的文件');const raw=fs.readFileSync(file);const mime=raw[0]===0xff&&raw[1]===0xd8?'image/jpeg':raw.subarray(0,8).toString('hex')==='89504e470d0a1a0a'?'image/png':raw.subarray(0,4).toString()==='RIFF'&&raw.subarray(8,12).toString()==='WEBP'?'image/webp':null;if(!mime)fail('INVALID_IMAGE','商品图片须为 JPEG、PNG 或 WebP');payload.imageDataUrl=`data:${mime};base64,${raw.toString('base64')}`;}
|
|
38
|
+
const result=await call('/v1/enterprise/listings',{method:'POST',body:payload,shops:[body.shopId]});
|
|
39
|
+
const check=await call('/v1/enterprise/products');if(!check.listings.some(l=>l.id===result.id&&l.platform_item_id===body.itemId&&l.title===body.title))fail('OUTPUT_CONTRACT_FAILED','商品资料保存后回验失败',{id:result.id});return {...result,verified:true};
|
|
40
|
+
}
|
|
41
|
+
fail('INVALID_COMMAND','不支持的管理操作');
|
|
42
|
+
}
|
package/lib/market.mjs
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import {connection, fail, jsonRequest} from './core.mjs';
|
|
2
|
+
|
|
3
|
+
const monthPattern = /^\d{4}-(0[1-9]|1[0-2])$/;
|
|
4
|
+
const idPattern = /^\d{1,20}$/;
|
|
5
|
+
const pageOptions = {page: 'page', 'page-size': 'pageSize'};
|
|
6
|
+
const rankingOptions = {
|
|
7
|
+
...pageOptions, category: 'categoryId', month: 'month', query: 'q',
|
|
8
|
+
sort: 'sort', direction: 'direction', 'recent-year': 'recentYear',
|
|
9
|
+
};
|
|
10
|
+
const priceOptions = {'min-price': 'minPrice', 'max-price': 'maxPrice'};
|
|
11
|
+
const opportunityOptions = {
|
|
12
|
+
...pageOptions, category: 'categoryId', month: 'month', query: 'q', sort: 'sort',
|
|
13
|
+
'min-growth': 'minGrowth', 'min-sales': 'minSales', 'min-base': 'minBase',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function required(value, pattern, label) {
|
|
17
|
+
if (!pattern.test(value ?? '')) fail('INVALID_ARGUMENT', label + '格式不正确或未提供');
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function boundedText(value, length, label) {
|
|
22
|
+
const query = value?.trim();
|
|
23
|
+
if (!query || query.length > length || /[\x00-\x1f]/.test(query))
|
|
24
|
+
fail('INVALID_ARGUMENT', label + '为空或格式不正确');
|
|
25
|
+
return query;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function pathFor(row, categories) {
|
|
29
|
+
const path = [];
|
|
30
|
+
const visited = new Set();
|
|
31
|
+
for (let node = row; node && !visited.has(node.id); node = categories.get(node.parentId)) {
|
|
32
|
+
visited.add(node.id);
|
|
33
|
+
path.unshift({id: node.id, name: node.name});
|
|
34
|
+
}
|
|
35
|
+
return path;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function previousMonth(month) {
|
|
39
|
+
const [year, number] = month.split('-').map(Number);
|
|
40
|
+
return number === 1
|
|
41
|
+
? String(year - 1).padStart(4, '0') + '-12'
|
|
42
|
+
: month.slice(0, 5) + String(number - 1).padStart(2, '0');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function withGrowth(row, previous, categories) {
|
|
46
|
+
const current = row.sales ?? null;
|
|
47
|
+
const base = previous?.sales ?? null;
|
|
48
|
+
const comparisonStatus = current === null || row.availableMonths !== 1 ? 'missing-current'
|
|
49
|
+
: base === null || previous.availableMonths !== 1 ? 'missing-base'
|
|
50
|
+
: base === 0 ? 'zero-base'
|
|
51
|
+
: !Number.isFinite(current) || !Number.isFinite(base) || current < 0 || base < 0 ? 'invalid-sales'
|
|
52
|
+
: 'comparable';
|
|
53
|
+
return {
|
|
54
|
+
...row, path: pathFor(row, categories), previousSales: base, comparisonStatus,
|
|
55
|
+
salesMom: comparisonStatus === 'comparable' ? (current / base - 1) * 100 : null,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function readBootstrap(request) {
|
|
60
|
+
const data = await request('bootstrap');
|
|
61
|
+
if (data.status === 'no-access') fail('PERMISSION_REQUIRED', '当前企业未获市场类目授权');
|
|
62
|
+
if (data.status === 'unpublished') fail('MARKET_UNPUBLISHED', '市场数据尚未开放');
|
|
63
|
+
if (data.status !== 'ready' || !Array.isArray(data.categories))
|
|
64
|
+
fail('INVALID_RESPONSE', '市场类目返回合同不匹配');
|
|
65
|
+
return data;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function categorySearch(options, request) {
|
|
69
|
+
const query = boundedText(options.query, 120, '类目关键词').normalize('NFKC').toLocaleLowerCase('zh-CN');
|
|
70
|
+
const page = Number(options.page ?? 1);
|
|
71
|
+
const pageSize = Number(options['page-size'] ?? 25);
|
|
72
|
+
if (!Number.isInteger(page) || page < 1 || page > 10000 || ![25, 50, 100].includes(pageSize))
|
|
73
|
+
fail('INVALID_ARGUMENT', '类目搜索分页不正确');
|
|
74
|
+
const {categories, months, latestCategoryMonth, sourceLabel, batchStatus} = await readBootstrap(request);
|
|
75
|
+
const categoryIndex = new Map(categories.map(row => [row.id, row]));
|
|
76
|
+
const matches = categories.filter(row => row.id === query ||
|
|
77
|
+
row.name.normalize('NFKC').toLocaleLowerCase('zh-CN').includes(query));
|
|
78
|
+
return {
|
|
79
|
+
query, page, pageSize, total: matches.length, months, latestCategoryMonth, sourceLabel, batchStatus,
|
|
80
|
+
rows: matches.slice((page - 1) * pageSize, page * pageSize)
|
|
81
|
+
.map(row => ({...row, path: pathFor(row, categoryIndex)})),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function categoryOverview(options, request) {
|
|
86
|
+
const bootstrap = await readBootstrap(request);
|
|
87
|
+
const month = options.month ?? bootstrap.latestCategoryMonth;
|
|
88
|
+
if (!month) fail('MARKET_MONTH_UNAVAILABLE', '当前授权范围没有已入库的类目统计月份');
|
|
89
|
+
required(month, monthPattern, '月份');
|
|
90
|
+
const categoryId = options.category === undefined ? '' : required(options.category, idPattern, '类目 ID');
|
|
91
|
+
const categories = new Map(bootstrap.categories.map(row => [row.id, row]));
|
|
92
|
+
const category = categories.get(categoryId);
|
|
93
|
+
if (categoryId && !category) fail('PERMISSION_REQUIRED', '该类目未获授权或不可访问');
|
|
94
|
+
const baseMonth = previousMonth(month);
|
|
95
|
+
const dashboard = (id, selectedMonth) => request('dashboard', {view: 'categories', categoryId: id, month: selectedMonth});
|
|
96
|
+
const compare = async id => {
|
|
97
|
+
if (!bootstrap.months?.includes(baseMonth)) return {categories: []};
|
|
98
|
+
try {
|
|
99
|
+
return await dashboard(id, baseMonth);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error.code === 'MARKET_MONTH_UNAVAILABLE') return {categories: []};
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const [current, previous, parent, previousParent] = await Promise.all([
|
|
106
|
+
dashboard(categoryId, month), compare(categoryId),
|
|
107
|
+
category ? dashboard(category.parentId ?? '', month) : null,
|
|
108
|
+
category ? compare(category.parentId ?? '') : null,
|
|
109
|
+
]);
|
|
110
|
+
const previousRows = new Map(previous.categories.map(row => [row.id, row]));
|
|
111
|
+
const selected = parent?.categories.find(row => row.id === categoryId);
|
|
112
|
+
return {
|
|
113
|
+
month, comparisonMonth: baseMonth, period: current.period, provenance: current.provenance,
|
|
114
|
+
selected: selected ? withGrowth(selected, previousParent.categories.find(row => row.id === categoryId), categories) : null,
|
|
115
|
+
trend: current.trend, rows: current.categories.map(row => withGrowth(row, previousRows.get(row.id), categories)),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function selectParams(options, mapping) {
|
|
120
|
+
return Object.fromEntries(Object.entries(mapping)
|
|
121
|
+
.filter(([flag]) => options[flag] !== undefined)
|
|
122
|
+
.map(([flag, param]) => [param, options[flag]]));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function dashboardQuery(options, view, extra = {}) {
|
|
126
|
+
required(options.category, idPattern, '类目 ID');
|
|
127
|
+
required(options.month, monthPattern, '月份');
|
|
128
|
+
return {view, pageSize: 25, ...selectParams(options, {...rankingOptions, ...extra})};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const recordKey = options => encodeURIComponent(required(options.key, /^[A-Za-z0-9_-]{1,1024}$/, '榜单记录键'));
|
|
132
|
+
|
|
133
|
+
const operations = {
|
|
134
|
+
'market category search': categorySearch,
|
|
135
|
+
'market category overview': categoryOverview,
|
|
136
|
+
'market ranking products': (o, request) => request('dashboard', dashboardQuery(o, 'products', priceOptions)),
|
|
137
|
+
'market ranking shops': (o, request) => request('dashboard', dashboardQuery(o, 'shops')),
|
|
138
|
+
'market record get': (o, request) => request('records/' + recordKey(o)),
|
|
139
|
+
'market opportunity markets': (o, request) => opportunity('markets', o, request),
|
|
140
|
+
'market opportunity products': (o, request) => opportunity('products', o, request),
|
|
141
|
+
'market price distribution': async (o, request) => {
|
|
142
|
+
const categoryId = required(o.category, idPattern, '类目 ID');
|
|
143
|
+
const month = required(o.month, monthPattern, '月份');
|
|
144
|
+
return {...await request('price-distribution', {categoryId, month}), categoryId, month};
|
|
145
|
+
},
|
|
146
|
+
'market shop categories': async (o, request) => {
|
|
147
|
+
if (o.key !== undefined) {
|
|
148
|
+
if (o.shops !== undefined || o.month !== undefined || o.category !== undefined || o['recent-year'])
|
|
149
|
+
fail('INVALID_ARGUMENT', '记录键模式只需要 --key');
|
|
150
|
+
return request('shop-categories/' + recordKey(o));
|
|
151
|
+
}
|
|
152
|
+
const shops = o.shops?.split(',') ?? [];
|
|
153
|
+
if (shops.length < 1 || shops.length > 3 || new Set(shops).size !== shops.length ||
|
|
154
|
+
shops.some(id => !idPattern.test(id)))
|
|
155
|
+
fail('INVALID_ARGUMENT', '--shops 需要一至三个不同的店铺 ID,以逗号分隔');
|
|
156
|
+
const month = required(o.month, monthPattern, '月份');
|
|
157
|
+
return request('shop-categories', {view: 'shop-layout', shops: o.shops, month,
|
|
158
|
+
...selectParams(o, {category: 'category', 'recent-year': 'recentYear'})});
|
|
159
|
+
},
|
|
160
|
+
'market favorite list': async (o, request) => {
|
|
161
|
+
if (o.kind && !['category', 'product', 'shop'].includes(o.kind)) fail('INVALID_ARGUMENT', '收藏类型不正确');
|
|
162
|
+
const result = await request('favorites');
|
|
163
|
+
return o.kind ? {...result, kind: o.kind, entries: result.entries.filter(entry => entry.kind === o.kind)} : result;
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
async function opportunity(kind, options, request) {
|
|
168
|
+
if (options.month !== undefined || kind === 'products') required(options.month, monthPattern, '月份');
|
|
169
|
+
if (options.category !== undefined || kind === 'products') required(options.category, idPattern, '类目 ID');
|
|
170
|
+
const bootstrap = await readBootstrap(request);
|
|
171
|
+
if (bootstrap.capabilities?.opportunities !== true)
|
|
172
|
+
fail('FEATURE_UNSUPPORTED', '中央市场服务暂未开放机会发现');
|
|
173
|
+
const params = selectParams(options, kind === 'markets'
|
|
174
|
+
? {...opportunityOptions, 'max-shops': 'maxShops'} : opportunityOptions);
|
|
175
|
+
return request('dashboard', {view: 'opportunities', kind, pageSize: 25, ...params});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function marketRead(command, options, {fetchImpl = fetch} = {}) {
|
|
179
|
+
const config = connection(options);
|
|
180
|
+
const request = async (endpoint, params = {}) => {
|
|
181
|
+
const url = new URL('/v1/market/' + endpoint, config.authUrl);
|
|
182
|
+
url.search = new URLSearchParams(params).toString();
|
|
183
|
+
try {
|
|
184
|
+
return await jsonRequest(url.toString(), {token: config.sessionToken, fetchImpl});
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (error.code === 'SERVICE_ERROR' && error.details?.serviceCode)
|
|
187
|
+
fail(error.details.serviceCode, error.message, error.details.serviceDetails);
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
return operations[command](options, request);
|
|
192
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {connection,session,jsonRequest,fail} from './core.mjs';
|
|
5
|
+
|
|
6
|
+
export async function projectArtifact(options,{fetchImpl=fetch}={}){
|
|
7
|
+
const config=connection(options);await session(config,fetchImpl);
|
|
8
|
+
for(const key of ['project-id','task-id','id','output'])if(!options[key])fail('TARGET_REQUIRED','附件下载需要项目、任务、附件 ID 和输出路径');
|
|
9
|
+
const output=path.resolve(options.output);if(fs.existsSync(output))fail('FILE_EXISTS','输出文件已存在,请指定新路径');
|
|
10
|
+
const query=new URLSearchParams({projectId:options['project-id'],taskId:options['task-id']});
|
|
11
|
+
const context=await jsonRequest(config.dataServiceUrl+'/api/workbench/collaboration/query/task/get?'+query,{token:config.sessionToken,fetchImpl});
|
|
12
|
+
const file=context.data.artifacts.find(row=>row.id===options.id);
|
|
13
|
+
if(!file)fail('NOT_FOUND','附件不属于指定项目任务');
|
|
14
|
+
if(!Number.isInteger(file.size)||file.size<0||file.size>2*1024*1024||!/^[a-f0-9]{64}$/.test(file.sha))fail('UNSUPPORTED_ARTIFACT','附件大小或校验信息不支持下载');
|
|
15
|
+
const response=await fetchImpl(config.dataServiceUrl+'/api/workbench/collaboration/files/'+encodeURIComponent(file.id),{method:'GET',redirect:'error',signal:AbortSignal.timeout(15000),headers:{Authorization:'Bearer '+config.sessionToken}});
|
|
16
|
+
if(!response.ok)fail('DOWNLOAD_FAILED','附件原件读取失败',{status:response.status});
|
|
17
|
+
const chunks=[];let size=0;
|
|
18
|
+
if(!response.body)fail('DOWNLOAD_FAILED','附件原件为空');
|
|
19
|
+
const reader=response.body.getReader();
|
|
20
|
+
while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>file.size){await reader.cancel();fail('VERIFY_FAILED','附件返回大小与记录不一致');}chunks.push(Buffer.from(value));}
|
|
21
|
+
const bytes=Buffer.concat(chunks),sha=createHash('sha256').update(bytes).digest('hex');
|
|
22
|
+
if(size!==file.size||sha!==file.sha)fail('VERIFY_FAILED','附件内容与记录的 SHA 不一致');
|
|
23
|
+
try{fs.writeFileSync(output,bytes,{flag:'wx',mode:0o600});}catch(e){if(e.code==='EEXIST')fail('FILE_EXISTS','输出文件已存在,已保留');throw e;}
|
|
24
|
+
return {projectId:options['project-id'],taskId:options['task-id'],artifactId:file.id,path:output,name:file.name,size,sha,verification:'sha256-matched'};
|
|
25
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {connection,session,jsonRequest,fail} from './core.mjs';
|
|
5
|
+
export async function projectEdit(options,{fetchImpl=fetch}={}){
|
|
6
|
+
const config=connection(options),user=await session(config,fetchImpl);
|
|
7
|
+
const request=async(suffix,body)=>{try{return await jsonRequest(config.dataServiceUrl+'/api/workbench/collaboration'+suffix,{token:config.sessionToken,fetchImpl,...(body?{method:'POST',body}:{})});}catch(error){if(error.code==='SERVICE_ERROR'&&error.details?.serviceCode)fail(error.details.serviceCode,error.message,error.details.serviceDetails);throw error;}};
|
|
8
|
+
if(!options.project&&!options['project-id']||options.project&&options['project-id'])fail('TARGET_REQUIRED','请指定唯一项目名称或 --project-id');
|
|
9
|
+
const selectors=new URLSearchParams(options['project-id']?{projectId:options['project-id']}:{project:options.project});
|
|
10
|
+
const current=(await request('/query/project/edit-context?'+selectors)).data;
|
|
11
|
+
let patch=options.file?JSON.parse(fs.readFileSync(options.file,'utf8')):{};
|
|
12
|
+
if(!patch||typeof patch!=='object'||Array.isArray(patch))fail('INVALID_INPUT','编辑文件须为字段对象');
|
|
13
|
+
const fields={name:'name',goal:'goal','owner-id':'ownerMemberId',folder:'folderId','start-date':'startDate','due-date':'dueDate','duration-mode':'durationMode'};
|
|
14
|
+
for(const [flag,key] of Object.entries(fields))if(options[flag]!==undefined){if(key in patch)fail('INVALID_INPUT','字段重复:'+key);patch[key]=key==='folderId'&&options[flag]==='unfiled'?null:options[flag];}
|
|
15
|
+
const put=(key,value)=>{if(key in patch)fail('INVALID_INPUT','字段重复:'+key);patch[key]=value;};
|
|
16
|
+
if(options.platforms!==undefined)put('platforms',options.platforms.split(',').map(x=>x.trim()));
|
|
17
|
+
if(options.pinned!==undefined){if(!['true','false'].includes(options.pinned))fail('INVALID_INPUT','pinned 须为 true 或 false');put('pinned',options.pinned==='true');}
|
|
18
|
+
if(options['duration-days']!==undefined)put('durationDays',Number(options['duration-days']));
|
|
19
|
+
if(options.cover&&options['clear-cover'])fail('INVALID_INPUT','封面上传与清除请择一');
|
|
20
|
+
if(options.cover){const file=path.resolve(options.cover),stat=fs.lstatSync(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>2*1024*1024)fail('INVALID_INPUT','封面须为2 MB以内的普通图片文件');const bytes=fs.readFileSync(file),type=bytes[0]===137?'png':bytes[0]===255?'jpeg':'webp';put('cover',{name:path.basename(file),dataUrl:`data:image/${type};base64,${bytes.toString('base64')}`});}
|
|
21
|
+
if(options['clear-cover'])put('cover',null);
|
|
22
|
+
if(!Object.keys(patch).length)fail('INVALID_INPUT','请指定需要编辑的字段');
|
|
23
|
+
const body={op:'project-edit',projectId:current.id,patch,clientMemberId:user.id,expectedRevision:options['expected-revision']===undefined?current.expectedRevision:Number(options['expected-revision']),expectedVersion:options['expected-version']===undefined?current.version:Number(options['expected-version'])};
|
|
24
|
+
const preview=await request('/command',{...body,preview:true,requestId:randomUUID()});
|
|
25
|
+
if(options['dry-run'])return {preview:true,...preview.data};
|
|
26
|
+
if(!options.yes)fail('CONFIRMATION_REQUIRED','写入项目编辑需要 --yes;可先使用 --dry-run 预演');
|
|
27
|
+
const requestId=options['idempotency-key']||randomUUID();let written;
|
|
28
|
+
try{written=await request('/command',{...body,patchHash:preview.data.patchHash,requestId});}
|
|
29
|
+
catch(error){if(error.code!=='WRITE_OUTCOME_UNKNOWN')throw error;written=await request('/command',{...body,patchHash:preview.data.patchHash,requestId});}
|
|
30
|
+
const readback=(await request('/query/project/get?'+new URLSearchParams({projectId:current.id}))).data;
|
|
31
|
+
for(const key of Object.keys(patch)){if(key==='cover'){if(patch.cover===null?readback.hasCover:readback.cover?.sha!==written.data.project.cover?.sha)fail('VERIFY_FAILED','封面写后回读不一致',{requestId});}else if(JSON.stringify(readback[key])!==JSON.stringify(written.data.project[key]))fail('VERIFY_FAILED','项目字段写后回读不一致',{requestId,field:key});}
|
|
32
|
+
return {project:readback,changedFields:written.data.changedFields,requestId,reused:!!written.reused,verification:'write-after-readback'};
|
|
33
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
4
|
+
import {connection,session,jsonRequest,fail} from './core.mjs';
|
|
5
|
+
|
|
6
|
+
export async function projectExecution(command,options,{fetchImpl=fetch}={}){
|
|
7
|
+
const config=connection(options),user=await session(config,fetchImpl);
|
|
8
|
+
const request=async(suffix,body)=>{try{return await jsonRequest(config.dataServiceUrl+'/api/workbench/collaboration'+suffix,{token:config.sessionToken,fetchImpl,...(body?{method:'POST',body}:{})});}catch(e){if(e.code==='SERVICE_ERROR'&&e.details?.serviceCode)fail(e.details.serviceCode,e.message,e.details.serviceDetails);throw e;}};
|
|
9
|
+
const selectors=options['run-id']?{runId:options['run-id']}:{projectId:options['project-id'],taskId:options['task-id']};
|
|
10
|
+
if(Object.values(selectors).some(v=>!v))fail('TARGET_REQUIRED','请指定 --run-id 或项目及任务 ID');
|
|
11
|
+
const current=await request('/query/execution/context?'+new URLSearchParams(selectors));
|
|
12
|
+
const action=command.split(' ')[1],body={op:'execution',action,...selectors,expectedRevision:current.revision,clientMemberId:user.id,requestId:options['idempotency-key']||randomUUID()};
|
|
13
|
+
if(action==='prepare')body.agent=options.agent;
|
|
14
|
+
if(action==='start'){body.agent=options.agent;body.skills=(options.skills||'').split(',').map(s=>s.trim()).filter(Boolean);if(options['conversation-id'])body.conversationId=options['conversation-id'];}
|
|
15
|
+
if(action==='attach'){
|
|
16
|
+
if(!options.file)fail('INVALID_INPUT','请提供 --file');const stat=fs.lstatSync(options.file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>2*1024*1024)fail('INVALID_INPUT','成果文件须为 2 MB 内普通文件');
|
|
17
|
+
body.file={name:path.basename(options.file),base64:fs.readFileSync(options.file).toString('base64'),mime:options.mime||'application/octet-stream'};
|
|
18
|
+
}
|
|
19
|
+
if(action==='finish'){
|
|
20
|
+
if(!options.wiki)fail('INVALID_INPUT','请提供 --wiki 正文文件');const stat=fs.lstatSync(options.wiki);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>1500000)fail('INVALID_INPUT','Wiki 文件无效');
|
|
21
|
+
body.content=fs.readFileSync(options.wiki,'utf8');body.summary=options.summary;body.expectedDocumentVersion=options['expected-document-version']===undefined?current.data.run.wikiVersion:Number(options['expected-document-version']);
|
|
22
|
+
}
|
|
23
|
+
if(action==='fail')body.error=options.error;
|
|
24
|
+
if(options['dry-run'])return {preview:true,action,context:current.data};
|
|
25
|
+
if(!options.yes)fail('CONFIRMATION_REQUIRED','写入执行记录需要 --yes');
|
|
26
|
+
let result;try{result=await request('/command',body);}catch(e){if(e.code!=='WRITE_OUTCOME_UNKNOWN')throw e;result=await request('/command',body);}
|
|
27
|
+
const runId=result.data.run.id,readback=await request('/query/execution/context?'+new URLSearchParams({runId}));
|
|
28
|
+
if(readback.data.run.status!==result.data.run.status)fail('VERIFY_FAILED','执行状态写后回读不一致',{runId,requestId:body.requestId});
|
|
29
|
+
if(action==='attach'&&!readback.data.task.artifacts.some(f=>f.name===body.file.name&&f.sha===createHash('sha256').update(Buffer.from(body.file.base64,'base64')).digest('hex')))fail('VERIFY_FAILED','成果文件写后回读不一致',{runId,requestId:body.requestId});
|
|
30
|
+
if(action==='finish'&&createHash('sha256').update(readback.data.document?.content||'').digest('hex')!==result.data.run.wikiSha)fail('VERIFY_FAILED','Wiki 正文写后回读不一致',{runId,requestId:body.requestId});
|
|
31
|
+
if(action==='finish'&&(readback.data.document?.version!==result.data.documentVersion||readback.data.task.status!=='已完成'))fail('VERIFY_FAILED','Wiki 或任务状态回读不一致',{runId,requestId:body.requestId});
|
|
32
|
+
return {...result.data,context:readback.data,requestId:body.requestId,reused:!!result.reused,verification:'write-after-readback'};
|
|
33
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import {connection,session,jsonRequest,fail} from './core.mjs';
|
|
2
|
+
// Transport only: resolution, filtering and project access rules live on the service.
|
|
3
|
+
export async function projectRead(command,options,{fetchImpl=fetch}={}){
|
|
4
|
+
const config=connection(options);await session(config,fetchImpl);
|
|
5
|
+
const query=new URLSearchParams();
|
|
6
|
+
for(const [key,value] of Object.entries(options))if(!['profile','config','json','help'].includes(key))query.set(key.replace(/-([a-z])/g,(_,letter)=>letter.toUpperCase()),String(value));
|
|
7
|
+
const url=config.dataServiceUrl+'/api/workbench/collaboration/query/'+command.replace(' ','/')+'?'+query;
|
|
8
|
+
try{return await jsonRequest(url,{token:config.sessionToken,fetchImpl});}
|
|
9
|
+
catch(error){if(error.code==='SERVICE_ERROR'&&error.details?.serviceCode)fail(error.details.serviceCode,error.message,error.details.serviceDetails);throw error;}
|
|
10
|
+
}
|