@officesdk/officesdk-plugin 1.0.3 → 1.0.5
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 +15 -0
- package/bin/file-host.mjs +42 -4
- package/bin/hosts.mjs +6 -12
- package/bin/ide.mjs +9 -7
- package/bin/install.mjs +12 -0
- package/bin/personal-hosts.mjs +55 -0
- package/bin/personal.mjs +70 -0
- package/bin/workbuddy.mjs +55 -4
- package/package.json +4 -1
- package/personal/build-imports.py +123 -0
- package/personal/kimi-office-intent.py +37 -0
- package/personal/office-mcp.py +64 -0
- package/personal/office.py +106 -0
- package/routes.json +60 -27
package/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# OfficeSDK for AI Agent
|
|
2
|
+
|
|
3
|
+
Open and edit Word documents, Excel workbooks, and PowerPoint presentations in your AI agent.
|
|
4
|
+
|
|
5
|
+
## Install in your agent
|
|
6
|
+
|
|
7
|
+
Paste this command into your agent’s chat and ask it to install OfficeSDK in the current client.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npx --yes @officesdk/officesdk-plugin@latest
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The installer selects the adapter for your client. [Supported clients and installation guide](https://github.com/officesdk/officesdk-plugin#quick-start)
|
|
14
|
+
|
|
15
|
+
在当前 Agent 的对话框中发送上面的命令,即可运行 OfficeSDK 安装器。[中文安装指南](https://github.com/officesdk/officesdk-plugin/blob/main/README.zh-CN.md#quick-start)
|
package/bin/file-host.mjs
CHANGED
|
@@ -1,10 +1,37 @@
|
|
|
1
|
-
import fs from 'node:fs/promises';
|
|
2
|
-
import {createHash} from 'node:crypto';
|
|
3
|
-
import {Readable} from 'node:stream';
|
|
4
1
|
import os from 'node:os';
|
|
5
2
|
import path from 'node:path';
|
|
6
3
|
import {fileURLToPath} from 'node:url';
|
|
7
4
|
|
|
5
|
+
import fs from 'node:fs/promises';
|
|
6
|
+
import {createHash} from 'node:crypto';
|
|
7
|
+
import {Readable} from 'node:stream';
|
|
8
|
+
import {execFile} from 'node:child_process';
|
|
9
|
+
import {promisify} from 'node:util';
|
|
10
|
+
|
|
11
|
+
const run=promisify(execFile);
|
|
12
|
+
async function enableHermesTools(profile, version) {
|
|
13
|
+
const paths=[path.join(os.homedir(),'Applications'),'/Applications'].map(dir=>
|
|
14
|
+
path.join(dir,'Hermes Agent.app/Contents/Resources/agent-payload/bin/hermes'));
|
|
15
|
+
let cli='hermes';
|
|
16
|
+
for(const file of paths) {
|
|
17
|
+
if(await fs.access(file,fs.constants.X_OK).then(()=>true,()=>false)){cli=file;break;}
|
|
18
|
+
}
|
|
19
|
+
const options={env:{...process.env,HERMES_HOME:profile},timeout:25000};
|
|
20
|
+
const status=async()=>{
|
|
21
|
+
const {stdout}=await run(cli,['plugins','list','--user','--json'],options);
|
|
22
|
+
return JSON.parse(stdout).find(row=>row.name==='officesdk');
|
|
23
|
+
};
|
|
24
|
+
const before=await status();
|
|
25
|
+
if(!before || before.version!==version)throw Error('Hermes could not register OfficeSDK '+version);
|
|
26
|
+
if(before.status==='enabled')return;
|
|
27
|
+
await run(cli,['plugins','enable','officesdk','--no-allow-tool-override'],options);
|
|
28
|
+
try {
|
|
29
|
+
if((await status())?.status!=='enabled')throw Error('Hermes did not enable the OfficeSDK tools.');
|
|
30
|
+
} catch(error) {
|
|
31
|
+
await run(cli,['plugins','disable','officesdk'],options);
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
8
35
|
async function readSettings(file) {
|
|
9
36
|
try { return JSON.parse(await fs.readFile(file,'utf8')); }
|
|
10
37
|
catch(error) { if(error.code==='ENOENT')return {}; throw error; }
|
|
@@ -50,6 +77,10 @@ export async function prepareEngine() {
|
|
|
50
77
|
}
|
|
51
78
|
export async function installFileHost({host, route, version, assetDir, project}) {
|
|
52
79
|
const {target,data}=hostLocations(host);
|
|
80
|
+
if(host==='workbuddy'){
|
|
81
|
+
const {checkChatInstall}=await import('./workbuddy.mjs');
|
|
82
|
+
if(await checkChatInstall(target,version))return;
|
|
83
|
+
}
|
|
53
84
|
const bytes=await assetBytes(route,version,assetDir);
|
|
54
85
|
const {extractTar}=await import('../runtime/tar.mjs');
|
|
55
86
|
const {acquireLease}=await import('../runtime/lease.mjs');
|
|
@@ -64,7 +95,9 @@ export async function installFileHost({host, route, version, assetDir, project})
|
|
|
64
95
|
if(!previous.isDirectory())throw Error('The target is not an OfficeSDK directory: '+target);
|
|
65
96
|
if((await readSettings(path.join(target,integration?'plugins/officesdk':'',route.manifest))).name!==route.name)throw Error('The target belongs to another plugin: '+target);
|
|
66
97
|
}
|
|
67
|
-
|
|
98
|
+
// Hermes discovers nested plugin manifests, including copies kept for rollback.
|
|
99
|
+
const scratchParent = host === 'hermes' ? data : parent;
|
|
100
|
+
scratch=await fs.mkdtemp(path.join(scratchParent,'.officesdk-install-'));
|
|
68
101
|
staging=path.join(scratch,'new');
|
|
69
102
|
await extractTar(Readable.from([bytes]),staging,{gzip:true,strip:'package'});
|
|
70
103
|
const identity=await readSettings(path.join(staging,route.manifest));
|
|
@@ -93,6 +126,7 @@ export async function installFileHost({host, route, version, assetDir, project})
|
|
|
93
126
|
await fs.rename(staging,target);activated=true;
|
|
94
127
|
await fs.rename(config,settingsFile);settingsCommitted=true;
|
|
95
128
|
if(manager)await manager.activate(version);
|
|
129
|
+
if(host==='hermes')await enableHermesTools(path.dirname(data),version);
|
|
96
130
|
} catch(error) {
|
|
97
131
|
if(activated){
|
|
98
132
|
try { await fs.rename(target,staging); }
|
|
@@ -113,6 +147,10 @@ export async function installFileHost({host, route, version, assetDir, project})
|
|
|
113
147
|
throw error;
|
|
114
148
|
} finally {await fs.rm(configTmp,{recursive:true,force:true});}
|
|
115
149
|
if(manager){console.log('Installed and enabled OfficeSDK '+version+' in '+host+'.');return;}
|
|
150
|
+
if(host==='hermes'){
|
|
151
|
+
console.log('OfficeSDK '+version+' tools are enabled in Hermes. In Settings → Plugins, turn on the OfficeSDK desktop plugin, then open a new chat. If the panel is missing, run Reload desktop plugins from the command palette.');
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
116
154
|
console.log('Installed OfficeSDK '+version+' for '+host+'. Restart the client and enable OfficeSDK in its plugin manager.');
|
|
117
155
|
} finally {
|
|
118
156
|
try { if(scratch&&!keepBackup)await fs.rm(scratch,{recursive:true,force:true}); } finally { await lock.release(); }
|
package/bin/hosts.mjs
CHANGED
|
@@ -10,12 +10,8 @@ const clients = {
|
|
|
10
10
|
hermes: ['Hermes Agent', 'hermes'],
|
|
11
11
|
minimax: ['MiniMax Code', 'minimax-code'],
|
|
12
12
|
zcode: ['ZCode'],
|
|
13
|
-
cursor: ['Cursor', 'cursor-agent']
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
// Recognize these clients before falling back to inherited terminal hints.
|
|
17
|
-
const deferredClients = {
|
|
18
|
-
kimi: ['Kimi Work', 'kimi-daimon'],
|
|
13
|
+
cursor: ['Cursor', 'cursor-agent'],
|
|
14
|
+
kimi: ['Kimi', 'Kimi Work', 'kimi-daimon'],
|
|
19
15
|
qwen: ['QwenWorkCN', 'Qwen Work', '千问办公'],
|
|
20
16
|
doubao: ['DoubaoWork', 'Doubao Work', '豆包工作']
|
|
21
17
|
};
|
|
@@ -25,11 +21,6 @@ export const hosts = Object.keys(clients);
|
|
|
25
21
|
function clientId(value) {
|
|
26
22
|
if (!value) return undefined;
|
|
27
23
|
const name = value.trim().toLowerCase();
|
|
28
|
-
for (const [id, aliases] of Object.entries(deferredClients)) {
|
|
29
|
-
if ([id, ...aliases].some(alias => alias.toLowerCase() === name)) {
|
|
30
|
-
throw Error('This OfficeSDK version does not support ' + value);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
24
|
return hosts.find(id => id === name || clients[id].some(alias => alias.toLowerCase() === name));
|
|
34
25
|
}
|
|
35
26
|
|
|
@@ -42,10 +33,13 @@ export function chooseHost(explicit, env, parents) {
|
|
|
42
33
|
}
|
|
43
34
|
for (const executable of parents) {
|
|
44
35
|
const bundle = executable.match(/(?:^|\/)([^/]+)\.app\/Contents\//i);
|
|
45
|
-
const found = clientId(path.basename(executable).replace(/\.exe$/i, ''))
|
|
36
|
+
const found = clientId(bundle?.[1]) || clientId(path.basename(executable).replace(/\.exe$/i, ''));
|
|
46
37
|
if (found) return found;
|
|
47
38
|
}
|
|
48
39
|
const signals = new Set();
|
|
40
|
+
// WorkBuddy can run chat commands in a detached shell without an app parent.
|
|
41
|
+
if (env.WORKBUDDY_CONFIG_DIR || env.WORKBUDDY_RESOURCES_PATH ||
|
|
42
|
+
(env.CODEBUDDY_CONFIG_DIR && path.basename(env.CODEBUDDY_CONFIG_DIR) === '.workbuddy')) signals.add('workbuddy');
|
|
49
43
|
if (env.CODEX_THREAD_ID) signals.add('codex');
|
|
50
44
|
if (env.CURSOR_AGENT === '1') signals.add('cursor');
|
|
51
45
|
const terminal = clientId(env.TERM_PROGRAM);
|
package/bin/ide.mjs
CHANGED
|
@@ -12,10 +12,10 @@ async function put(file, bytes) {
|
|
|
12
12
|
try {const staged=path.join(tmp,'new');await fs.writeFile(staged,bytes,{mode:0o600});await fs.rename(staged,file);}
|
|
13
13
|
finally{await fs.rm(tmp,{recursive:true,force:true});}
|
|
14
14
|
}
|
|
15
|
-
async function registerProject(project, folder) {
|
|
15
|
+
async function registerProject(project, folder, host) {
|
|
16
16
|
const configFile=path.join(project,'.cursor','mcp.json'), rulesFile=path.join(project,'.cursor/rules/officesdk.mdc');
|
|
17
17
|
const skillFile=path.join(os.homedir(),'.cursor/skills/officesdk/SKILL.md');
|
|
18
|
-
const shim=path.join(os.homedir(),'.officesdk
|
|
18
|
+
const shim=path.join(os.homedir(),'.officesdk',host,'project-mcp.cjs');
|
|
19
19
|
const config=JSON.parse(await optional(configFile)??'{}');
|
|
20
20
|
const servers=config.mcpServers??={};
|
|
21
21
|
if(!servers||typeof servers!=='object'||Array.isArray(servers))throw Error('Invalid Cursor mcpServers configuration');
|
|
@@ -23,18 +23,20 @@ async function registerProject(project, folder) {
|
|
|
23
23
|
if(previous && !previous.args?.includes('--cursor-project'))throw Error('The OfficeSDK Project name is already in use in this project');
|
|
24
24
|
const rule=await fs.readFile(path.join(folder,'cursor/office-tasks.mdc'),'utf8');
|
|
25
25
|
const skill=await fs.readFile(path.join(folder,'cursor/skills/officesdk/SKILL.md'),'utf8');
|
|
26
|
-
|
|
26
|
+
const files=host==='cursor'?[[rulesFile,rule],[skillFile,skill]]:[[rulesFile,rule]];
|
|
27
|
+
for(const [file,bytes] of files){
|
|
27
28
|
const current=await optional(file);
|
|
28
29
|
if(current && current!==bytes && !current.includes('OfficeSDK'))throw Error('An unrelated file already exists at '+file);
|
|
29
30
|
}
|
|
30
31
|
await put(shim,'require('+JSON.stringify(path.join(folder,'mcp.cjs'))+');\n');
|
|
31
|
-
|
|
32
|
-
servers['OfficeSDK Project']={command:process.execPath,args:[shim,'--cursor-project',project]};
|
|
32
|
+
for(const [file,bytes] of files)await put(file,bytes);
|
|
33
|
+
servers['OfficeSDK Project']={command:process.execPath,args:[shim,'--cursor-project',project],env:{OFFICESDK_IDE_HOST:host}};
|
|
33
34
|
await put(configFile,JSON.stringify(config,null,2)+'\n');
|
|
34
35
|
}
|
|
35
36
|
export async function installExtension({host,route,version,values}) {
|
|
36
37
|
const project=await fs.realpath(values.project||process.cwd());
|
|
37
|
-
|
|
38
|
+
const projectEligible=project!==os.homedir() && project!==path.parse(project).root && (await fs.stat(project)).isDirectory();
|
|
39
|
+
if(!projectEligible && (host==='cursor' || values.project))throw Error('Choose the target workspace using --project <directory>');
|
|
38
40
|
const name=host==='cursor'?'cursor':'grok-build';
|
|
39
41
|
let command=name;
|
|
40
42
|
const appName=host==='cursor'?'Cursor.app':'Grok Build.app';
|
|
@@ -64,7 +66,7 @@ export async function installExtension({host,route,version,values}) {
|
|
|
64
66
|
const folder=path.join(root,entry.relativeLocation);
|
|
65
67
|
const manifest=JSON.parse(await fs.readFile(path.join(folder,'package.json'),'utf8'));
|
|
66
68
|
if(manifest.publisher+'.'+manifest.name!==route.name || manifest.version!==version)throw Error('Installed extension identity mismatch');
|
|
67
|
-
if(
|
|
69
|
+
if(projectEligible)await registerProject(project,folder,host);
|
|
68
70
|
console.log('Installed OfficeSDK '+version+' for '+host+'. Reopen the workspace to activate the extension.');
|
|
69
71
|
} finally { try{if(tmp)await fs.rm(tmp,{recursive:true,force:true});}finally{await lock.release();} }
|
|
70
72
|
}
|
package/bin/install.mjs
CHANGED
|
@@ -18,6 +18,18 @@ async function run() {
|
|
|
18
18
|
const host = chooseHost(values.host, process.env, parentExecutables());
|
|
19
19
|
const route = routes[host];
|
|
20
20
|
if (!route) throw Error('OfficeSDK ' + version + ' has no verified installation package for ' + host + '.');
|
|
21
|
+
if(route.kind==='personal-import') {
|
|
22
|
+
const platform=process.platform+'-'+process.arch;
|
|
23
|
+
if(!route.platforms.includes(platform))throw Error('Unsupported platform for '+host+': '+platform);
|
|
24
|
+
if(values['dry-run'])return console.log(JSON.stringify({host,version,asset:route.asset,platform}));
|
|
25
|
+
const {preparePersonalImports}=await import('./personal.mjs');
|
|
26
|
+
const {installPersonalHost}=await import('./personal-hosts.mjs');
|
|
27
|
+
const result=await installPersonalHost(host,await preparePersonalImports({assets:values['asset-dir'],hosts:[host]}));
|
|
28
|
+
console.log(JSON.stringify(result));
|
|
29
|
+
if(result.status==='awaiting-native-import')console.log(host==='qwen'?'千问办公 → 技能 · 扩展 → 专家套件 → 本地安装,选择上述 ZIP。':'豆包工作 → 插件 · 技能 → 上传个人插件,选择上述 ZIP。');
|
|
30
|
+
if(result.status==='awaiting-market-activation')console.log('在 Kimi 的个人插件页更新并启用 OfficeSDK。');
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
21
33
|
if(['codex-market','zcode-market','workbuddy-market','file-host','vsix'].includes(route.kind)) {
|
|
22
34
|
const platform=process.platform+'-'+process.arch;
|
|
23
35
|
if(!route.platforms.includes(platform))throw Error('OfficeSDK '+version+' has no '+host+' release for '+platform);
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {execFile} from 'node:child_process';
|
|
5
|
+
import {promisify} from 'node:util';
|
|
6
|
+
const run=promisify(execFile);
|
|
7
|
+
async function appTool(name,file) {
|
|
8
|
+
for(const base of ['/Applications',path.join(os.homedir(),'Applications')]){
|
|
9
|
+
const p=path.join(base,name+'.app/Contents/Resources',file);
|
|
10
|
+
if(await fs.access(p,fs.constants.X_OK).then(()=>true,()=>false))return p;
|
|
11
|
+
}
|
|
12
|
+
throw Error('The installed '+name+' client does not provide its native installer');
|
|
13
|
+
}
|
|
14
|
+
export async function installPersonalHost(host,prepared) {
|
|
15
|
+
if (host === 'qwen' || host === 'doubao') {
|
|
16
|
+
const qwen = host === 'qwen';
|
|
17
|
+
const basename = qwen ? 'QwenWork' : 'DoubaoWork';
|
|
18
|
+
const importFile = path.join(prepared.destination, 'OfficeSDK-' + basename + '-' + prepared.version + '.zip');
|
|
19
|
+
await fs.access(importFile);
|
|
20
|
+
return {...prepared, status:'awaiting-native-import', importFile,
|
|
21
|
+
...(qwen && {nativeAction:{key:'qwenwork.settings.plugins.install_from_path', action:'execute',
|
|
22
|
+
params:{sourcePath:path.join(prepared.destination,'Qwen Work'),usageOrigin:'created'}}})};
|
|
23
|
+
}
|
|
24
|
+
if (host !== 'kimi') throw Error('Unsupported personal host: ' + host);
|
|
25
|
+
const result={...prepared,importFile:path.join(prepared.destination,'Kimi Work')};
|
|
26
|
+
const cli=process.env.DAIMON_RUNTIME_BINARY_PATH || await appTool('Kimi','resources/daimon-bundle/bin/kimi-daimon');
|
|
27
|
+
const share=process.env.KIMI_SHARE_DIR || path.join(os.homedir(),'Library/Application Support/kimi-desktop/daimon-share');
|
|
28
|
+
const entry=path.join(share,'daimon/plugin-market/personal/officesdk.json');
|
|
29
|
+
const market=await fs.stat(entry).then(()=>true,e=>{if(e.code==='ENOENT')return false;throw e;});
|
|
30
|
+
// Use the same registry the desktop app owns, including for users who first installed from Personal.
|
|
31
|
+
let node=process.env.DAIMON_BUNDLE_NODE_BIN||process.env.DAIMON_NODE_BIN;
|
|
32
|
+
if(!node){
|
|
33
|
+
const candidates=[path.join(path.dirname(cli),'node'),path.join(share,'daimon/runtime/tool-node/bin/node')];
|
|
34
|
+
for(const candidate of candidates){
|
|
35
|
+
if(await fs.access(candidate,fs.constants.X_OK).then(()=>true,()=>false)){node=candidate;break;}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// The bundle can resolve its own pinned Node. Only use the npm Node if the launcher lacks a runtime.
|
|
39
|
+
const args=['kimi-plugin',market?'register-personal':'install',result.importFile,'--share-dir',share,'--json'];
|
|
40
|
+
let output;
|
|
41
|
+
try {output=await run(cli,[...(node?['--node',node]:[]),...args],{timeout:90000,maxBuffer:2*1024*1024});}
|
|
42
|
+
catch(error){
|
|
43
|
+
if(node||Number(error.code)!==127||!/requires Node/.test(error.stderr||''))throw error;
|
|
44
|
+
output=await run(cli,['--node',process.execPath,...args],{timeout:90000,maxBuffer:2*1024*1024});
|
|
45
|
+
}
|
|
46
|
+
const {stdout}=output;
|
|
47
|
+
const receipt=JSON.parse(stdout);
|
|
48
|
+
if(market){
|
|
49
|
+
if(!receipt.ok||receipt.id!=='officesdk'||receipt.sourceVersion!==prepared.version)throw Error('Kimi could not register this version in the personal marketplace');
|
|
50
|
+
return {...result,status:'awaiting-market-activation',marketLink:receipt.link};
|
|
51
|
+
}
|
|
52
|
+
const plugin=receipt.plugin;
|
|
53
|
+
if(!receipt.ok||!receipt.installed||!plugin?.enabled||plugin.id!=='officesdk'||plugin.version!==prepared.version||plugin.hasErrors||plugin.enabledMcpServerCount!==1)throw Error('Kimi did not enable this version of OfficeSDK');
|
|
54
|
+
return {...result,status:'installed',nativeSkillCount:plugin.skillCount,nativeServerCount:plugin.enabledMcpServerCount};
|
|
55
|
+
}
|
package/bin/personal.mjs
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Prepare personal-host import files against the exact same renderer as the native release.
|
|
2
|
+
// Run locally after extracting the packed npm installer. The host owns import and activation.
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
7
|
+
import {createHash} from 'node:crypto';
|
|
8
|
+
import {Readable} from 'node:stream';
|
|
9
|
+
import {execFileSync} from 'node:child_process';
|
|
10
|
+
|
|
11
|
+
const source=fileURLToPath(new URL('../personal/',import.meta.url));
|
|
12
|
+
const installer=fileURLToPath(new URL('../',import.meta.url));
|
|
13
|
+
const readJson=async f=>JSON.parse(await fs.readFile(f,'utf8'));
|
|
14
|
+
const load=async relative=>import(pathToFileURL(path.join(installer,relative)));
|
|
15
|
+
export async function preparePersonalImports({assets,destination,hosts}) {
|
|
16
|
+
if(hosts?.length !== 1 || !['kimi','qwen','doubao'].includes(hosts[0]))throw Error('Select a supported personal host');
|
|
17
|
+
const {version}=await readJson(path.join(installer,'package.json'));
|
|
18
|
+
const route=(await readJson(path.join(installer,'routes.json'))).hermes;
|
|
19
|
+
const {assetBytes,prepareEngine}=await load('bin/file-host.mjs');
|
|
20
|
+
const {extractTar}=await load('runtime/tar.mjs');
|
|
21
|
+
const {acquireLease}=await load('runtime/lease.mjs');
|
|
22
|
+
const archive=await assetBytes(route,version,assets);
|
|
23
|
+
if(!route?.sha256)throw Error('Missing verified renderer for native imports');
|
|
24
|
+
const scripts=['office.py','office-mcp.py','kimi-office-intent.py'];
|
|
25
|
+
const hash=createHash('sha256').update(archive);
|
|
26
|
+
for(const f of scripts)hash.update(await fs.readFile(path.join(source,f)));
|
|
27
|
+
const runtimeId=hash.digest('hex');
|
|
28
|
+
const relative='.officesdk/personal/versions/'+version+'-'+runtimeId.slice(0,16);
|
|
29
|
+
const base=path.join(os.homedir(),'.officesdk/personal'),runtime=path.join(os.homedir(),relative);
|
|
30
|
+
await fs.mkdir(path.dirname(runtime),{recursive:true,mode:0o700});
|
|
31
|
+
const lock=await acquireLease(path.join(base,'.stage.lock'));
|
|
32
|
+
const temp=await fs.mkdtemp(path.join(path.dirname(runtime),'.prepare-'));
|
|
33
|
+
try{
|
|
34
|
+
const engine=await prepareEngine();
|
|
35
|
+
const current=await fs.readFile(path.join(runtime,'content.sha256'),'utf8').catch(e=>{if(e.code!=='ENOENT')throw e;return null;});
|
|
36
|
+
if(current!==runtimeId){
|
|
37
|
+
if(current!==null)throw Error('Existing runtime identity does not match its directory');
|
|
38
|
+
const staging=path.join(temp,'runtime');
|
|
39
|
+
await extractTar(Readable.from([archive]),path.join(staging,'editor'),{gzip:true,strip:'package'});
|
|
40
|
+
if((await readJson(path.join(staging,'editor/package.json'))).version!==version)throw Error('Renderer and import versions differ');
|
|
41
|
+
for(const file of scripts)await fs.copyFile(path.join(source,file),path.join(staging,file));
|
|
42
|
+
await fs.writeFile(path.join(staging,'content.sha256'),runtimeId);
|
|
43
|
+
await fs.rename(staging,runtime);
|
|
44
|
+
}
|
|
45
|
+
const host = hosts[0], title = {kimi:'Kimi Work',qwen:'千问办公',doubao:'豆包工作'}[host];
|
|
46
|
+
const profile=path.join(base,'profiles',host),settings=path.join(profile,'settings.json');
|
|
47
|
+
await fs.mkdir(profile,{recursive:true,mode:0o700});
|
|
48
|
+
const previous=await readJson(settings).catch(e=>{if(e.code!=='ENOENT')throw e;return {};});
|
|
49
|
+
const workspace=previous.workspace??path.join(os.homedir(),'Documents','OfficeSDK '+title);
|
|
50
|
+
await fs.mkdir(workspace,{recursive:true});
|
|
51
|
+
const data={...previous,...engine,workspace,node:process.execPath};
|
|
52
|
+
const staging=path.join(temp,host+'.json');
|
|
53
|
+
await fs.writeFile(staging,JSON.stringify(data,null,2)+'\n',{mode:0o600});
|
|
54
|
+
await fs.rename(staging,settings);
|
|
55
|
+
// Previous clients may still have a live editor. Give each renderer build its own
|
|
56
|
+
// service while preserving the user's workspace, file zoom and existing sessions.
|
|
57
|
+
const service=path.join(profile,'services',path.basename(runtime));
|
|
58
|
+
await fs.mkdir(service,{recursive:true,mode:0o700});
|
|
59
|
+
await fs.mkdir(path.join(profile,'file-zoom'),{recursive:true,mode:0o700});
|
|
60
|
+
for(const shared of ['settings.json','file-zoom']){
|
|
61
|
+
const target=path.join('..','..',shared),link=path.join(service,shared);
|
|
62
|
+
try{await fs.symlink(target,link);}
|
|
63
|
+
catch(error){if(error.code!=='EEXIST'||await fs.readlink(link)!==target)throw error;}
|
|
64
|
+
}
|
|
65
|
+
destination??=path.join(base,'imports',version+'-'+runtimeId.slice(0,16),hosts.join('-'));
|
|
66
|
+
await fs.mkdir(destination,{recursive:true,mode:0o700});
|
|
67
|
+
execFileSync('python3',[path.join(source,'build-imports.py'),destination,relative,version,path.join(runtime,'editor/LICENSE'),'--hosts',...hosts],{stdio:'inherit'});
|
|
68
|
+
return {version,runtime:relative,rendererSHA256:route.sha256,prepared:hosts,destination,status:'awaiting-native-import'};
|
|
69
|
+
}finally{try{await fs.rm(temp,{recursive:true,force:true});}finally{await lock.release();}}
|
|
70
|
+
}
|
package/bin/workbuddy.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import fs from 'node:fs/promises';
|
|
|
2
2
|
import os from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import net from 'node:net';
|
|
5
|
+
import {createHmac, randomBytes} from 'node:crypto';
|
|
5
6
|
import {execFile} from 'node:child_process';
|
|
6
7
|
import {promisify} from 'node:util';
|
|
7
8
|
|
|
@@ -28,6 +29,28 @@ async function closePreviousService(port) {
|
|
|
28
29
|
}
|
|
29
30
|
throw Error('WorkBuddy has not finished closing the previous editor service');
|
|
30
31
|
}
|
|
32
|
+
function stateDirectory() {
|
|
33
|
+
return process.env.OFFICESDK_WORKBUDDY_DATA || path.join(os.homedir(),'.officesdk/workbuddy/state');
|
|
34
|
+
}
|
|
35
|
+
export async function checkChatInstall(target, version) {
|
|
36
|
+
if (!/^(1|true)$/i.test(process.env.CODEBUDDY_DISABLE_PLUGIN_INSTALLS || '')) return false;
|
|
37
|
+
const profile=process.env.WORKBUDDY_CONFIG_DIR || path.join(os.homedir(),'.workbuddy');
|
|
38
|
+
const read=async file=>JSON.parse(await fs.readFile(file,'utf8').catch(error=>{if(error.code==='ENOENT')return '{}';throw error;}));
|
|
39
|
+
const registry=await read(path.join(profile,'plugins/installed_plugins.json'));
|
|
40
|
+
const preferences=await read(path.join(profile,'settings.json'));
|
|
41
|
+
const record=registry.plugins?.[plugin]?.find(row=>row.scope==='user' && row.version===version);
|
|
42
|
+
if(record?.installPath && preferences.enabledPlugins?.[plugin]===true){
|
|
43
|
+
const manifest=await read(path.join(record.installPath,'.workbuddy-plugin/plugin.json'));
|
|
44
|
+
const source=await read(path.join(target,relativePlugin,'.workbuddy-plugin/plugin.json'));
|
|
45
|
+
if(manifest.name===market && manifest.version===version && source.version===version &&
|
|
46
|
+
manifest.mcpServers?.office?.type==='http' && source.mcpServers?.office?.url===manifest.mcpServers.office.url){
|
|
47
|
+
await run(process.execPath,[path.join(target,relativePlugin,'src/ensure-service.mjs')],{timeout:10000});
|
|
48
|
+
console.log('OfficeSDK '+version+' is already enabled in WorkBuddy and the editor is ready. Open a new chat to load its tools.');
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
throw Error('WorkBuddy has disabled plugin installation in this chat. Run npx --yes @officesdk/officesdk-plugin@'+version+' --host workbuddy in your desktop terminal, then reopen WorkBuddy. 当前对话限制安装插件,请在系统终端执行上述命令,然后重新打开 WorkBuddy。');
|
|
53
|
+
}
|
|
31
54
|
export async function prepareMarket(staging,target,settings,version) {
|
|
32
55
|
// Let the host launch its own transport. The service is local to the user's
|
|
33
56
|
// profile and survives the end of a chat while an Office tab is open.
|
|
@@ -42,8 +65,23 @@ export async function prepareMarket(staging,target,settings,version) {
|
|
|
42
65
|
const prior=await fs.readFile(installed,'utf8').then(JSON.parse).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
43
66
|
if(prior&&prior.version!==version)await closePreviousService(settings.port);
|
|
44
67
|
const entry=JSON.parse(await fs.readFile(path.join(staging,'.workbuddy-plugin/plugin.json')));
|
|
45
|
-
|
|
68
|
+
const state=stateDirectory();
|
|
69
|
+
await fs.mkdir(state,{recursive:true,mode:0o700});
|
|
70
|
+
const keyPath=path.join(state,'connector.key');
|
|
71
|
+
try {await fs.writeFile(keyPath,randomBytes(32).toString('hex'),{flag:'wx',mode:0o600});}
|
|
72
|
+
catch(error){if(error.code!=='EEXIST')throw error;}
|
|
73
|
+
const key=await fs.readFile(keyPath,'utf8');
|
|
74
|
+
const header=createHmac('sha256',key).update('workbuddy-mcp-http-v1').digest('hex');
|
|
75
|
+
entry.mcpServers.office={type:'http',url:'http://127.0.0.1:'+settings.port+'/mcp',headers:{Authorization:'Bearer '+header},defer_loading:false};
|
|
76
|
+
// Persist the Node executable selected by the installer; GUI sessions need not inherit PATH.
|
|
77
|
+
const hooksFile=path.join(staging,'hooks/hooks.json');
|
|
78
|
+
const hooks=JSON.parse(await fs.readFile(hooksFile,'utf8'));
|
|
79
|
+
const shellQuote=value=>"'"+value.replaceAll("'","'\\''")+"'";
|
|
80
|
+
const start={type:'command',command:shellQuote(process.execPath)+' '+shellQuote(path.join(target,relativePlugin,'src/ensure-service.mjs')),timeout:10};
|
|
81
|
+
hooks.hooks.SessionStart=[{hooks:[start]}];
|
|
82
|
+
await fs.writeFile(hooksFile,JSON.stringify(hooks,null,2)+'\n');
|
|
46
83
|
await fs.writeFile(path.join(staging,'.workbuddy-plugin/plugin.json'),JSON.stringify(entry,null,2)+'\n');
|
|
84
|
+
await fs.chmod(path.join(staging,'.workbuddy-plugin/plugin.json'),0o600);
|
|
47
85
|
const marketDir=staging+'-market';
|
|
48
86
|
await fs.mkdir(path.join(marketDir,'plugins'),{recursive:true});
|
|
49
87
|
await fs.mkdir(path.join(marketDir,'.workbuddy-plugin'));
|
|
@@ -53,7 +91,7 @@ export async function prepareMarket(staging,target,settings,version) {
|
|
|
53
91
|
}
|
|
54
92
|
export async function marketManager(target) {
|
|
55
93
|
const home=os.homedir();
|
|
56
|
-
const profile=path.join(home,'.workbuddy');
|
|
94
|
+
const profile=process.env.WORKBUDDY_CONFIG_DIR || path.join(home,'.workbuddy');
|
|
57
95
|
const cli='Contents/Resources/app.asar.unpacked/cli/dist/codebuddy-lite-wb.mjs';
|
|
58
96
|
const candidates=[path.join(home,'Applications/WorkBuddy.app',cli),path.join('/Applications/WorkBuddy.app',cli)];
|
|
59
97
|
let entry;
|
|
@@ -76,12 +114,25 @@ export async function marketManager(target) {
|
|
|
76
114
|
return {
|
|
77
115
|
async activate(version) {
|
|
78
116
|
await manage('validate',path.join(target,relativePlugin));
|
|
79
|
-
|
|
117
|
+
// A directory can still be registered on disk after the host stopped loading it.
|
|
118
|
+
const marketReady=async()=>JSON.parse(await manage('marketplace','list')).some(item=>item.name===market);
|
|
119
|
+
if(!record || !await marketReady()){
|
|
120
|
+
await manage('marketplace','add',target);
|
|
121
|
+
added=!record;
|
|
122
|
+
if(!await marketReady())throw Error('WorkBuddy recorded the OfficeSDK directory but did not load its local plugin source. Check WorkBuddy plugin management for this profile and retry.');
|
|
123
|
+
}
|
|
80
124
|
if(!old){await manage('install',plugin,'--scope','user');installed=true;}
|
|
81
125
|
else if(old.version!==version){await manage('marketplace','update',market);await manage('update',plugin,'--scope','user');}
|
|
82
126
|
let rows=await list();
|
|
83
127
|
if(rows.some(r=>r.id===plugin&&!r.enabled)){await manage('enable',plugin,'--scope','user');enabled=true;rows=await list();}
|
|
84
|
-
|
|
128
|
+
const isActive=items=>items.some(r=>r.id===plugin&&r.scope==='user'&&r.enabled&&r.version===version);
|
|
129
|
+
for(const delay of [250,750,1500]){
|
|
130
|
+
if(isActive(rows))break;
|
|
131
|
+
await new Promise(resolve=>setTimeout(resolve,delay));
|
|
132
|
+
rows=await list();
|
|
133
|
+
}
|
|
134
|
+
if(!isActive(rows))throw Error('WorkBuddy loaded the OfficeSDK local source but did not confirm version '+version+' as enabled for this user.');
|
|
135
|
+
await run(process.execPath,[path.join(target,relativePlugin,'src/ensure-service.mjs')],{timeout:10000});
|
|
85
136
|
if(legacy){await manage('disable',legacy.id,'--scope','user');disabled=true;}
|
|
86
137
|
},
|
|
87
138
|
async rollback() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@officesdk/officesdk-plugin",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "Install OfficeSDK for the current AI agent",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
"bin/zcode.mjs",
|
|
18
18
|
"routes.json",
|
|
19
19
|
"LICENSE",
|
|
20
|
+
"bin/personal.mjs",
|
|
21
|
+
"bin/personal-hosts.mjs",
|
|
22
|
+
"personal",
|
|
20
23
|
"runtime",
|
|
21
24
|
"kit-manifest.json",
|
|
22
25
|
"NOTICE"
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Build only the host import descriptors; leave native registration to the host."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import tempfile
|
|
7
|
+
import zipfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
SOURCE = Path(__file__).resolve().parent
|
|
11
|
+
DESCRIPTION = "使用 OfficeSDK 创建、编辑和保存 Word、Excel、PPT 原件。Create, edit and save Word documents, Excel workbooks and PowerPoint presentations."
|
|
12
|
+
NAMES = {"kimi": "Kimi Work", "qwen": "千问办公", "doubao": "豆包工作"}
|
|
13
|
+
|
|
14
|
+
def write_json(path, value):
|
|
15
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
16
|
+
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def skill(directory, host, runtime_path):
|
|
20
|
+
dest = directory / "skills/officesdk"
|
|
21
|
+
dest.mkdir(parents=True)
|
|
22
|
+
command = f'/usr/bin/python3 "$HOME/{runtime_path}/office.py" {host}'
|
|
23
|
+
doc = f"""---
|
|
24
|
+
name: officesdk
|
|
25
|
+
description: {DESCRIPTION} Default for writing reports or meeting minutes, tracking stock or expenses, budgets, and preparing presentations. 工作总结、会议纪要、库存台账、预算、汇报演示直接使用本技能。
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
“帮我写份工作总结”或“做个预算表”的交付物分别是 Word 和 Excel。会议纪要、周报与报告用 Word,预算、台账与项目跟踪用 Excel,汇报演示用 PowerPoint。用户指定其他应用或只要聊天文本时按其要求执行。
|
|
29
|
+
Use the installed OfficeSDK editor for ordinary document, spreadsheet and slide tasks.
|
|
30
|
+
First use officesdk_start, then officesdk_schema and officesdk_call. If the host exposes only the skill, use the local command below.
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
office() {{ {command} "$@"; }}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
In each shell invocation define the function above or use the full command.
|
|
37
|
+
Start one editing session for this chat using `printf '%s' '{{}}' | office begin`.
|
|
38
|
+
If the host assigned a local task folder, send its absolute path in the JSON field
|
|
39
|
+
`workspace`. Reuse the returned session and the same original throughout this task.
|
|
40
|
+
Use `office list` for tool names. Pipe `{{"tool":"document_create"}}` to `office schema`
|
|
41
|
+
to inspect a tool before using it. Pipe a JSON object containing
|
|
42
|
+
`session`, `tool`, and `args` to `office call`. Pass JSON on stdin.
|
|
43
|
+
|
|
44
|
+
For Word, supply the intended filename and complete body to document_create.
|
|
45
|
+
For Excel, use spreadsheet_create, spreadsheet_edit, and spreadsheet_save.
|
|
46
|
+
For a new presentation, call presentation_plan, ask the user for the slide count
|
|
47
|
+
and style, then call it again with the same arguments and their confirmedChoices
|
|
48
|
+
(slideCount and style) before presentation_create. Use the corresponding read tool
|
|
49
|
+
for existing documents and follow revision tokens for edits.
|
|
50
|
+
|
|
51
|
+
When an operation returns open_in_kimi_workbench, load the native InAppBrowser tool
|
|
52
|
+
and execute the returned navigate action in this conversation before retrying the same
|
|
53
|
+
operation. This opens the OfficeSDK editor in Kimi's right workbench as work begins.
|
|
54
|
+
The launch URL is single use. Keep it out of messages, file links, and shell commands.
|
|
55
|
+
If the tool is unavailable, keep the file task going with workbenchUnavailable=true
|
|
56
|
+
and explain the Browser setting in Kimi. Do not launch a system browser.
|
|
57
|
+
On delivery, use the returned find_tab action to focus the existing editor. Deliver the
|
|
58
|
+
actual original from the returned workspace using this host's file attachment.
|
|
59
|
+
Report errors returned by the editor. Keep local service credentials private.
|
|
60
|
+
"""
|
|
61
|
+
if host != "kimi":
|
|
62
|
+
start = doc.index("When an operation returns")
|
|
63
|
+
doc = doc[:start] + """For open_in_host_workbench, navigate directly to the one-time local URL in the current
|
|
64
|
+
client's built-in browser tab, then retry the operation. Keep the URL private. Use the existing
|
|
65
|
+
tab for subsequent edits. Deliver the original file as the host's attachment.
|
|
66
|
+
"""
|
|
67
|
+
(dest / "SKILL.md").write_text(doc)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def build(out, runtime_path, version, license_file, hosts):
|
|
71
|
+
if not re.fullmatch(r"[0-9]+[.][0-9]+[.][0-9]+",version) or not re.fullmatch(r"[.]officesdk/personal/versions/[a-zA-Z0-9.-]+",runtime_path):
|
|
72
|
+
raise ValueError("Invalid OfficeSDK runtime identity")
|
|
73
|
+
out.mkdir(parents=True,exist_ok=True)
|
|
74
|
+
with tempfile.TemporaryDirectory(dir=out) as temp:
|
|
75
|
+
for host in (hosts or NAMES):
|
|
76
|
+
folder = Path(temp) / host
|
|
77
|
+
folder.mkdir()
|
|
78
|
+
manifest = dict(name="officesdk", version=version, description=DESCRIPTION, author={"name":"OfficeSDK"})
|
|
79
|
+
shutil.copy2(license_file, folder)
|
|
80
|
+
skill(folder, host, runtime_path)
|
|
81
|
+
runner = f"from pathlib import Path;import runpy;runpy.run_path(str(Path.home()/'{runtime_path}/office-mcp.py'),run_name='__main__')"
|
|
82
|
+
server = {"command":"python3","args":["-IBc",runner,host]}
|
|
83
|
+
if host in ("qwen", "doubao"):
|
|
84
|
+
if host == "qwen":
|
|
85
|
+
manifest.update(name="officesdk-qwenwork-native", displayName="OfficeSDK", displayNameEn="OfficeSDK",
|
|
86
|
+
displayNameCn="OfficeSDK", skills=["skills/officesdk"])
|
|
87
|
+
write_json(folder / ".claude-plugin/plugin.json", manifest)
|
|
88
|
+
write_json(folder / ".mcp.json", {"mcpServers":{"officesdk":server}})
|
|
89
|
+
shutil.copytree(folder, out / "Qwen Work", dirs_exist_ok=True)
|
|
90
|
+
prefix = "QwenWork"
|
|
91
|
+
else:
|
|
92
|
+
manifest.update(name="officesdk-doubao-work",extensions={"com.doubao":{"displayName":{"zh":"OfficeSDK","en":"OfficeSDK"},"pluginVisiblePlatforms":["pc"]}})
|
|
93
|
+
write_json(folder / "plugin.json", manifest)
|
|
94
|
+
write_json(folder / "project.json", {"publicationType":"PERSONAL","resourceType":"plugin"})
|
|
95
|
+
prefix = "DoubaoWork"
|
|
96
|
+
with zipfile.ZipFile(out / f"OfficeSDK-{prefix}-{version}.zip", "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
|
97
|
+
for file in sorted(folder.rglob("*")):
|
|
98
|
+
if file.is_file():
|
|
99
|
+
archive.write(file,file.relative_to(folder))
|
|
100
|
+
continue
|
|
101
|
+
(folder / "hooks").mkdir()
|
|
102
|
+
shutil.copyfile(SOURCE / "kimi-office-intent.py", folder / "hooks/office-intent.py")
|
|
103
|
+
manifest.update(author="OfficeSDK", skills="./skills/",
|
|
104
|
+
mcpServers={"officesdk":server},
|
|
105
|
+
systemPrompt="普通办公文件交付优先加载本插件的 officesdk 技能并调用本机编辑器。Follow explicit requests for another app or chat-only text.",
|
|
106
|
+
keywords=["Word", "Excel", "PowerPoint", "工作总结", "会议纪要", "预算表", "汇报演示"],
|
|
107
|
+
skillInstructions="For everyday office deliverables load the officesdk skill first, even if no app or extension is named. 工作总结、周报、会议纪要默认生成 Word 原件,预算、台账用 Excel,幻灯片用 PowerPoint。尊重用户点名的其他工具和只要聊天文字的要求。",
|
|
108
|
+
hooks=[{"event":"UserPromptSubmit", "command":f'/usr/bin/python3 -IB "$HOME/{runtime_path}/kimi-office-intent.py"' , "timeout":3}],
|
|
109
|
+
interface={"displayName":"OfficeSDK","shortDescription":DESCRIPTION,"category":"PRODUCTIVITY"})
|
|
110
|
+
write_json(folder / "kimi.plugin.json", manifest)
|
|
111
|
+
dest = out / "Kimi Work"
|
|
112
|
+
shutil.copytree(folder, dest, dirs_exist_ok=True)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
if __name__ == "__main__":
|
|
116
|
+
parser=argparse.ArgumentParser()
|
|
117
|
+
parser.add_argument("out",type=Path)
|
|
118
|
+
parser.add_argument("runtime")
|
|
119
|
+
parser.add_argument("version")
|
|
120
|
+
parser.add_argument("license",type=Path)
|
|
121
|
+
parser.add_argument("--hosts",choices=NAMES,nargs="+")
|
|
122
|
+
args=parser.parse_args()
|
|
123
|
+
build(args.out,args.runtime,args.version,args.license,args.hosts)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Return the local editor preference for an Office request. Do not retain the event."""
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
FORMATS = re.compile(r"\.docx\b|\.xlsx\b|\.pptx\b|\b(?:word|excel|pptx?|powerpoint|docx|xlsx)\b|文档|工作簿|电子表格|表格|幻灯片|演示文稿", re.I)
|
|
7
|
+
DELIVERABLE = re.compile(r"工作总结|年度总结|总结文档|文章|作文|散文|发言稿|演讲稿|新闻稿|稿件|纪要|周报|月报|报告|申请书|通知书|策划书|登记表|预算表|清单表|明细表|统计表|台账|进销存|出入库|库存|预算|汇报材料|课件|\b(?:work summary|project summary|inventory|stock|expense report|budget|tracker|essay|article|report|minutes|workbook|spreadsheet|slides?|presentation)\b", re.I)
|
|
8
|
+
ACTION = re.compile(r"写|撰|拟|起草|编一|生成|制作|做|建|整理|改|润色|扩写|补充|打开|查看|读取|保存|插入|填入|排版|\b(?:write|draft|create|make|prepare|track|organize|record|open|read|edit|update|save|revise)\b", re.I)
|
|
9
|
+
CHAT_ONLY = re.compile(r"(?:只|仅|直接)(?:需|要|用|在)?(?:聊天|文字回答|发文字|贴正文)|(?:不用|无需|不需要|不要|别)(?:创建|做成|写成|生成|输出|给我|用)?(?:文件|文档|做成文档|生成文件|做文件|OfficeSDK)|\b(?:chat only|plain text only|no files?)\b", re.I)
|
|
10
|
+
QUESTION = re.compile(r"^(?:请问|请教)?(?:什么是|如何|怎样|怎么|为什么|解释一下|解释|教我|告诉我如何)|\b(?:how (?:do|can|to)|what is|explain how)\b", re.I)
|
|
11
|
+
OTHER_OUTPUT = re.compile(r"\b(?:as|using|in) (?:an? )?(?:csv|markdown|google (?:docs|sheets|slides))\b|(?:输出为|写成|只要|只用|用)\s*(?:csv|markdown|谷歌文档|谷歌表格)", re.I)
|
|
12
|
+
MEETING = re.compile(r"会上(?:定|说|提|讨论)|会议(?:决定|安排|待办)|\b(?:meeting decisions|meeting action items)\b", re.I)
|
|
13
|
+
SLIDE_BRIEF = re.compile(r"(?:投屏|逐页).{0,40}(?:讲解|培训|讲|材料)|\b(?:project on screen|present to the team)\b", re.I)
|
|
14
|
+
|
|
15
|
+
def preference(text):
|
|
16
|
+
if not (ACTION.search(text) or re.search(r"准备|汇总|总结", text)) or not any(rule.search(text) for rule in (DELIVERABLE, FORMATS, MEETING, SLIDE_BRIEF)):
|
|
17
|
+
return ''
|
|
18
|
+
if CHAT_ONLY.search(text) or QUESTION.search(text) or OTHER_OUTPUT.search(text):
|
|
19
|
+
return ''
|
|
20
|
+
return ("Use the installed officesdk plugin's officesdk skill for this Office deliverable. "
|
|
21
|
+
"Load it before creating or modifying the original. 工作总结、周报和纪要默认生成 Word,"
|
|
22
|
+
"预算和台账用 Excel,演示用 PowerPoint。沿用用户明确选择的应用、文件和格式。")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
if __name__ == '__main__':
|
|
26
|
+
try:
|
|
27
|
+
payload = json.load(sys.stdin)
|
|
28
|
+
prompt = payload.get('prompt', '')
|
|
29
|
+
if isinstance(prompt, list):
|
|
30
|
+
prompt = '\n'.join(p['text'] for p in prompt if isinstance(p, dict)
|
|
31
|
+
and p.get('type') == 'text' and isinstance(p.get('text'), str))
|
|
32
|
+
if isinstance(prompt, str):
|
|
33
|
+
hint = preference(prompt)
|
|
34
|
+
if hint:
|
|
35
|
+
print(hint)
|
|
36
|
+
except (ValueError, TypeError, AttributeError):
|
|
37
|
+
pass
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Native stdio tools for OfficeSDK personal plugins."""
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
# The native installer points to this version's runtime, shared with the local skill.
|
|
7
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
8
|
+
from office import execute, VERSION
|
|
9
|
+
|
|
10
|
+
HOST = sys.argv[1]
|
|
11
|
+
if HOST not in ("kimi", "qwen", "doubao"):
|
|
12
|
+
raise ValueError("Unknown desktop adapter")
|
|
13
|
+
|
|
14
|
+
def tool(name, description, properties, required):
|
|
15
|
+
return {"name":name, "description":description, "inputSchema":{
|
|
16
|
+
"type":"object","properties":properties,"required":required,"additionalProperties":False}}
|
|
17
|
+
|
|
18
|
+
string = {"type":"string"}
|
|
19
|
+
tools = [
|
|
20
|
+
tool("officesdk_start", "Start working on a Word document, Excel spreadsheet or PowerPoint presentation. 工作总结、会议纪要、周报、预算表、台账和汇报演示默认用此入口。Use for everyday office file requests, even without a file extension or plugin name.", {"workspace":string}, []),
|
|
21
|
+
tool("officesdk_schema", "Get the input schema for an OfficeSDK editing operation before calling it.", {"tool":string}, ["tool"]),
|
|
22
|
+
tool("officesdk_call", "Create, read, change or save the original in the OfficeSDK editor using an operation from officesdk_start.", {"session":string,"tool":string,"args":{"type":"object"},"confirmedChoices":{"type":"object"},"workbenchUnavailable":{"type":"boolean","description":"Set only after the native InAppBrowser is unavailable or the user declines the right panel."}}, ["session","tool","args"])
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
def request(method, params):
|
|
26
|
+
if method == "initialize":
|
|
27
|
+
versions = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
28
|
+
version = params.get("protocolVersion")
|
|
29
|
+
return {"protocolVersion":version if version in versions else versions[0],"capabilities":{"tools":{}},
|
|
30
|
+
"serverInfo":{"name":"officesdk","version":VERSION}}
|
|
31
|
+
if method == "ping":
|
|
32
|
+
return {}
|
|
33
|
+
if method == "tools/list":
|
|
34
|
+
return {"tools":tools}
|
|
35
|
+
if method != "tools/call":
|
|
36
|
+
raise LookupError(method)
|
|
37
|
+
name, args = params.get("name"), params.get("arguments", {})
|
|
38
|
+
try:
|
|
39
|
+
if name == "officesdk_start":
|
|
40
|
+
result = execute(HOST, "begin", args)
|
|
41
|
+
result["operations"] = execute(HOST, "list", {})
|
|
42
|
+
elif name == "officesdk_schema":
|
|
43
|
+
result = execute(HOST, "schema", args)
|
|
44
|
+
elif name == "officesdk_call":
|
|
45
|
+
result = execute(HOST, "call", args)
|
|
46
|
+
else:
|
|
47
|
+
raise ValueError("Unknown OfficeSDK tool")
|
|
48
|
+
return {"content":[{"type":"text","text":json.dumps(result, ensure_ascii=False)}]}
|
|
49
|
+
except (OSError, ValueError, KeyError, RuntimeError, StopIteration) as error:
|
|
50
|
+
return {"isError":True, "content":[{"type":"text","text":str(error) or "Unknown OfficeSDK operation"}]}
|
|
51
|
+
|
|
52
|
+
for line in sys.stdin:
|
|
53
|
+
try:
|
|
54
|
+
message = json.loads(line)
|
|
55
|
+
if "id" not in message:
|
|
56
|
+
continue
|
|
57
|
+
reply = {"jsonrpc":"2.0","id":message["id"]}
|
|
58
|
+
try:
|
|
59
|
+
reply["result"] = request(message.get("method"), message.get("params") or {})
|
|
60
|
+
except LookupError:
|
|
61
|
+
reply["error"] = {"code":-32601,"message":"Method not found"}
|
|
62
|
+
print(json.dumps(reply, ensure_ascii=False), flush=True)
|
|
63
|
+
except (TypeError, ValueError):
|
|
64
|
+
print('{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Invalid JSON"}}',flush=True)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Use the installed editor from a native desktop extension or skill."""
|
|
2
|
+
import argparse
|
|
3
|
+
import fcntl
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
import uuid
|
|
10
|
+
|
|
11
|
+
ROOT = Path(__file__).resolve().parent
|
|
12
|
+
sys.path.insert(0, str(ROOT / "editor"))
|
|
13
|
+
import bridge
|
|
14
|
+
from native_questions import form
|
|
15
|
+
|
|
16
|
+
HOST_NAMES = {"kimi": "Kimi Work", "qwen": "千问办公", "doubao": "豆包工作"}
|
|
17
|
+
VERSION = json.loads((ROOT / "editor/package.json").read_text())["version"]
|
|
18
|
+
TOOLS = json.loads((ROOT / "editor/runtime/tools.json").read_text())
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def visible(value):
|
|
22
|
+
if isinstance(value, dict):
|
|
23
|
+
private = {"auth", "token", "bearer", "authorization", "capability", "headers", "editorurl", "viewurl"}
|
|
24
|
+
return {k: visible(v) for k, v in value.items() if k.lower() not in private}
|
|
25
|
+
if isinstance(value, list):
|
|
26
|
+
return [visible(item) for item in value]
|
|
27
|
+
if isinstance(value, str):
|
|
28
|
+
return re.sub(r"https?://(?:127\.0\.0\.1|localhost|\[::1\])[^\s\"']*", "[local editor]", value)
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def execute(host, action, request):
|
|
33
|
+
base = ROOT.parent.parent / "profiles" / host
|
|
34
|
+
bridge.DATA = base / "services" / ROOT.name
|
|
35
|
+
workspace = Path(json.loads((base / "settings.json").read_text())["workspace"])
|
|
36
|
+
if action == "version":
|
|
37
|
+
return {"host": HOST_NAMES[host], "version": VERSION}
|
|
38
|
+
if action == "list":
|
|
39
|
+
return [t["name"] for t in TOOLS]
|
|
40
|
+
if action == "schema":
|
|
41
|
+
return next(t["parameters"] for t in TOOLS if t["name"] == request["tool"])
|
|
42
|
+
if action == "begin":
|
|
43
|
+
session = str(uuid.uuid4())
|
|
44
|
+
root = Path(request.get("workspace") or workspace).expanduser().resolve(strict=True)
|
|
45
|
+
# An explicit task directory is allowed; never confer a system or home-wide grant.
|
|
46
|
+
if (not root.is_dir() or root in (Path("/"), Path.home()) or
|
|
47
|
+
not any(parent in root.parents or root == parent for parent in
|
|
48
|
+
(Path.home(), Path("/private/tmp"), Path(os.environ.get("TMPDIR", "/private/tmp")).resolve()))):
|
|
49
|
+
raise ValueError("Choose a task folder inside your home or temporary workspace.")
|
|
50
|
+
(base / "sessions").mkdir(exist_ok=True, mode=0o700)
|
|
51
|
+
with (base / "sessions" / session).open("x") as f:
|
|
52
|
+
json.dump({"workspace": str(root)}, f)
|
|
53
|
+
return {"session": session, "workspace": str(root)}
|
|
54
|
+
session = str(uuid.UUID(request["session"]))
|
|
55
|
+
name = request["tool"]
|
|
56
|
+
if name not in {t["name"] for t in TOOLS}:
|
|
57
|
+
raise ValueError("Unknown OfficeSDK tool")
|
|
58
|
+
args = request["args"]
|
|
59
|
+
if not isinstance(args, dict):
|
|
60
|
+
raise ValueError("args must be an object")
|
|
61
|
+
choices = None
|
|
62
|
+
if name == "presentation_plan":
|
|
63
|
+
questions, pages, styles = form(args)
|
|
64
|
+
choices = request.get("confirmedChoices")
|
|
65
|
+
if not choices:
|
|
66
|
+
return {"status": "awaiting_user", "questions": questions}
|
|
67
|
+
if str(choices.get("slideCount")) not in pages or choices.get("style") not in styles.values():
|
|
68
|
+
raise ValueError("Use the slide count and style confirmed by the user.")
|
|
69
|
+
choices = {"slideCount": str(choices["slideCount"]), "style": choices["style"]}
|
|
70
|
+
with (base / "sessions" / session).open("r+") as f:
|
|
71
|
+
fcntl.flock(f, fcntl.LOCK_EX)
|
|
72
|
+
record = json.load(f)
|
|
73
|
+
body = {"session": session, "cwd": record["workspace"]}
|
|
74
|
+
if name != "presentation_plan":
|
|
75
|
+
panel = bridge.call("bind", dict(body, surface="kimi-workbench"))
|
|
76
|
+
if not panel.get("ready") and not request.get("workbenchUnavailable"):
|
|
77
|
+
if host != "kimi":
|
|
78
|
+
return {"status":"open_in_host_workbench", "applied":False, "url":panel["launch"],
|
|
79
|
+
"instruction":"Navigate to this URL in the current client's built-in browser tab, then retry. Keep the one-time URL out of public messages and the system browser."}
|
|
80
|
+
return {
|
|
81
|
+
"status": "open_in_kimi_workbench",
|
|
82
|
+
"applied": False,
|
|
83
|
+
"action": {"tool": "InAppBrowser", "action": "navigate",
|
|
84
|
+
"params": {"url": panel["launch"], "newTab": True}},
|
|
85
|
+
"instruction": "Open this in the current Kimi chat's right panel using the native InAppBrowser tool. Then repeat the same OfficeSDK operation. If browser control is unavailable, repeat with workbenchUnavailable=true and tell the user. Never open an external browser or print this link."
|
|
86
|
+
}
|
|
87
|
+
else:
|
|
88
|
+
bridge.call("bind", body)
|
|
89
|
+
result = visible(bridge.call("tool", dict(body, name=name, args=args, humanChoices=choices)))
|
|
90
|
+
if isinstance(result, dict) and name != "presentation_plan" and host == "kimi" and panel.get("ready") and (name.endswith("_save") or result.get("officeFileCard")):
|
|
91
|
+
result["workbench"] = {"tool": "InAppBrowser", "action": "find_tab", "params": {"url": panel["url"]},
|
|
92
|
+
"instruction": "Keep this editor selected for delivery. Use the original file as the download link."}
|
|
93
|
+
return result
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
if __name__ == "__main__":
|
|
97
|
+
parser = argparse.ArgumentParser()
|
|
98
|
+
parser.add_argument("host", choices=HOST_NAMES)
|
|
99
|
+
parser.add_argument("action", choices=("version", "begin", "list", "schema", "call"))
|
|
100
|
+
parameters = parser.parse_args()
|
|
101
|
+
try:
|
|
102
|
+
body = {} if parameters.action in ("version", "list") or sys.stdin.isatty() else json.load(sys.stdin)
|
|
103
|
+
print(json.dumps(execute(parameters.host, parameters.action, body), ensure_ascii=False))
|
|
104
|
+
except Exception as error:
|
|
105
|
+
print(json.dumps({"error": visible(str(error))}, ensure_ascii=False), file=sys.stderr)
|
|
106
|
+
sys.exit(1)
|
package/routes.json
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
"dsh": {
|
|
3
3
|
"kind": "dsh-npm",
|
|
4
4
|
"package": "@officesdk/officesdk-plugin-dsh",
|
|
5
|
-
"asset": "officesdk-officesdk-plugin-dsh-1.0.
|
|
6
|
-
"size":
|
|
7
|
-
"sha256": "
|
|
5
|
+
"asset": "officesdk-officesdk-plugin-dsh-1.0.5.tgz",
|
|
6
|
+
"size": 1392967,
|
|
7
|
+
"sha256": "1f162faec910343d307faea32d2c63155a1676bd075b0fab02b9ecbbba71b4a8"
|
|
8
8
|
},
|
|
9
9
|
"hermes": {
|
|
10
10
|
"kind": "file-host",
|
|
11
|
-
"asset": "officesdk-hermes-1.0.
|
|
12
|
-
"sha256": "
|
|
13
|
-
"size":
|
|
11
|
+
"asset": "officesdk-hermes-1.0.5.tar.gz",
|
|
12
|
+
"sha256": "c7fe0282ff3ad24e1f58ce2ac8a3907f403d749274fecc23905e0f98a375e2e5",
|
|
13
|
+
"size": 1833041,
|
|
14
14
|
"manifest": "package.json",
|
|
15
15
|
"name": "officesdk-plugin-hermes",
|
|
16
16
|
"platforms": [
|
|
@@ -19,20 +19,53 @@
|
|
|
19
19
|
},
|
|
20
20
|
"minimax": {
|
|
21
21
|
"kind": "file-host",
|
|
22
|
-
"asset": "officesdk-minimax-1.0.
|
|
23
|
-
"sha256": "
|
|
24
|
-
"size":
|
|
22
|
+
"asset": "officesdk-minimax-1.0.5.tar.gz",
|
|
23
|
+
"sha256": "4abf275715bdfab1b905d5d0ea50ed671e1aea5fe870e5e7fc9f47cad19a3c84",
|
|
24
|
+
"size": 1149417,
|
|
25
25
|
"manifest": ".minimax-plugin/plugin.json",
|
|
26
26
|
"name": "officesdk-minimax",
|
|
27
27
|
"platforms": [
|
|
28
28
|
"darwin-arm64"
|
|
29
29
|
]
|
|
30
30
|
},
|
|
31
|
+
"kimi": {
|
|
32
|
+
"kind": "personal-import",
|
|
33
|
+
"asset": "officesdk-hermes-1.0.5.tar.gz",
|
|
34
|
+
"sha256": "c7fe0282ff3ad24e1f58ce2ac8a3907f403d749274fecc23905e0f98a375e2e5",
|
|
35
|
+
"size": 1833041,
|
|
36
|
+
"manifest": "package.json",
|
|
37
|
+
"name": "officesdk-plugin-hermes",
|
|
38
|
+
"platforms": [
|
|
39
|
+
"darwin-arm64"
|
|
40
|
+
]
|
|
41
|
+
},
|
|
42
|
+
"qwen": {
|
|
43
|
+
"kind": "personal-import",
|
|
44
|
+
"asset": "officesdk-hermes-1.0.5.tar.gz",
|
|
45
|
+
"sha256": "c7fe0282ff3ad24e1f58ce2ac8a3907f403d749274fecc23905e0f98a375e2e5",
|
|
46
|
+
"size": 1833041,
|
|
47
|
+
"manifest": "package.json",
|
|
48
|
+
"name": "officesdk-plugin-hermes",
|
|
49
|
+
"platforms": [
|
|
50
|
+
"darwin-arm64"
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
"doubao": {
|
|
54
|
+
"kind": "personal-import",
|
|
55
|
+
"asset": "officesdk-hermes-1.0.5.tar.gz",
|
|
56
|
+
"sha256": "c7fe0282ff3ad24e1f58ce2ac8a3907f403d749274fecc23905e0f98a375e2e5",
|
|
57
|
+
"size": 1833041,
|
|
58
|
+
"manifest": "package.json",
|
|
59
|
+
"name": "officesdk-plugin-hermes",
|
|
60
|
+
"platforms": [
|
|
61
|
+
"darwin-arm64"
|
|
62
|
+
]
|
|
63
|
+
},
|
|
31
64
|
"zcode": {
|
|
32
65
|
"kind": "zcode-market",
|
|
33
|
-
"asset": "officesdk-zcode-1.0.
|
|
34
|
-
"size":
|
|
35
|
-
"sha256": "
|
|
66
|
+
"asset": "officesdk-zcode-1.0.5.tar.gz",
|
|
67
|
+
"size": 1572195,
|
|
68
|
+
"sha256": "3f1383396a81609bf740232e63750edc604917a3076aa464d767e19d9905bdb1",
|
|
36
69
|
"manifest": ".zcode-plugin/plugin.json",
|
|
37
70
|
"name": "officesdk",
|
|
38
71
|
"platforms": [
|
|
@@ -41,9 +74,9 @@
|
|
|
41
74
|
},
|
|
42
75
|
"codex": {
|
|
43
76
|
"kind": "codex-market",
|
|
44
|
-
"asset": "officesdk-codex-1.0.
|
|
45
|
-
"size":
|
|
46
|
-
"sha256": "
|
|
77
|
+
"asset": "officesdk-codex-1.0.5.tar.gz",
|
|
78
|
+
"size": 1666569,
|
|
79
|
+
"sha256": "354cd7374176d972c9d33e81a89425fa87b24eb7326d1375eb90353bfeea14c7",
|
|
47
80
|
"manifest": ".codex-plugin/plugin.json",
|
|
48
81
|
"name": "officesdk",
|
|
49
82
|
"platforms": [
|
|
@@ -52,9 +85,9 @@
|
|
|
52
85
|
},
|
|
53
86
|
"workbuddy": {
|
|
54
87
|
"kind": "workbuddy-market",
|
|
55
|
-
"asset": "officesdk-workbuddy-1.0.
|
|
56
|
-
"size":
|
|
57
|
-
"sha256": "
|
|
88
|
+
"asset": "officesdk-workbuddy-1.0.5.tar.gz",
|
|
89
|
+
"size": 1513734,
|
|
90
|
+
"sha256": "1f5aa948818cb8fa1092e18d138f64ddfd5ba32508ad5a2091a6e81266ae9d88",
|
|
58
91
|
"manifest": ".workbuddy-plugin/plugin.json",
|
|
59
92
|
"name": "officesdk",
|
|
60
93
|
"platforms": [
|
|
@@ -63,9 +96,9 @@
|
|
|
63
96
|
},
|
|
64
97
|
"antigravity": {
|
|
65
98
|
"kind": "file-host",
|
|
66
|
-
"asset": "officesdk-antigravity-1.0.
|
|
67
|
-
"size":
|
|
68
|
-
"sha256": "
|
|
99
|
+
"asset": "officesdk-antigravity-1.0.5.tar.gz",
|
|
100
|
+
"size": 1529253,
|
|
101
|
+
"sha256": "2e38ed3e8b6ea64427cac026e566f35e76e24fead74ce9314e9e08416bbb8be5",
|
|
69
102
|
"manifest": "plugin.json",
|
|
70
103
|
"name": "officesdk",
|
|
71
104
|
"platforms": [
|
|
@@ -74,20 +107,20 @@
|
|
|
74
107
|
},
|
|
75
108
|
"grok": {
|
|
76
109
|
"kind": "vsix",
|
|
77
|
-
"asset": "officesdk-ide-1.0.
|
|
110
|
+
"asset": "officesdk-ide-1.0.5-darwin-arm64.vsix",
|
|
78
111
|
"name": "officesdk.officesdk-plugin-grok",
|
|
79
|
-
"size":
|
|
80
|
-
"sha256": "
|
|
112
|
+
"size": 1822608,
|
|
113
|
+
"sha256": "83876466d4dba558bcce1ad2fd2fca9aa07b1fa55f77d40ca7ce9c003d793f88",
|
|
81
114
|
"platforms": [
|
|
82
115
|
"darwin-arm64"
|
|
83
116
|
]
|
|
84
117
|
},
|
|
85
118
|
"cursor": {
|
|
86
119
|
"kind": "vsix",
|
|
87
|
-
"asset": "officesdk-ide-1.0.
|
|
120
|
+
"asset": "officesdk-ide-1.0.5-darwin-arm64.vsix",
|
|
88
121
|
"name": "officesdk.officesdk-plugin-grok",
|
|
89
|
-
"size":
|
|
90
|
-
"sha256": "
|
|
122
|
+
"size": 1822608,
|
|
123
|
+
"sha256": "83876466d4dba558bcce1ad2fd2fca9aa07b1fa55f77d40ca7ce9c003d793f88",
|
|
91
124
|
"platforms": [
|
|
92
125
|
"darwin-arm64"
|
|
93
126
|
]
|