@officesdk/officesdk-plugin 0.0.0-stage → 1.0.4
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/LICENSE +21 -0
- package/NOTICE +23 -0
- package/README.md +14 -2
- package/bin/check-package.mjs +9 -0
- package/bin/codex.mjs +63 -0
- package/bin/file-host.mjs +120 -0
- package/bin/hosts.mjs +78 -0
- package/bin/ide.mjs +70 -0
- package/bin/install.mjs +62 -0
- package/bin/workbuddy.mjs +109 -0
- package/bin/zcode.mjs +91 -0
- package/kit-manifest.json +3465 -0
- package/package.json +38 -4
- package/routes.json +95 -0
- package/runtime/download-sources.mjs +107 -0
- package/runtime/downloader.mjs +326 -0
- package/runtime/lease.mjs +88 -0
- package/runtime/office-kit.mjs +150 -0
- package/runtime/runtime.mjs +139 -0
- package/runtime/sources.mjs +85 -0
- package/runtime/tar.mjs +235 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 OfficeSDK contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
OfficeSDK plugin for AI agents
|
|
2
|
+
Copyright (c) 2026 OfficeSDK contributors
|
|
3
|
+
|
|
4
|
+
The source code in this repository is licensed under the MIT License (see LICENSE).
|
|
5
|
+
|
|
6
|
+
This repository contains the source code of the plugin only. It depends on the following external components,
|
|
7
|
+
which are not part of this repository and are not covered by its LICENSE:
|
|
8
|
+
|
|
9
|
+
office-kit (Kit document engine, editor page and editor resources)
|
|
10
|
+
Copyright (c) Shimo. All rights reserved.
|
|
11
|
+
- The Kit and the editor resources are downloaded by the plugin on first use from office-kit's official release
|
|
12
|
+
(the Kit from its GitHub release, the editor resources from its npm package), as described by kit-manifest.json,
|
|
13
|
+
and checked against it.
|
|
14
|
+
- The editor page (offline-editor.js) and the Sheet host fonts that the published plugin package carries are taken
|
|
15
|
+
at build time from the pinned sources named in components/office-kit.json (tooling/kit/vendor.mjs).
|
|
16
|
+
Their use is governed by office-kit's own terms.
|
|
17
|
+
|
|
18
|
+
DeepSeek Harness packages (@deepseek-ai/*)
|
|
19
|
+
DeepSeek Harness provides its peer dependencies at run time. Other native adapters
|
|
20
|
+
list any bundled packages and their licenses in their own third-party notices.
|
|
21
|
+
|
|
22
|
+
Third-party open-source packages bundled into the published plugin are listed in the package's
|
|
23
|
+
THIRD-PARTY-NOTICES.md, generated at build time.
|
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# OfficeSDK for AI Agent
|
|
2
2
|
|
|
3
|
-
|
|
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)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {readFile,access} from 'node:fs/promises';
|
|
2
|
+
const root=new URL('../',import.meta.url);
|
|
3
|
+
try {
|
|
4
|
+
const routes=JSON.parse(await readFile(new URL('routes.json',root)));
|
|
5
|
+
await Promise.all(['runtime/runtime.mjs','kit-manifest.json','NOTICE'].map(file=>access(new URL(file,root))));
|
|
6
|
+
if(!routes.dsh || !Object.values(routes).some(route=>route.asset))throw Error('Missing native packages');
|
|
7
|
+
} catch(cause) {
|
|
8
|
+
throw Error('Assemble the verified native assets with tooling/suite/pack-installer.mjs before packing OfficeSDK.',{cause});
|
|
9
|
+
}
|
package/bin/codex.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import {execFile} from 'node:child_process';
|
|
5
|
+
import {promisify} from 'node:util';
|
|
6
|
+
const run=promisify(execFile);
|
|
7
|
+
export async function prepareMarket(staging,target,settings,version,project) {
|
|
8
|
+
if(project) {
|
|
9
|
+
const chosen=await fs.realpath(project);
|
|
10
|
+
if(chosen===os.homedir()||chosen===path.parse(chosen).root||!(await fs.stat(chosen)).isDirectory())throw Error('Choose a document workspace for Codex');
|
|
11
|
+
settings.workspace=chosen;
|
|
12
|
+
}
|
|
13
|
+
const finalRoot=path.join(target,'plugins/officesdk');
|
|
14
|
+
const mcpFile=path.join(staging,'.mcp.json');
|
|
15
|
+
const mcp=JSON.parse(await fs.readFile(mcpFile,'utf8'));
|
|
16
|
+
Object.assign(mcp.mcpServers.officesdk,{command:process.execPath,args:[path.join(finalRoot,'server.mjs')],cwd:finalRoot});
|
|
17
|
+
await fs.writeFile(mcpFile,JSON.stringify(mcp,null,2)+'\n');
|
|
18
|
+
const recipe=path.join(staging,'assembly');
|
|
19
|
+
await run('npm',['ci','--ignore-scripts','--no-audit','--no-fund','--registry=https://registry.npmjs.org'],{cwd:recipe,timeout:150000});
|
|
20
|
+
await run(process.execPath,[path.join(recipe,'assemble.mjs'),settings.editor],{cwd:recipe,timeout:120000,maxBuffer:2097152});
|
|
21
|
+
await fs.rm(recipe,{recursive:true});
|
|
22
|
+
const wrapper=staging+'-market';
|
|
23
|
+
await fs.mkdir(path.join(wrapper,'.agents/plugins'),{recursive:true});
|
|
24
|
+
await fs.mkdir(path.join(wrapper,'plugins'));
|
|
25
|
+
const entry={name:'officesdk',source:{source:'local',path:'./plugins/officesdk'},category:'Productivity',policy:{installation:'AVAILABLE',authentication:'ON_INSTALL'}};
|
|
26
|
+
await fs.writeFile(path.join(wrapper,'.agents/plugins/marketplace.json'),JSON.stringify({name:'officesdk',interface:{displayName:'OfficeSDK'},plugins:[entry]},null,2)+'\n');
|
|
27
|
+
await fs.rename(staging,path.join(wrapper,'plugins/officesdk'));
|
|
28
|
+
await fs.rename(wrapper,staging);
|
|
29
|
+
}
|
|
30
|
+
export async function marketManager(target) {
|
|
31
|
+
let command='codex';
|
|
32
|
+
for(const app of ['/Applications/Codex.app',path.join(os.homedir(),'Applications/Codex.app')]) {
|
|
33
|
+
const binary=path.join(app,'Contents/Resources/codex');
|
|
34
|
+
if(await fs.access(binary,fs.constants.X_OK).then(()=>true,()=>false)){command=binary;break;}
|
|
35
|
+
}
|
|
36
|
+
async function manage(...args) {
|
|
37
|
+
const {stdout}=await run(command,['plugin',...args,'--json'],{timeout:60000});
|
|
38
|
+
return JSON.parse(stdout);
|
|
39
|
+
}
|
|
40
|
+
const known=(await manage('marketplace','list')).marketplaces;
|
|
41
|
+
const existing=known.find(x=>x.name==='officesdk');
|
|
42
|
+
if(existing && await fs.realpath(existing.root)!==await fs.realpath(target))throw Error('A different marketplace is registered as OfficeSDK');
|
|
43
|
+
const own=async()=>(await manage('list','--marketplace','officesdk')).installed.find(x=>x.name==='officesdk');
|
|
44
|
+
const previous=existing?await own():null;
|
|
45
|
+
const oldMarket=known.find(x=>x.name==='officesdk-development');
|
|
46
|
+
const local=oldMarket?(await manage('list','--marketplace',oldMarket.name)).installed.find(x=>x.name==='officesdk'&&x.enabled):null;
|
|
47
|
+
let added=false,changed=false,removedLegacy=false;
|
|
48
|
+
return {
|
|
49
|
+
async activate(version) {
|
|
50
|
+
if(!existing){await manage('marketplace','add',target);added=true;}
|
|
51
|
+
// Refresh the host's cached manifest as well as the marketplace files on reinstall.
|
|
52
|
+
await manage('add','officesdk@officesdk');changed=true;
|
|
53
|
+
const current=await own();
|
|
54
|
+
if(!current?.enabled||current.version!==version)throw Error('Codex did not enable OfficeSDK '+version);
|
|
55
|
+
if(local){await manage('remove',local.pluginId);removedLegacy=true;}
|
|
56
|
+
},
|
|
57
|
+
async rollback() {
|
|
58
|
+
if(removedLegacy)await manage('add',local.pluginId);
|
|
59
|
+
if(changed){if(previous)await manage('add',previous.pluginId);else await manage('remove','officesdk@officesdk');}
|
|
60
|
+
if(added)await manage('marketplace','remove','officesdk');
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {Readable} from 'node:stream';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {fileURLToPath} from 'node:url';
|
|
7
|
+
|
|
8
|
+
async function readSettings(file) {
|
|
9
|
+
try { return JSON.parse(await fs.readFile(file,'utf8')); }
|
|
10
|
+
catch(error) { if(error.code==='ENOENT')return {}; throw error; }
|
|
11
|
+
}
|
|
12
|
+
async function exists(file) {
|
|
13
|
+
try { return await fs.lstat(file); } catch(error) { if(error.code==='ENOENT')return null; throw error; }
|
|
14
|
+
}
|
|
15
|
+
export async function assetBytes(route, version, assetDir) {
|
|
16
|
+
let bytes;
|
|
17
|
+
if(assetDir) bytes=await fs.readFile(path.join(assetDir,route.asset));
|
|
18
|
+
else {
|
|
19
|
+
const url = new URL('https://github.com/officesdk/officesdk-plugin/releases/download/v'+version+'/'+route.asset);
|
|
20
|
+
const response=await fetch(url,{signal:AbortSignal.timeout(120000)});
|
|
21
|
+
if(!response.ok)throw Error('Release download returned '+response.status+' for '+route.asset);
|
|
22
|
+
const chunks=[];let length=0;
|
|
23
|
+
for await(const chunk of response.body){
|
|
24
|
+
length+=chunk.length;
|
|
25
|
+
if(length>route.size)throw Error('Release attachment exceeds its expected size');
|
|
26
|
+
chunks.push(chunk);
|
|
27
|
+
}
|
|
28
|
+
bytes=Buffer.concat(chunks);
|
|
29
|
+
}
|
|
30
|
+
if(bytes.length!==route.size||createHash('sha256').update(bytes).digest('hex')!==route.sha256)throw Error('Release checksum mismatch for '+route.asset);
|
|
31
|
+
return bytes;
|
|
32
|
+
}
|
|
33
|
+
export function hostLocations(host, home=os.homedir(), env=process.env) {
|
|
34
|
+
if(host==='workbuddy'||host==='codex'||host==='zcode')return {target:path.join(home,'.officesdk',host,'marketplace'),data:path.join(home,'.officesdk',host)};
|
|
35
|
+
if(host==='hermes') {
|
|
36
|
+
const profile=env.HERMES_HOME||path.join(home,'.hermes');
|
|
37
|
+
if(!path.isAbsolute(profile)) throw Error('HERMES_HOME must be an absolute path');
|
|
38
|
+
return {target:path.join(profile,'plugins/officesdk'),data:path.join(profile,'officesdk-data')};
|
|
39
|
+
}
|
|
40
|
+
if(host==='antigravity')return {target:path.join(home,'.gemini/config/plugins/officesdk'),data:path.join(home,'.officesdk/antigravity')};
|
|
41
|
+
if(host==='minimax')return {target:path.join(home,'.minimax/plugins/officesdk-minimax'),data:path.join(home,'Library/Application Support/OfficeSDK MiniMax')};
|
|
42
|
+
throw Error('Unsupported file installation target '+host);
|
|
43
|
+
}
|
|
44
|
+
export async function prepareEngine() {
|
|
45
|
+
const {OfficeKitRuntime}=await import('../runtime/runtime.mjs');
|
|
46
|
+
const manifest=JSON.parse(await fs.readFile(new URL('../kit-manifest.json',import.meta.url),'utf8'));
|
|
47
|
+
const runtime=new OfficeKitRuntime({manifest,dataRoot:path.join(os.homedir(),'.officesdk'),packageRoot:fileURLToPath(new URL('../',import.meta.url))});
|
|
48
|
+
try { await runtime.binary(); return {kit:runtime.kitDir,editor:runtime.editorDir}; }
|
|
49
|
+
finally { runtime.dispose(); }
|
|
50
|
+
}
|
|
51
|
+
export async function installFileHost({host, route, version, assetDir, project}) {
|
|
52
|
+
const {target,data}=hostLocations(host);
|
|
53
|
+
const bytes=await assetBytes(route,version,assetDir);
|
|
54
|
+
const {extractTar}=await import('../runtime/tar.mjs');
|
|
55
|
+
const {acquireLease}=await import('../runtime/lease.mjs');
|
|
56
|
+
const parent=path.dirname(target);
|
|
57
|
+
await fs.mkdir(parent,{recursive:true});await fs.mkdir(data,{recursive:true,mode:0o700});
|
|
58
|
+
const lock=await acquireLease(path.join(data,'.install.lock'));
|
|
59
|
+
let scratch, staging, oldMoved=false, activated=false, keepBackup=false;
|
|
60
|
+
try {
|
|
61
|
+
const integration=host==='workbuddy'?await import('./workbuddy.mjs'):host==='codex'?await import('./codex.mjs'):host==='zcode'?await import('./zcode.mjs'):null;
|
|
62
|
+
const previous=await exists(target);
|
|
63
|
+
if(previous) {
|
|
64
|
+
if(!previous.isDirectory())throw Error('The target is not an OfficeSDK directory: '+target);
|
|
65
|
+
if((await readSettings(path.join(target,integration?'plugins/officesdk':'',route.manifest))).name!==route.name)throw Error('The target belongs to another plugin: '+target);
|
|
66
|
+
}
|
|
67
|
+
scratch=await fs.mkdtemp(path.join(parent,'.officesdk-install-'));
|
|
68
|
+
staging=path.join(scratch,'new');
|
|
69
|
+
await extractTar(Readable.from([bytes]),staging,{gzip:true,strip:'package'});
|
|
70
|
+
const identity=await readSettings(path.join(staging,route.manifest));
|
|
71
|
+
if(identity.name!==route.name||identity.version!==version)throw Error('Native plugin identity or version mismatch');
|
|
72
|
+
const engine=await prepareEngine();
|
|
73
|
+
const settingsFile=path.join(data,'settings.json');
|
|
74
|
+
const settings=await readSettings(settingsFile);
|
|
75
|
+
if(!settings||typeof settings!=='object'||Array.isArray(settings))throw Error('Invalid OfficeSDK settings in '+settingsFile);
|
|
76
|
+
const merged={...settings,...engine};
|
|
77
|
+
if(integration)await integration.prepareMarket(staging,target,merged,version,project);
|
|
78
|
+
const manager=integration?await integration.marketManager(target):null;
|
|
79
|
+
if(host==='hermes'){
|
|
80
|
+
merged.node=process.execPath;
|
|
81
|
+
merged.workspace??=path.join(data,'workspace');
|
|
82
|
+
merged.pdfConverter??='/Applications/LibreOffice.app/Contents/MacOS/soffice';
|
|
83
|
+
await fs.mkdir(merged.workspace,{recursive:true});
|
|
84
|
+
}
|
|
85
|
+
const hadSettings=Boolean(await exists(settingsFile));
|
|
86
|
+
let settingsCommitted=false;
|
|
87
|
+
const configTmp=await fs.mkdtemp(path.join(data,'.settings-'));
|
|
88
|
+
try {
|
|
89
|
+
const config=path.join(configTmp,'settings.json');
|
|
90
|
+
await fs.writeFile(config,JSON.stringify(merged,null,2)+'\n',{mode:0o600});
|
|
91
|
+
if(hadSettings)await fs.copyFile(settingsFile,path.join(configTmp,'previous'));
|
|
92
|
+
if(previous){ await fs.rename(target,path.join(scratch,'previous'));oldMoved=true; }
|
|
93
|
+
await fs.rename(staging,target);activated=true;
|
|
94
|
+
await fs.rename(config,settingsFile);settingsCommitted=true;
|
|
95
|
+
if(manager)await manager.activate(version);
|
|
96
|
+
} catch(error) {
|
|
97
|
+
if(activated){
|
|
98
|
+
try { await fs.rename(target,staging); }
|
|
99
|
+
catch(recovery){keepBackup=true;throw Error('Could not roll back OfficeSDK. Recovery files: '+scratch,{cause:recovery});}
|
|
100
|
+
}
|
|
101
|
+
if(oldMoved) {
|
|
102
|
+
try { await fs.rename(path.join(scratch,'previous'),target); }
|
|
103
|
+
catch(recovery){keepBackup=true;throw Error('Restore the previous OfficeSDK from '+path.join(scratch,'previous'),{cause:recovery});}
|
|
104
|
+
}
|
|
105
|
+
if(settingsCommitted){
|
|
106
|
+
if(hadSettings)await fs.rename(path.join(configTmp,'previous'),settingsFile);
|
|
107
|
+
else await fs.rm(settingsFile,{force:true});
|
|
108
|
+
}
|
|
109
|
+
if(manager){
|
|
110
|
+
try {await manager.rollback();}
|
|
111
|
+
catch(recovery){throw new AggregateError([error,recovery],'Installation failed and registry recovery failed: '+error.message);}
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
} finally {await fs.rm(configTmp,{recursive:true,force:true});}
|
|
115
|
+
if(manager){console.log('Installed and enabled OfficeSDK '+version+' in '+host+'.');return;}
|
|
116
|
+
console.log('Installed OfficeSDK '+version+' for '+host+'. Restart the client and enable OfficeSDK in its plugin manager.');
|
|
117
|
+
} finally {
|
|
118
|
+
try { if(scratch&&!keepBackup)await fs.rm(scratch,{recursive:true,force:true}); } finally { await lock.release(); }
|
|
119
|
+
}
|
|
120
|
+
}
|
package/bin/hosts.mjs
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
|
|
4
|
+
const clients = {
|
|
5
|
+
dsh: ['DeepSeek Harness', 'dsh'],
|
|
6
|
+
workbuddy: ['WorkBuddy'],
|
|
7
|
+
codex: ['Codex'],
|
|
8
|
+
antigravity: ['Antigravity', 'agy'],
|
|
9
|
+
grok: ['Grok Build', 'grok-build'],
|
|
10
|
+
hermes: ['Hermes Agent', 'hermes'],
|
|
11
|
+
minimax: ['MiniMax Code', 'minimax-code'],
|
|
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'],
|
|
19
|
+
qwen: ['QwenWorkCN', 'Qwen Work', '千问办公'],
|
|
20
|
+
doubao: ['DoubaoWork', 'Doubao Work', '豆包工作']
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const hosts = Object.keys(clients);
|
|
24
|
+
|
|
25
|
+
function clientId(value) {
|
|
26
|
+
if (!value) return undefined;
|
|
27
|
+
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
|
+
return hosts.find(id => id === name || clients[id].some(alias => alias.toLowerCase() === name));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function chooseHost(explicit, env, parents) {
|
|
37
|
+
const specified = explicit || env.OFFICESDK_HOST;
|
|
38
|
+
if (specified) {
|
|
39
|
+
const found = clientId(specified);
|
|
40
|
+
if (!found) throw Error('Unknown host: ' + specified + '. Choose one of ' + hosts.join(', '));
|
|
41
|
+
return found;
|
|
42
|
+
}
|
|
43
|
+
for (const executable of parents) {
|
|
44
|
+
const bundle = executable.match(/(?:^|\/)([^/]+)\.app\/Contents\//i);
|
|
45
|
+
const found = clientId(path.basename(executable).replace(/\.exe$/i, '')) || clientId(bundle?.[1]);
|
|
46
|
+
if (found) return found;
|
|
47
|
+
}
|
|
48
|
+
const signals = new Set();
|
|
49
|
+
// WorkBuddy can run chat commands in a detached shell without an app parent.
|
|
50
|
+
if (env.WORKBUDDY_CONFIG_DIR || env.WORKBUDDY_RESOURCES_PATH ||
|
|
51
|
+
(env.CODEBUDDY_CONFIG_DIR && path.basename(env.CODEBUDDY_CONFIG_DIR) === '.workbuddy')) signals.add('workbuddy');
|
|
52
|
+
if (env.CODEX_THREAD_ID) signals.add('codex');
|
|
53
|
+
if (env.CURSOR_AGENT === '1') signals.add('cursor');
|
|
54
|
+
const terminal = clientId(env.TERM_PROGRAM);
|
|
55
|
+
if (terminal) signals.add(terminal);
|
|
56
|
+
if (signals.size === 1) return [...signals][0];
|
|
57
|
+
throw Error('Select the current client using --host <name>. Available: ' + hosts.join(', '));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function parentExecutables() {
|
|
61
|
+
const result = [];
|
|
62
|
+
if (process.platform === 'win32') return result;
|
|
63
|
+
let pid = process.ppid;
|
|
64
|
+
for (let depth = 0; pid > 1 && depth < 18; depth++) {
|
|
65
|
+
let row;
|
|
66
|
+
try {
|
|
67
|
+
row = execFileSync('ps', ['-p', String(pid), '-o', 'ppid=', '-o', 'comm='],
|
|
68
|
+
{ encoding:'utf8', timeout:1500, stdio:['ignore', 'pipe', 'ignore'] }).trim();
|
|
69
|
+
} catch { break; }
|
|
70
|
+
const match = row.match(/^(\d+)\s+(.+)$/);
|
|
71
|
+
if (!match) break;
|
|
72
|
+
result.push(match[2]);
|
|
73
|
+
const parent = Number(match[1]);
|
|
74
|
+
if (parent === pid) break;
|
|
75
|
+
pid = parent;
|
|
76
|
+
}
|
|
77
|
+
return result;
|
|
78
|
+
}
|
package/bin/ide.mjs
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import {execFile} from 'node:child_process';
|
|
5
|
+
import {promisify} from 'node:util';
|
|
6
|
+
import {assetBytes,prepareEngine} from './file-host.mjs';
|
|
7
|
+
const run=promisify(execFile);
|
|
8
|
+
async function optional(file) {try{return await fs.readFile(file,'utf8');}catch(e){if(e.code==='ENOENT')return;throw e;}}
|
|
9
|
+
async function put(file, bytes) {
|
|
10
|
+
await fs.mkdir(path.dirname(file),{recursive:true});
|
|
11
|
+
const tmp=await fs.mkdtemp(path.join(path.dirname(file),'.officesdk-write-'));
|
|
12
|
+
try {const staged=path.join(tmp,'new');await fs.writeFile(staged,bytes,{mode:0o600});await fs.rename(staged,file);}
|
|
13
|
+
finally{await fs.rm(tmp,{recursive:true,force:true});}
|
|
14
|
+
}
|
|
15
|
+
async function registerProject(project, folder) {
|
|
16
|
+
const configFile=path.join(project,'.cursor','mcp.json'), rulesFile=path.join(project,'.cursor/rules/officesdk.mdc');
|
|
17
|
+
const skillFile=path.join(os.homedir(),'.cursor/skills/officesdk/SKILL.md');
|
|
18
|
+
const shim=path.join(os.homedir(),'.officesdk/cursor/project-mcp.cjs');
|
|
19
|
+
const config=JSON.parse(await optional(configFile)??'{}');
|
|
20
|
+
const servers=config.mcpServers??={};
|
|
21
|
+
if(!servers||typeof servers!=='object'||Array.isArray(servers))throw Error('Invalid Cursor mcpServers configuration');
|
|
22
|
+
const previous=servers['OfficeSDK Project'];
|
|
23
|
+
if(previous && !previous.args?.includes('--cursor-project'))throw Error('The OfficeSDK Project name is already in use in this project');
|
|
24
|
+
const rule=await fs.readFile(path.join(folder,'cursor/office-tasks.mdc'),'utf8');
|
|
25
|
+
const skill=await fs.readFile(path.join(folder,'cursor/skills/officesdk/SKILL.md'),'utf8');
|
|
26
|
+
for(const [file,bytes] of [[rulesFile,rule],[skillFile,skill]]){
|
|
27
|
+
const current=await optional(file);
|
|
28
|
+
if(current && current!==bytes && !current.includes('OfficeSDK'))throw Error('An unrelated file already exists at '+file);
|
|
29
|
+
}
|
|
30
|
+
await put(shim,'require('+JSON.stringify(path.join(folder,'mcp.cjs'))+');\n');
|
|
31
|
+
await put(rulesFile,rule);await put(skillFile,skill);
|
|
32
|
+
servers['OfficeSDK Project']={command:process.execPath,args:[shim,'--cursor-project',project]};
|
|
33
|
+
await put(configFile,JSON.stringify(config,null,2)+'\n');
|
|
34
|
+
}
|
|
35
|
+
export async function installExtension({host,route,version,values}) {
|
|
36
|
+
const project=await fs.realpath(values.project||process.cwd());
|
|
37
|
+
if(host==='cursor' && (project===os.homedir()||project===path.parse(project).root||!(await fs.stat(project)).isDirectory()))throw Error('Choose the target Cursor workspace using --project <directory>');
|
|
38
|
+
const name=host==='cursor'?'cursor':'grok-build';
|
|
39
|
+
let command=name;
|
|
40
|
+
const appName=host==='cursor'?'Cursor.app':'Grok Build.app';
|
|
41
|
+
for(const applications of [path.join(os.homedir(),'Applications'),'/Applications']) {
|
|
42
|
+
const bundled=path.join(applications,appName,'Contents/Resources/app/bin',name);
|
|
43
|
+
if(await fs.access(bundled,fs.constants.X_OK).then(()=>true,()=>false)) {
|
|
44
|
+
command=bundled;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const root=path.resolve(values['extensions-dir']||path.join(os.homedir(),'.cursor/extensions'));
|
|
49
|
+
const args=['--extensions-dir',root];
|
|
50
|
+
if(values['user-data-dir'])args.push('--user-data-dir',path.resolve(values['user-data-dir']));
|
|
51
|
+
const bytes=await assetBytes(route,version,values['asset-dir']);
|
|
52
|
+
let tmp;
|
|
53
|
+
const {acquireLease}=await import('../runtime/lease.mjs');
|
|
54
|
+
const lock=await acquireLease(path.join(os.homedir(),'.officesdk','ide-install.lock'));
|
|
55
|
+
try {
|
|
56
|
+
tmp=await fs.mkdtemp(path.join(os.tmpdir(),'officesdk-vsix-'));
|
|
57
|
+
await prepareEngine();
|
|
58
|
+
const file=path.join(tmp,route.asset);
|
|
59
|
+
await fs.writeFile(file,bytes);
|
|
60
|
+
await run(command,[...args,'--install-extension',file,'--force'],{timeout:120000});
|
|
61
|
+
const entries=JSON.parse(await fs.readFile(path.join(root,'extensions.json'),'utf8'));
|
|
62
|
+
const entry=entries.find(row=>row.identifier?.id===route.name && row.version===version);
|
|
63
|
+
if(!entry?.relativeLocation || path.basename(entry.relativeLocation)!==entry.relativeLocation)throw Error('The client did not register OfficeSDK '+version);
|
|
64
|
+
const folder=path.join(root,entry.relativeLocation);
|
|
65
|
+
const manifest=JSON.parse(await fs.readFile(path.join(folder,'package.json'),'utf8'));
|
|
66
|
+
if(manifest.publisher+'.'+manifest.name!==route.name || manifest.version!==version)throw Error('Installed extension identity mismatch');
|
|
67
|
+
if(host==='cursor')await registerProject(project,folder);
|
|
68
|
+
console.log('Installed OfficeSDK '+version+' for '+host+'. Reopen the workspace to activate the extension.');
|
|
69
|
+
} finally { try{if(tmp)await fs.rm(tmp,{recursive:true,force:true});}finally{await lock.release();} }
|
|
70
|
+
}
|
package/bin/install.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, accessSync, constants } from 'node:fs';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { chooseHost, parentExecutables, hosts } from './hosts.mjs';
|
|
6
|
+
|
|
7
|
+
const readJson = path => JSON.parse(readFileSync(new URL(path, import.meta.url), 'utf8'));
|
|
8
|
+
const { version } = readJson('../package.json');
|
|
9
|
+
const routes = readJson('../routes.json');
|
|
10
|
+
|
|
11
|
+
async function run() {
|
|
12
|
+
const { values } = parseArgs({ options: {
|
|
13
|
+
host: { type: 'string' }, version: { type: 'boolean' }, help: { type: 'boolean' },
|
|
14
|
+
'dry-run': { type: 'boolean' }, 'asset-dir': {type:'string'}, project:{type:'string'}, 'user-data-dir':{type:'string'}, 'extensions-dir':{type:'string'}
|
|
15
|
+
}});
|
|
16
|
+
if (values.version) return console.log(version);
|
|
17
|
+
if (values.help) return console.log('officesdk-plugin [--host <name>] [--dry-run]\n' + hosts.join(', '));
|
|
18
|
+
const host = chooseHost(values.host, process.env, parentExecutables());
|
|
19
|
+
const route = routes[host];
|
|
20
|
+
if (!route) throw Error('OfficeSDK ' + version + ' has no verified installation package for ' + host + '.');
|
|
21
|
+
if(['codex-market','zcode-market','workbuddy-market','file-host','vsix'].includes(route.kind)) {
|
|
22
|
+
const platform=process.platform+'-'+process.arch;
|
|
23
|
+
if(!route.platforms.includes(platform))throw Error('OfficeSDK '+version+' has no '+host+' release for '+platform);
|
|
24
|
+
if(values['dry-run'])return console.log(JSON.stringify({host,version,asset:route.asset,sha256:route.sha256,platform}));
|
|
25
|
+
if(route.kind==='vsix'){
|
|
26
|
+
const {installExtension}=await import('./ide.mjs');
|
|
27
|
+
return installExtension({host,route,version,values});
|
|
28
|
+
}
|
|
29
|
+
const {installFileHost}=await import('./file-host.mjs');
|
|
30
|
+
return installFileHost({host,route,version,assetDir:values['asset-dir'],project:values.project});
|
|
31
|
+
}
|
|
32
|
+
if (route.kind !== 'dsh-npm') throw Error('Unknown native installer: ' + route.kind);
|
|
33
|
+
const spec = route.package + '@' + version;
|
|
34
|
+
let installTarget=spec;
|
|
35
|
+
if(values['asset-dir']&&!values['dry-run']) {
|
|
36
|
+
const {assetBytes}=await import('./file-host.mjs');
|
|
37
|
+
const fs=await import('node:fs/promises');
|
|
38
|
+
const {homedir}=await import('node:os');
|
|
39
|
+
const path=await import('node:path');
|
|
40
|
+
const bytes=await assetBytes(route,version,values['asset-dir']);
|
|
41
|
+
const folder=path.join(homedir(),'.officesdk','installer',route.sha256);
|
|
42
|
+
await fs.mkdir(folder,{recursive:true,mode:0o700});
|
|
43
|
+
installTarget=path.join(folder,route.asset);
|
|
44
|
+
const scratch=await fs.mkdtemp(path.join(folder,'.staging-'));
|
|
45
|
+
try {
|
|
46
|
+
const staged=path.join(scratch,'release.tgz');
|
|
47
|
+
await fs.writeFile(staged,bytes);
|
|
48
|
+
await fs.rename(staged,installTarget);
|
|
49
|
+
} finally { await fs.rm(scratch,{recursive:true,force:true}); }
|
|
50
|
+
}
|
|
51
|
+
const args = ['plugin', '--profile', 'desktop', 'add', installTarget];
|
|
52
|
+
if (values['dry-run']) return console.log(JSON.stringify({host, version, command: 'dsh', args}));
|
|
53
|
+
let command = 'dsh';
|
|
54
|
+
if (process.platform === 'darwin') {
|
|
55
|
+
const bundled = '/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh';
|
|
56
|
+
try { accessSync(bundled, constants.X_OK); command = bundled; } catch { /* use PATH */ }
|
|
57
|
+
}
|
|
58
|
+
const result = spawnSync(command, args, { stdio:'inherit', shell:false });
|
|
59
|
+
if (result.error) throw Error('Could not run the DeepSeek Harness CLI: ' + result.error.message);
|
|
60
|
+
if (result.status !== 0) throw Error('DeepSeek Harness did not finish installation (exit ' + (result.status ?? result.signal) + ').');
|
|
61
|
+
}
|
|
62
|
+
try { await run(); } catch (error) { console.error(error.message); process.exitCode = 1; }
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import {execFile} from 'node:child_process';
|
|
6
|
+
import {promisify} from 'node:util';
|
|
7
|
+
|
|
8
|
+
const run=promisify(execFile);
|
|
9
|
+
const market='officesdk';
|
|
10
|
+
const plugin='officesdk@'+market;
|
|
11
|
+
const relativePlugin='plugins/officesdk';
|
|
12
|
+
async function closePreviousService(port) {
|
|
13
|
+
const data=process.env.OFFICESDK_WORKBUDDY_DATA||path.join(os.homedir(),'.officesdk/workbuddy/state');
|
|
14
|
+
const key=await fs.readFile(path.join(data,'connector.key'),'utf8').catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
15
|
+
if(!key)return;
|
|
16
|
+
const request=tool=>fetch('http://127.0.0.1:'+port+'/rpc',{method:'POST',redirect:'error',
|
|
17
|
+
headers:{'Content-Type':'application/json',Authorization:'Bearer '+key},body:JSON.stringify({tool,args:{}}),signal:AbortSignal.timeout(3000)});
|
|
18
|
+
const status=await request('office_status').catch(error=>{if(error.cause?.code==='ECONNREFUSED')return null;throw error;});
|
|
19
|
+
if(!status)return;
|
|
20
|
+
if(!status.ok||!(await status.json()).version)throw Error('Could not identify the running WorkBuddy editor service');
|
|
21
|
+
const response=await request('_shutdown');
|
|
22
|
+
const result=await response.json();
|
|
23
|
+
if(!response.ok||!result.stopping)throw Error(result.error||'Save and close the open WorkBuddy editor before updating');
|
|
24
|
+
for(let i=0;i<30;i++){
|
|
25
|
+
await new Promise(resolve=>setTimeout(resolve,100));
|
|
26
|
+
try {const running=await request('office_status');await running.body?.cancel();}
|
|
27
|
+
catch(error){if(error.cause?.code==='ECONNREFUSED')return;throw error;}
|
|
28
|
+
}
|
|
29
|
+
throw Error('WorkBuddy has not finished closing the previous editor service');
|
|
30
|
+
}
|
|
31
|
+
export async function prepareMarket(staging,target,settings,version) {
|
|
32
|
+
// Let the host launch its own transport. The service is local to the user's
|
|
33
|
+
// profile and survives the end of a chat while an Office tab is open.
|
|
34
|
+
if(!settings.port) {
|
|
35
|
+
const socket=net.createServer();
|
|
36
|
+
await new Promise((resolve,reject)=>socket.once('error',reject).listen(0,'127.0.0.1',resolve));
|
|
37
|
+
settings.port=socket.address().port;
|
|
38
|
+
await new Promise(resolve=>socket.close(resolve));
|
|
39
|
+
}
|
|
40
|
+
if(!Number.isInteger(settings.port)||settings.port<1024||settings.port>65535)throw Error('Invalid WorkBuddy editor port');
|
|
41
|
+
const installed=path.join(target,relativePlugin,'package.json');
|
|
42
|
+
const prior=await fs.readFile(installed,'utf8').then(JSON.parse).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
43
|
+
if(prior&&prior.version!==version)await closePreviousService(settings.port);
|
|
44
|
+
const entry=JSON.parse(await fs.readFile(path.join(staging,'.workbuddy-plugin/plugin.json')));
|
|
45
|
+
entry.mcpServers.office={command:process.execPath,args:[path.join(target,relativePlugin,'src/mcp.mjs')],defer_loading:false};
|
|
46
|
+
await fs.writeFile(path.join(staging,'.workbuddy-plugin/plugin.json'),JSON.stringify(entry,null,2)+'\n');
|
|
47
|
+
const marketDir=staging+'-market';
|
|
48
|
+
await fs.mkdir(path.join(marketDir,'plugins'),{recursive:true});
|
|
49
|
+
await fs.mkdir(path.join(marketDir,'.workbuddy-plugin'));
|
|
50
|
+
await fs.writeFile(path.join(marketDir,'.workbuddy-plugin/marketplace.json'),JSON.stringify({name:market,owner:{name:'OfficeSDK'},plugins:[{name:entry.name,source:'./'+relativePlugin,description:entry.description,version}]},null,2)+'\n');
|
|
51
|
+
await fs.rename(staging,path.join(marketDir,relativePlugin));
|
|
52
|
+
await fs.rename(marketDir,staging);
|
|
53
|
+
}
|
|
54
|
+
export async function marketManager(target) {
|
|
55
|
+
const home=os.homedir();
|
|
56
|
+
const profile=process.env.WORKBUDDY_CONFIG_DIR || path.join(home,'.workbuddy');
|
|
57
|
+
const cli='Contents/Resources/app.asar.unpacked/cli/dist/codebuddy-lite-wb.mjs';
|
|
58
|
+
const candidates=[path.join(home,'Applications/WorkBuddy.app',cli),path.join('/Applications/WorkBuddy.app',cli)];
|
|
59
|
+
let entry;
|
|
60
|
+
for(const option of candidates)if(await fs.access(option).then(()=>true,()=>false)){entry=option;break;}
|
|
61
|
+
if(!entry)throw Error('WorkBuddy is required to register the native plugin');
|
|
62
|
+
async function manage(...args) {
|
|
63
|
+
const {stdout}=await run(process.execPath,[entry,'plugin',...args],{cwd:path.dirname(target),timeout:65000,maxBuffer:4*1024*1024,
|
|
64
|
+
env:{...process.env,CODEBUDDY_CONFIG_DIR:profile,WORKBUDDY_CONFIG_DIR:profile,NO_COLOR:'1'}});
|
|
65
|
+
return stdout;
|
|
66
|
+
}
|
|
67
|
+
async function list(){return JSON.parse(await manage('list','--json'));}
|
|
68
|
+
const markets=JSON.parse(await fs.readFile(path.join(profile,'plugins/known_marketplaces.json'),'utf8').catch(e=>{if(e.code==='ENOENT')return '{}';throw e;}));
|
|
69
|
+
const record=markets[market];
|
|
70
|
+
if(record && record.source?.path!==target && record.installLocation!==target)throw Error('WorkBuddy already has a different marketplace named '+market);
|
|
71
|
+
const before=(await list()).filter(r=>r.scope==='user');
|
|
72
|
+
const old=before.find(r=>r.id===plugin);
|
|
73
|
+
const legacy=before.find(r=>r.id==='officesdk@officesdk-workbuddy-local'&&r.enabled);
|
|
74
|
+
if(before.some(r=>r.enabled&&r.id.startsWith('officesdk@')&&![plugin,'officesdk@officesdk-workbuddy-local'].includes(r.id)))throw Error('Another installed marketplace manages OfficeSDK in this WorkBuddy profile');
|
|
75
|
+
let added=false,installed=false,disabled=false,enabled=false;
|
|
76
|
+
return {
|
|
77
|
+
async activate(version) {
|
|
78
|
+
await manage('validate',path.join(target,relativePlugin));
|
|
79
|
+
// A directory can still be registered on disk after the host stopped loading it.
|
|
80
|
+
const marketReady=async()=>JSON.parse(await manage('marketplace','list')).some(item=>item.name===market);
|
|
81
|
+
if(!record || !await marketReady()){
|
|
82
|
+
await manage('marketplace','add',target);
|
|
83
|
+
added=!record;
|
|
84
|
+
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.');
|
|
85
|
+
}
|
|
86
|
+
if(!old){await manage('install',plugin,'--scope','user');installed=true;}
|
|
87
|
+
else if(old.version!==version){await manage('marketplace','update',market);await manage('update',plugin,'--scope','user');}
|
|
88
|
+
let rows=await list();
|
|
89
|
+
if(rows.some(r=>r.id===plugin&&!r.enabled)){await manage('enable',plugin,'--scope','user');enabled=true;rows=await list();}
|
|
90
|
+
const isActive=items=>items.some(r=>r.id===plugin&&r.scope==='user'&&r.enabled&&r.version===version);
|
|
91
|
+
for(const delay of [250,750,1500]){
|
|
92
|
+
if(isActive(rows))break;
|
|
93
|
+
await new Promise(resolve=>setTimeout(resolve,delay));
|
|
94
|
+
rows=await list();
|
|
95
|
+
}
|
|
96
|
+
if(!isActive(rows))throw Error('WorkBuddy loaded the OfficeSDK local source but did not confirm version '+version+' as enabled for this user.');
|
|
97
|
+
if(legacy){await manage('disable',legacy.id,'--scope','user');disabled=true;}
|
|
98
|
+
},
|
|
99
|
+
async rollback() {
|
|
100
|
+
if(disabled)await manage('enable',legacy.id,'--scope','user');
|
|
101
|
+
if(installed)await manage('uninstall',plugin,'--scope','user');
|
|
102
|
+
else if(old) {
|
|
103
|
+
if(enabled&&!old.enabled)await manage('disable',plugin,'--scope','user');
|
|
104
|
+
if(old.version!==(await list()).find(r=>r.id===plugin)?.version){await manage('marketplace','update',market);await manage('update',plugin,'--scope','user');}
|
|
105
|
+
}
|
|
106
|
+
if(added)await manage('marketplace','remove',market);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|