### Install the SDK Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Install the package via npm. ```bash npm install @office-agents/sdk ``` -------------------------------- ### Start Word Add-in Development Server Source: https://github.com/hewliyang/office-agents/blob/main/packages/word/README.md Use this command to start the development server for the Word add-in. It typically runs on https://localhost:3002. ```bash pnpm dev-server:word ``` -------------------------------- ### Install Dependencies Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Installs all project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Start PowerPoint Dev Server Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Starts the development server for PowerPoint add-ins, usually at https://localhost:3001. ```bash pnpm dev-server:ppt ``` -------------------------------- ### Start Development Server for Excel Add-in Source: https://github.com/hewliyang/office-agents/blob/main/packages/excel/README.md Use this command to start the development server for the Excel add-in. It typically runs on https://localhost:3000. ```bash pnpm dev-server:excel ``` -------------------------------- ### Start development server and launch PowerPoint Source: https://github.com/hewliyang/office-agents/blob/main/packages/powerpoint/README.md Commands to initiate the development environment and sideload the add-in into PowerPoint. ```bash pnpm dev-server:ppt # Start dev server (https://localhost:3001) pnpm start:ppt # Launch PowerPoint with add-in sideloaded ``` -------------------------------- ### Start Office RPC Bridge Server Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Starts the local Office RPC bridge server, typically accessible at https://localhost:4017. ```bash pnpm bridge:serve ``` -------------------------------- ### Manage Skills Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Functions for adding, getting, removing, and syncing skills. Skills are installable packages with a SKILL.md file and optional supporting files, mounted at /home/skills// in the VFS. Also builds prompt sections for skills. ```typescript import { addSkill, getInstalledSkills, removeSkill, syncSkillsToVfs, buildSkillsPromptSection, AgentContext, type StorageNamespace, } from "@office-agents/sdk"; const ns: StorageNamespace = { /* ... */ }; const ctx = new AgentContext({ namespace: ns }); // Install a skill from files await addSkill(ns, ctx, [ { path: "SKILL.md", data: "---\nname: data-analysis\ndescription: Data analysis best practices\n---\n # Data Analysis When analyzing data, always start by summarizing the dataset...", }, ]); // List installed skills const skills = await getInstalledSkills(ns); // Build the skills section for the system prompt const promptSection = buildSkillsPromptSection(skills); // Sync all skill files into the VFS (preserves uploads) await syncSkillsToVfs(ns, ctx); // Uninstall await removeSkill(ns, ctx, "data-analysis"); ``` -------------------------------- ### Skills Management Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Explains how to add, install, list, sync, and remove skills, which are installable packages containing markdown files and supporting assets, mounted in the VFS. ```APIDOC ## Skills ### Description Manage installable skills, including adding, listing, syncing, and removing them. Skills are mounted at `/home/skills//` in the VFS. ### Usage ```typescript import { addSkill, getInstalledSkills, removeSkill, syncSkillsToVfs, buildSkillsPromptSection, AgentContext, type StorageNamespace, } from "@office-agents/sdk"; const ns: StorageNamespace = { /* ... */ }; const ctx = new AgentContext({ namespace: ns }); // Install a skill from files await addSkill(ns, ctx, [ { path: "SKILL.md", data: "---\nname: data-analysis\ndescription: Data analysis best practices\n---\n\n# Data Analysis\n\nWhen analyzing data, always start by summarizing the dataset...", }, ]); // List installed skills const skills = await getInstalledSkills(ns); // Build the skills section for the system prompt const promptSection = buildSkillsPromptSection(skills); // Sync all skill files into the VFS (preserves uploads) await syncSkillsToVfs(ns, ctx); // Uninstall await removeSkill(ns, ctx, "data-analysis"); ``` ``` -------------------------------- ### Development and Build Commands Source: https://github.com/hewliyang/office-agents/blob/main/README.md Use these commands to manage dependencies, start development servers for specific Office applications, and perform code quality checks. ```bash pnpm install # Install all dependencies pnpm dev-server:excel # Start Excel dev server (https://localhost:3000) pnpm dev-server:ppt # Start PowerPoint dev server (https://localhost:3001) pnpm dev-server:word # Start Word dev server (https://localhost:3002) pnpm start:excel # Launch Excel with add-in sideloaded pnpm start:ppt # Launch PowerPoint with add-in sideloaded pnpm start:word # Launch Word with add-in sideloaded pnpm build # Build all packages pnpm typecheck # TypeScript type checking (all packages) pnpm lint # Run Biome linter pnpm format # Format code with Biome pnpm check # Typecheck + lint pnpm validate # Validate Office manifests ``` -------------------------------- ### Initialize the Agent Runtime Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Configure the AgentContext and initialize the AgentRuntime to start the agent lifecycle. ```typescript import { AgentContext, AgentRuntime } from "@office-agents/sdk"; // Option A: let runtime.init() apply adapter.staticFiles / adapter.customCommands const ctx = new AgentContext({ namespace: adapter.storageNamespace, }); // Option B: pass everything upfront (app entrypoints typically do this) const ctx = new AgentContext({ namespace: adapter.storageNamespace, staticFiles: adapter.staticFiles, customCommands: adapter.customCommands, }); const runtime = new AgentRuntime(adapter, ctx); // Subscribe to state changes runtime.subscribe((state) => { console.log("Messages:", state.messages.length); console.log("Streaming:", state.isStreaming); }); // Initialize (applies adapter config, loads saved provider config, restores session + VFS) await runtime.init(); // Send a message await runtime.sendMessage("Hello, who are you?"); ``` -------------------------------- ### Start and Stop the Bridge Source: https://github.com/hewliyang/office-agents/blob/main/packages/bridge/README.md Commands to manage the lifecycle of the bridge server. ```bash pnpm bridge:serve pnpm bridge:stop ``` ```bash pnpm bridge -- list pnpm bridge -- exec word --code "const body = context.document.body; body.load('text'); await context.sync(); return body.text;" ``` ```bash pnpm --filter @office-agents/bridge start pnpm --filter @office-agents/bridge run cli -- list ``` -------------------------------- ### Get Office Bridge Metadata Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Retrieves metadata for a specific Office bridge session, for example, for Word. ```bash pnpm exec office-bridge metadata word ``` -------------------------------- ### Inspect Office Bridge Session Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Inspects a specific Office bridge session, for example, for Word. ```bash pnpm exec office-bridge inspect word ``` -------------------------------- ### Manage Sessions and VFS Persistence Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Functions for creating, listing, getting, saving, and deleting sessions. Also handles persisting VFS files per session using a StorageNamespace and document ID. ```typescript import { createSession, listSessions, getSession, saveSession, deleteSession, loadVfsFiles, saveVfsFiles, type StorageNamespace, } from "@office-agents/sdk"; const ns: StorageNamespace = { dbName: "MyAppDB", dbVersion: 1, localStoragePrefix: "my-app", documentSettingsPrefix: "my-app", }; const docId = "my-document-id"; // Create and manage sessions const session = await createSession(ns, docId, "My Chat"); const sessions = await listSessions(ns, docId); await deleteSession(ns, session.id); // Persist VFS files per session const snapshot = await ctx.snapshotVfs(); await saveVfsFiles(ns, session.id, snapshot); const restored = await loadVfsFiles(ns, session.id); await ctx.restoreVfs(restored); ``` -------------------------------- ### OOXML Table Structure Example Source: https://github.com/hewliyang/office-agents/blob/main/packages/word/TODO.md Representation of the XML structure for a Word table, illustrating the hierarchy of properties and elements that are currently lost during paragraph-only extraction. ```xml ... ... ... ... ... ``` -------------------------------- ### Get Document Text via Office Bridge Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Retrieves the text content of the document from a live Office session using the bridge. ```bash pnpm exec office-bridge tool word get_document_text ``` -------------------------------- ### Write to Excel Sheet using Excel API Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Use the Excel.run method to execute asynchronous operations within an Excel workbook. This example writes a value to cell A1 of the active worksheet. ```typescript await Excel.run(async (context) => { const sheet = context.workbook.worksheets.getActiveWorksheet(); const range = sheet.getRange("A1"); range.values = [["value"]]; await context.sync(); }); ``` -------------------------------- ### Build All Packages Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Compiles and builds all packages within the project. ```bash pnpm build ``` -------------------------------- ### Virtual Filesystem and Bash Integration Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Demonstrates how to use the AgentContext to interact with a virtual filesystem (VFS) and execute bash commands. This includes writing, reading, listing files, and managing VFS state through snapshots and restoration. ```APIDOC ## Virtual Filesystem & Bash ### Description Interact with a virtual filesystem (VFS) and execute bash commands using the `AgentContext`. ### Usage ```typescript import { AgentContext } from "@office-agents/sdk"; const ctx = new AgentContext({ staticFiles: { "/home/user/docs/guide.txt": "Getting started...", }, }); // Write files to VFS await ctx.writeFile("/home/user/uploads/data.csv", "name,age\nAlice,30"); // Relative paths resolve to /home/user/uploads/ await ctx.writeFile("notes.txt", "some notes"); // Read files const content = await ctx.readFile("/home/user/uploads/data.csv"); // List uploads const uploads = await ctx.listUploads(); // ["data.csv", "notes.txt"] // Execute bash commands const bash = ctx.bash; const result = await bash.exec("ls /home/user/uploads/"); // Snapshot and restore VFS state (used for session persistence) const snapshot = await ctx.snapshotVfs(); // excludes /home/skills/ await ctx.restoreVfs(snapshot); // Update skill files in-place (preserves user uploads) await ctx.setSkillFiles({ "/home/skills/analysis/SKILL.md": new TextEncoder().encode("# Analysis skill"), }); // Update static files in-place (preserves user uploads) await ctx.setStaticFiles({ "/home/user/docs/new-guide.txt": "Updated guide", }); ``` ``` -------------------------------- ### Provider Configuration Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Explains how to configure providers and save/load settings using a `StorageNamespace` to scope localStorage keys. ```APIDOC ## Provider Configuration ### Description Configure providers and manage settings using a `StorageNamespace` for localStorage scoping. ### Usage ```typescript import { loadSavedConfig, saveConfig, type StorageNamespace } from "@office-agents/sdk"; const ns: StorageNamespace = { dbName: "MyAppDB", dbVersion: 1, localStoragePrefix: "my-app", documentSettingsPrefix: "my-app", }; // Load saved config from localStorage const config = loadSavedConfig(ns); // Save a new config saveConfig(ns, { provider: "openai", apiKey: "sk-...", model: "gpt-4o", useProxy: false, proxyUrl: "", thinking: "none", followMode: true, expandToolCalls: false, }); ``` ``` -------------------------------- ### Launch PowerPoint with Add-in Sideloaded Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Launches the PowerPoint application with the add-in pre-loaded for testing. ```bash pnpm start:ppt ``` -------------------------------- ### Create a RuntimeAdapter Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Implement the RuntimeAdapter interface to connect your application to the agent runtime, including tool registration and storage configuration. ```typescript import type { RuntimeAdapter } from "@office-agents/sdk"; const adapter: RuntimeAdapter = { tools: [greetTool], buildSystemPrompt: (skills, commandSnippets) => { let prompt = "You are a helpful assistant. Use tools when appropriate."; if (commandSnippets.length > 0) { prompt += "\n\nAvailable commands:\n" + commandSnippets.join("\n"); } return prompt; }, getDocumentId: async () => { return "my-document-id"; // unique ID for session scoping }, // Optional: provide static files to mount in the VFS (e.g., API docs) staticFiles: { "/home/user/docs/api-reference.d.ts": "declare const MyApi: any;", }, // Optional: register custom bash commands customCommands: (ns) => ({ commands: [/* CustomCommand instances */], promptSnippets: ["Use `my-cmd ` to do something"], }), // Optional: inject context into each message getDocumentMetadata: async () => ({ metadata: { title: "My Document", sheets: ["Sheet1"] }, }), // Optional: react to tool results (e.g., navigate to a cell) onToolResult: (toolCallId, result, isError) => { console.log("Tool result:", result); }, // Optional: scope storage to your app storageNamespace: { dbName: "MyAppDB", dbVersion: 1, localStoragePrefix: "my-app", documentSettingsPrefix: "my-app", }, }; ``` -------------------------------- ### Launch Excel with Sideloaded Add-in Source: https://github.com/hewliyang/office-agents/blob/main/packages/excel/README.md Execute this command to launch Microsoft Excel with the add-in already sideloaded for testing during development. ```bash pnpm start:excel ``` -------------------------------- ### Run Repository Checks Source: https://github.com/hewliyang/office-agents/blob/main/packages/core/README.md Execute the repository-level checks for type checking, linting, and building the project. ```bash pnpm typecheck pnpm lint pnpm build ``` -------------------------------- ### Screenshot Workflow Source: https://github.com/hewliyang/office-agents/blob/main/packages/bridge/README.md Commands for capturing screenshots of Office applications and saving them to the local filesystem. ```bash office-bridge screenshot word --pages 1 --out page1.png office-bridge screenshot excel --sheet-id 1 --range A1:F20 --out range.png office-bridge screenshot powerpoint --slide-index 0 --out slide1.png ``` ```bash office-bridge tool excel screenshot_range --input '{"sheetId":1,"range":"A1:F20"}' --out range.png ``` -------------------------------- ### Launch Word with Sideloaded Add-in Source: https://github.com/hewliyang/office-agents/blob/main/packages/word/README.md Execute this command to launch Microsoft Word with the add-in already sideloaded for testing during development. ```bash pnpm start:word ``` -------------------------------- ### Built-in Tools Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Shows how to create tools that are bound to an AgentContext, such as bash and read tools, which can be used within an adapter. ```APIDOC ## Built-in Tools ### Description Create tools bound to an `AgentContext` for VFS operations. ### Usage ```typescript import { createBashTool, createReadTool } from "@office-agents/sdk"; const ctx = new AgentContext(); // Tools that operate on the context's VFS const bashTool = createBashTool(ctx); const readTool = createReadTool(ctx); // Or use tools as a function of context in your adapter: const adapter: RuntimeAdapter = { tools: (ctx) => [createBashTool(ctx), createReadTool(ctx), greetTool], // ... }; ``` ``` -------------------------------- ### List Live Office Bridge Sessions Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Lists all currently active Office bridge sessions. ```bash pnpm exec office-bridge list ``` -------------------------------- ### Run Biome Linter Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Executes the Biome linter to check code quality and style. ```bash pnpm lint ``` -------------------------------- ### Office Bridge CLI Commands Source: https://github.com/hewliyang/office-agents/blob/main/README.md Commands for managing the bridge server and inspecting the live add-in runtime, including tool execution and virtual filesystem management. ```bash pnpm bridge:serve # Start the bridge server (https://localhost:4017) pnpm bridge:stop # Stop the bridge server pnpm exec office-bridge list # List connected sessions pnpm exec office-bridge inspect word # Inspect a session's tools & metadata pnpm exec office-bridge tool word get_document_text # Run a tool against the live add-in pnpm exec office-bridge screenshot word --out p.png # Screenshot a document page pnpm exec office-bridge vfs ls word /home/user # Browse the VFS ``` -------------------------------- ### Create Bash and Read Tools Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Factory functions to create tools that operate on the AgentContext's VFS. These tools can be used directly or within a RuntimeAdapter. ```typescript import { createBashTool, createReadTool } from "@office-agents/sdk"; const ctx = new AgentContext(); // Tools that operate on the context's VFS const bashTool = createBashTool(ctx); const readTool = createReadTool(ctx); // Or use tools as a function of context in your adapter: const adapter: RuntimeAdapter = { tools: (ctx) => [createBashTool(ctx), createReadTool(ctx), greetTool], // ... }; ``` -------------------------------- ### Sessions and VFS Persistence Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Details how to manage sessions and persist VFS files using a namespace and document ID for session management and VFS state saving/loading. ```APIDOC ## Sessions ### Description Manage agent sessions and persist VFS files, scoped by namespace and document ID. ### Usage ```typescript import { createSession, listSessions, getSession, saveSession, deleteSession, loadVfsFiles, saveVfsFiles, type StorageNamespace, } from "@office-agents/sdk"; const ns: StorageNamespace = { dbName: "MyAppDB", dbVersion: 1, localStoragePrefix: "my-app", documentSettingsPrefix: "my-app", }; const docId = "my-document-id"; // Create and manage sessions const session = await createSession(ns, docId, "My Chat"); const sessions = await listSessions(ns, docId); await deleteSession(ns, session.id); // Persist VFS files per session const snapshot = await ctx.snapshotVfs(); await saveVfsFiles(ns, session.id, snapshot); const restored = await loadVfsFiles(ns, session.id); await ctx.restoreVfs(restored); ``` ``` -------------------------------- ### Format Code with Biome Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Applies code formatting using Biome to ensure consistent style. ```bash pnpm format ``` -------------------------------- ### Push File to Virtual File System Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Uploads a local file to the Office application's virtual file system. ```bash pnpm exec office-bridge vfs push word ./local.txt /home/user/uploads/local.txt ``` -------------------------------- ### Custom Bash Commands Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Details how to register custom bash commands that become available in the shell and generate prompt snippets, including built-in commands like web search. ```APIDOC ## Custom bash commands ### Description Register custom commands that appear in the bash shell and generate prompt snippets. ### Usage ```typescript import { getSharedCustomCommands, type CustomCommandsResult, type StorageNamespace } from "@office-agents/sdk"; function getCustomCommands(ns: StorageNamespace): CustomCommandsResult { // getSharedCustomCommands provides built-in commands like // pdf-to-text, docx-to-text, xlsx-to-csv, web-search, web-fetch return getSharedCustomCommands({ ns }); } const ctx = new AgentContext({ customCommands: getCustomCommands, }); // Command snippets are derived from registered commands const snippets = ctx.commandSnippets; // string[] ``` ``` -------------------------------- ### List Files in Virtual File System Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Lists files and directories within a specified path in the Office application's virtual file system. ```bash pnpm exec office-bridge vfs ls word /home/user ``` -------------------------------- ### CLI Operations Source: https://github.com/hewliyang/office-agents/blob/main/packages/bridge/README.md Common CLI commands for inspecting, executing code, and managing Office add-in sessions. ```bash office-bridge list office-bridge inspect word office-bridge metadata excel office-bridge events word --limit 20 office-bridge exec word --code "return { href: window.location.href, title: document.title }" office-bridge exec word --sandbox --code "const body = context.document.body; body.load('text'); await context.sync(); return body.text;" office-bridge tool excel screenshot_range --input '{"sheetId":1,"range":"A1:F20"}' --out range.png office-bridge screenshot word --pages 1 --out page1.png office-bridge screenshot excel --sheet-id 1 --range A1:F20 --out range.png office-bridge screenshot powerpoint --slide-index 0 --out slide1.png office-bridge vfs ls word /home/user office-bridge vfs pull word /home/user/uploads/report.docx ./report.docx office-bridge vfs push word ./local.txt /home/user/uploads/local.txt ``` -------------------------------- ### Interact with Virtual Filesystem and Bash Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Use AgentContext to manage files in a virtual filesystem (VFS) and execute bash commands. Supports writing, reading, listing files, and snapshotting/restoring VFS state. Also allows updating skill and static files. ```typescript import { AgentContext } from "@office-agents/sdk"; const ctx = new AgentContext({ staticFiles: { "/home/user/docs/guide.txt": "Getting started...", }, }); // Write files to VFS await ctx.writeFile("/home/user/uploads/data.csv", "name,age\nAlice,30"); // Relative paths resolve to /home/user/uploads/ await ctx.writeFile("notes.txt", "some notes"); // Read files const content = await ctx.readFile("/home/user/uploads/data.csv"); // List uploads const uploads = await ctx.listUploads(); // ["data.csv", "notes.txt"] // Execute bash commands const bash = ctx.bash; const result = await bash.exec("ls /home/user/uploads/"); // Snapshot and restore VFS state (used for session persistence) const snapshot = await ctx.snapshotVfs(); // excludes /home/skills/ await ctx.restoreVfs(snapshot); // Update skill files in-place (preserves user uploads) await ctx.setSkillFiles({ "/home/skills/analysis/SKILL.md": new TextEncoder().encode("# Analysis skill"), }); // Update static files in-place (preserves user uploads) await ctx.setStaticFiles({ "/home/user/docs/new-guide.txt": "Updated guide", }); ``` -------------------------------- ### Take Screenshot via Office Bridge Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Captures a screenshot of the first page of the Office document and saves it to a local file. ```bash pnpm exec office-bridge screenshot word --pages 1 --out page1.png ``` -------------------------------- ### Pull File from Virtual File System Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Downloads a file from the Office application's virtual file system to the local machine. ```bash pnpm exec office-bridge vfs pull word /home/user/uploads/report.docx ./report.docx ``` -------------------------------- ### Execute code in Office taskpane Source: https://github.com/hewliyang/office-agents/blob/main/README.md Runs arbitrary JavaScript in the Office taskpane context to access globals like window and document. ```bash pnpm exec office-bridge exec word --code "return { href: window.location.href, title: document.title }" ``` -------------------------------- ### Configure Provider Settings Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Load and save configuration settings using a StorageNamespace to scope localStorage keys. Supports specifying provider, API key, model, proxy settings, and thinking/follow modes. ```typescript import { loadSavedConfig, saveConfig, type StorageNamespace } from "@office-agents/sdk"; const ns: StorageNamespace = { dbName: "MyAppDB", dbVersion: 1, localStoragePrefix: "my-app", documentSettingsPrefix: "my-app", }; // Load saved config from localStorage const config = loadSavedConfig(ns); // Save a new config saveConfig(ns, { provider: "openai", apiKey: "sk-...", model: "gpt-4o", useProxy: false, proxyUrl: "", thinking: "none", followMode: true, expandToolCalls: false, }); ``` -------------------------------- ### VFS File Operations Source: https://github.com/hewliyang/office-agents/blob/main/packages/bridge/README.md Commands to manage files between the add-in virtual file system and the local machine. ```bash office-bridge vfs ls word /home/user office-bridge vfs pull word /home/user/uploads/report.docx ./report.docx office-bridge vfs push word ./notes.txt /home/user/uploads/notes.txt office-bridge vfs rm word /home/user/uploads/notes.txt ``` -------------------------------- ### OAuth API Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Utilities for handling OAuth2 authentication flows including PKCE. ```APIDOC ## OAuth ### Description Handles authentication flows for external providers. ### Methods - **generatePKCE()**: Generates code verifier and challenge. - **buildAuthorizationUrl(provider, ...)**: Constructs the OAuth authorization URL. - **exchangeOAuthCode(...)**: Exchanges authorization code for tokens. - **refreshOAuthToken(...)**: Refreshes an existing OAuth token. ``` -------------------------------- ### Convert Compaction Summary to LLM Format (SDK) Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Handles the conversion of 'compactionSummary' messages into a format suitable for LLM context. It wraps the summary text within `` tags, transforming it into a 'UserMessage'. This extends the existing 'convertToLlm' functionality. ```typescript convertToLlm(message: AgentMessage): UserMessage { if (message.role === "compactionSummary") { return { role: "user", content: `${message.summary}` }; } // ... existing logic ... } ``` -------------------------------- ### Typecheck and Lint Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Runs both TypeScript type checking and Biome linting. ```bash pnpm check ``` -------------------------------- ### Compaction Flow Implementation (SDK) Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Orchestrates the compaction process upon detecting overflow. It retrieves current LLM context messages, determines a cut point, sends older messages for summarization using 'completeSimple()', inserts a 'compactionSummary' message, and updates the agent's state. ```typescript // ... get current context messages ... const cutPoint = findCutPoint(currentContext); const oldMessages = currentContext.slice(0, cutPoint); const summary = await completeSimple("Summarize:", oldMessages); const compactionSummaryMessage = { role: "compactionSummary", summary, timestamp: Date.now() }; const updatedMessages = [...currentContext.slice(cutPoint), compactionSummaryMessage]; agent.replaceMessages(updatedMessages); agent.saveSession(); ``` -------------------------------- ### AgentContext API Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Manages the virtual file system (VFS), bash shell, and custom command environment for an agent. ```APIDOC ## AgentContext ### Description Provides an isolated environment for agents, including file system operations and command execution. ### Methods - **new AgentContext(opts?)**: Initializes context with optional namespace, staticFiles, skillFiles, and customCommands. - **writeFile(path, content)**: Writes content to a file in /home/user/uploads/. - **readFile(path)**: Reads a file from the VFS. - **listUploads()**: Lists files in the user uploads directory. - **snapshotVfs()**: Snapshots current VFS state. - **restoreVfs(files)**: Restores VFS from a snapshot. ``` -------------------------------- ### Storage API Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Provides persistence mechanisms for sessions, VFS files, and document IDs. ```APIDOC ## Storage ### Description Utility functions for persisting agent data across sessions. ### Methods - **createSession(ns, workbookId, name?)**: Creates a new session. - **saveVfsFiles(ns, sessionId, files)**: Persists VFS files for a specific session. - **listSessions(ns, workbookId)**: Retrieves all sessions for a document. - **getOrCreateDocumentId(ns)**: Retrieves or generates a persistent document ID. ``` -------------------------------- ### Validate Office Manifests Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Validates the Office application manifests for correctness. ```bash pnpm validate ``` -------------------------------- ### AgentRuntime API Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Handles the lifecycle of an agent session, including message streaming and skill management. ```APIDOC ## AgentRuntime ### Description Manages the execution runtime, session state, and communication flow. ### Methods - **new AgentRuntime(adapter, context)**: Creates a runtime instance. - **init()**: Initializes adapter and restores session/VFS. - **sendMessage(text, images?)**: Sends a message and streams the response. - **newSession() / switchSession(id)**: Manages agent sessions. - **installSkill(files)**: Installs a new skill into the runtime. ``` -------------------------------- ### Proposed Container-Aware Tool Signature Source: https://github.com/hewliyang/office-agents/blob/main/packages/word/TODO.md A proposed extension to the existing paragraph extraction tool to include structural container information. ```python get_paragraph_ooxml(paragraphIndex, endParagraphIndex?, includeContainer?) ``` -------------------------------- ### Release Patch Version (SDK) Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Releases a patch version of the SDK package, updating version number, changelog, and pushing changes. ```bash pnpm release:sdk patch ``` -------------------------------- ### Release Patch Version (Word) Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Releases a patch version of the Word add-in, updating version number, changelog, and pushing changes. ```bash pnpm release:word patch ``` -------------------------------- ### Execute Code in Sandbox via Office Bridge Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Executes JavaScript code within a sandboxed environment in the Office taskpane/runtime, ensuring safer execution. ```bash pnpm exec office-bridge exec word --sandbox --code "const body = context.document.body; body.load('text'); await context.sync(); return body.text;" ``` -------------------------------- ### Context Building and Filtering (SDK) Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Implements context building logic using the 'transformContext' hook. It identifies the last 'compactionSummary' message and slices the message array to exclude messages before this point from the LLM context, while retaining them for persistence and display. ```typescript transformContext(messages: AgentMessage[]): AgentMessage[] { const lastCompactionIndex = messages.findLastIndex(msg => msg.role === "compactionSummary"); if (lastCompactionIndex !== -1) { return messages.slice(lastCompactionIndex + 1); } return messages; } ``` -------------------------------- ### Detect Legacy Browsers for Office Add-in Source: https://github.com/hewliyang/office-agents/blob/main/packages/excel/src/taskpane.html Checks the user agent string for Trident or Edge identifiers to determine if the browser is unsupported. If detected, it hides the main container and displays a warning message. ```javascript if ( navigator.userAgent.indexOf("Trident") !== -1 || navigator.userAgent.indexOf("Edge") !== -1 ) { var tridentMessage = document.getElementById("tridentmessage"); var normalContainer = document.getElementById("container"); tridentMessage.style.display = "block"; normalContainer.style.display = "none"; } ``` -------------------------------- ### Define AppAdapter Interface Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md The AppAdapter interface defines the contract for integrating specific Office applications into the chat interface. Implement this to provide app-specific tools, system prompts, and UI components. ```typescript interface AppAdapter { tools: AgentTool[]; // App-specific tools buildSystemPrompt: (skills) => string; // System prompt getDocumentId: () => Promise; // Unique doc ID for sessions getDocumentMetadata?: () => Promise<...>; // Injected into each prompt onToolResult?: (id, result, isError) => void; // Follow-mode, navigation metadataTag?: string; // XML tag for metadata (default: "doc_context") handleLinkClick?: (context) => "handled" | "default" | Promise<...>; ToolExtras?: Component; // Extra UI in tool call blocks HeaderExtras?: Component; // Extra header controls SelectionIndicator?: Component; // App-specific selection status UI appName?: string; appVersion?: string; emptyStateMessage?: string; } ``` -------------------------------- ### Release Patch Version (PowerPoint) Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Releases a patch version of the PowerPoint add-in, updating version number, changelog, and pushing changes. ```bash pnpm release:ppt patch ``` -------------------------------- ### Register Custom Bash Commands Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Register custom commands that integrate with the bash shell and generate prompt snippets. Uses getSharedCustomCommands for built-in commands like pdf-to-text and web-search. ```typescript import { getSharedCustomCommands, type CustomCommandsResult, type StorageNamespace } from "@office-agents/sdk"; function getCustomCommands(ns: StorageNamespace): CustomCommandsResult { // getSharedCustomCommands provides built-in commands like // pdf-to-text, docx-to-text, xlsx-to-csv, web-search, web-fetch return getSharedCustomCommands({ ns }); } const ctx = new AgentContext({ customCommands: getCustomCommands, }); // Command snippets are derived from registered commands const snippets = ctx.commandSnippets; // string[] ``` -------------------------------- ### Execute Arbitrary JavaScript in Taskpane Source: https://github.com/hewliyang/office-agents/blob/main/README.md Run custom JavaScript code directly within the Office taskpane context for debugging purposes. ```bash # Read the active Word document body text pnpm exec office-bridge exec word --code \ "const body = context.document.body; body.load('text'); await context.sync(); return body.text;" ``` -------------------------------- ### Event Flow for Threshold-Triggered Compaction Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Describes the event sequence when compaction is initiated due to token usage nearing the context limit. It involves detecting the threshold breach, setting 'isCompacting', running compaction, updating messages, and proceeding without an automatic retry. ```typescript // 1. agent streams response successfully // 2. message_end → usage shows context near limit // 3. agent_end fires → onStreamingEnd() saves session // 4. detect threshold breach // 5. set isCompacting = true // 6. run compaction (LLM call for summary) // 7. insert compactionSummary, replaceMessages, save session // 8. set isCompacting = false // 9. NO auto-retry — user continues manually ``` -------------------------------- ### Define a Tool Source: https://github.com/hewliyang/office-agents/blob/main/packages/sdk/README.md Define a custom tool using the defineTool function and TypeBox for parameter validation. ```typescript import { defineTool, toolSuccess } from "@office-agents/sdk"; import { Type } from "@sinclair/typebox"; const greetTool = defineTool({ name: "greet", label: "Greet", description: "Greet someone by name", parameters: Type.Object({ name: Type.String({ description: "Name to greet" }), }), execute: async (toolCallId, params) => { return toolSuccess({ message: `Hello, ${params.name}!` }); }, }); ``` -------------------------------- ### Stop Office RPC Bridge Server Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Stops the local Office RPC bridge server. ```bash pnpm bridge:stop ``` -------------------------------- ### Proposed Table OOXML Tool Signature Source: https://github.com/hewliyang/office-agents/blob/main/packages/word/TODO.md A proposed function signature for retrieving table-specific OOXML by index and row range. ```python get_table_ooxml(tableIndex, startRow?, endRow?) ``` -------------------------------- ### Release Patch Version (Excel) Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Releases a patch version of the Excel add-in, updating version number, changelog, and pushing changes. ```bash pnpm release:excel patch ``` -------------------------------- ### TypeScript Type Checking Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Performs TypeScript type checking across all packages in the project. ```bash pnpm typecheck ``` -------------------------------- ### Event Flow for Overflow-Triggered Compaction Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Details the sequence of events when compaction is triggered by an overflow error. It includes detecting the error, setting the 'isCompacting' state, performing compaction, updating messages, and automatically retrying the failed prompt. ```typescript // 1. agent streams response // 2. message_end → stopReason: "error" (overflow) // 3. agent_end fires → onStreamingEnd() saves session // 4. detect overflow in message_end or agent_end handler // 5. set isCompacting = true, emit state update // 6. remove error message from agent state // 7. run compaction (LLM call for summary) // 8. insert compactionSummary, replaceMessages, save session // 9. set isCompacting = false // 10. auto-retry: re-send the last user prompt ``` -------------------------------- ### Stop Bridge from Shell Source: https://github.com/hewliyang/office-agents/blob/main/packages/bridge/README.md Alternative commands to terminate the bridge process. ```bash office-bridge stop # or pnpm bridge:stop ``` -------------------------------- ### UI State Management for Compaction Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Introduces a new boolean state flag, 'isCompacting', to the 'RuntimeState'. This flag controls UI elements such as disabling user input and displaying a status indicator during the asynchronous compaction process. ```typescript interface RuntimeState { // ... other states ... isCompacting: boolean; } ``` -------------------------------- ### Retrieve Table OOXML Source: https://github.com/hewliyang/office-agents/blob/main/packages/word/TODO.md Accesses the OOXML representation of a specific table range within the document body. ```javascript body.tables.items[i].getRange().getOoxml() ``` -------------------------------- ### Display Filtering Utility (SDK) Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Filters out 'compactionSummary' messages during the conversion of 'AgentMessage[]' to 'ChatMessage[]' for UI display. This ensures that only user-visible messages are rendered in the chat interface, maintaining a linear history. ```typescript function agentMessagesToChatMessages(agentMessages: AgentMessage[]): ChatMessage[] { return agentMessages .filter(msg => msg.role !== "compactionSummary") .map(convertAgentMessageToChatMessage); } ``` -------------------------------- ### UI Updates for Compaction State Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Lists necessary UI modifications to support the compaction feature. This includes adding the 'isCompacting' flag to 'RuntimeState', disabling input in 'ChatInterface' when compacting, displaying a visual indicator, and updating token statistics. ```typescript // RuntimeState: add isCompacting: boolean // ChatInterface: disable input when isCompacting // ChatInterface: show compaction indicator (toast, inline status, or subtle banner) // Stats bar: update lastInputTokens after compaction ``` -------------------------------- ### Release Patch Version (Bridge) Source: https://github.com/hewliyang/office-agents/blob/main/AGENTS.md Releases a patch version of the Bridge package, updating version number, changelog, and pushing changes. ```bash pnpm release:bridge patch ``` -------------------------------- ### Overflow Detection Logic (SDK) Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Detects context overflow conditions within the 'handleAgentEvent' function for 'message_end' events. It checks for specific error messages or if the token usage exceeds a defined threshold, indicating the need for compaction. ```typescript if (assistantMessage.stopReason === "error" && assistantMessage.error?.message.includes("context overflow")) { // Handle overflow } if (usage.totalTokens > contextWindow - reserveTokens) { // Handle threshold breach } ``` -------------------------------- ### Define Custom Message Type (SDK) Source: https://github.com/hewliyang/office-agents/blob/main/TODO.md Defines a custom message type 'compactionSummary' by declaration-merging 'CustomAgentMessages'. This new type includes a 'role' property set to 'compactionSummary', a 'summary' string, and a 'timestamp' number. ```typescript declare global { interface CustomAgentMessages { compactionSummary: { role: "compactionSummary"; summary: string; timestamp: number; }; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.