cmd-op-sdk 1.3.2__tar.gz

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.
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: cmd-op-sdk
3
+ Version: 1.3.2
4
+ Summary: Thin Python SDK for the cmd_op resident pipe — forwards cmd_op commands to a running resident, no per-command process spawn. The same CLI is an MCP server for AI agents.
5
+ Author: karlmoriaty
6
+ Maintainer: karlmoriaty
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/karlmoriaty/office-command-operate
9
+ Project-URL: Repository, https://github.com/karlmoriaty/office-command-operate
10
+ Keywords: cmd_op,office,docx,xlsx,pptx,ooxml,mcp,ai-agents,office-automation
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Operating System :: Microsoft :: Windows
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+
17
+ # cmd_op — Python SDK
18
+
19
+ A **thin** Python SDK for the [cmd_op](https://github.com/karlmoriaty/office-command-operate) **resident pipe**. It does one
20
+ thing: forward a cmd_op command to a running resident over its named pipe and
21
+ hand back the response — no per-command process spawn, so a loop of edits is
22
+ ~hundreds of times faster than shelling out to the CLI per command.
23
+
24
+ "Thin" is the point: there is **no second vocabulary** to learn. A command is the
25
+ same dict you'd put in a cmd_op `batch` list; the SDK just carries it over the
26
+ pipe. Anything a `doc.set_cell(...)` / `doc.add_paragraph(...)` method would do is
27
+ **fully supported** — you just spell it `doc.send({"command": "set", ...})`, with
28
+ the exact same effect. One uniform verb instead of dozens of per-element named
29
+ methods: same power, nothing extra to memorize, and new cmd_op features work
30
+ the day they ship without an SDK update.
31
+
32
+ ## The cmd_op CLI (auto-installed if missing)
33
+
34
+ `pip install cmd-op-sdk` installs **only this SDK** (the Python library); the
35
+ real work is done by the `cmd_op` binary. You don't have to install it
36
+ yourself — if `cmd_op` isn't found on your `PATH` (or in the default install
37
+ location), the SDK **provisions it on first use**: it runs cmd_op's official
38
+ installer (`install.sh` on Linux, `install.ps1` on Windows), fetched
39
+ straight from the repository. A one-line notice is
40
+ printed before it installs — it never does so silently. Pass `auto_install=False`
41
+ to `open()`/`create()` to disable this and require a pre-installed CLI instead.
42
+
43
+ To install the CLI ahead of time (or to control where it lands):
44
+
45
+ ```bash
46
+ python -m cmd_op install # runs cmd_op's official installer
47
+ # …or directly:
48
+ curl -fsSL https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.sh | bash
49
+ # Windows (PowerShell):
50
+ irm https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.ps1 | iex
51
+ ```
52
+
53
+ `cmd_op.install()` does the same from Python. If the CLI can't be found or
54
+ installed, the SDK raises a clear error pointing here (never a cryptic
55
+ `FileNotFoundError`).
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install cmd-op-sdk # once published — note: import name is `cmd_op`
61
+ # or, from a checkout of this repo:
62
+ pip install ./sdk/python
63
+ ```
64
+
65
+ The pip/distribution name is `cmd-op-sdk`, but you `import cmd_op`
66
+ (distribution name ≠ import name, like `pip install pillow` → `import PIL`).
67
+
68
+ Zero third-party dependencies (standard library only).
69
+
70
+ ## Quickstart
71
+
72
+ ```python
73
+ import cmd_op
74
+
75
+ # create() makes a new file and returns a live session handle;
76
+ # open() does the same for an existing file. Both return a Document.
77
+ with cmd_op.create("report.xlsx", "--force") as doc:
78
+ doc.send({"command": "set", "path": "/Sheet1/A1",
79
+ "props": {"text": "Region", "bold": "true"}})
80
+ doc.send({"command": "set", "path": "/Sheet1/B1", "props": {"formula": "=SUM(B2:B9)"}})
81
+
82
+ # read one back (returns the parsed JSON envelope)
83
+ node = doc.send({"command": "get", "path": "/Sheet1/A1"})
84
+ print(node["data"]["results"][0]["text"]) # -> Region
85
+
86
+ # many edits in ONE pipe round-trip
87
+ doc.batch([
88
+ {"command": "set", "path": "/Sheet1/A2", "props": {"text": "North"}},
89
+ {"command": "set", "path": "/Sheet1/A3", "props": {"text": "South"}},
90
+ ])
91
+
92
+ doc.send({"command": "save"})
93
+ # leaving `with` closes the resident (which flushes to disk)
94
+
95
+ # borrow an already-running resident without owning it: skip `with`/close()
96
+ d = cmd_op.open("report.xlsx")
97
+ print(d.send({"command": "view", "mode": "stats"}, as_json=False))
98
+ ```
99
+
100
+ See `demo.py` for a fuller example.
101
+
102
+ ## The command dict
103
+
104
+ `send(item)` and `batch([item, ...])` take the cmd_op **batch-item** shape:
105
+
106
+ ```jsonc
107
+ { "command": "set", // or "op"; picks the cmd_op command
108
+ "path": "/Sheet1/A1", // every key except command/op/props is forwarded
109
+ "props": { "text": "hi" } } // verbatim as a command argument
110
+ ```
111
+
112
+ Keys are cmd_op's own batch fields (`command`/`op`, `path`, `parent`, `type`,
113
+ `index`, `after`, `before`, `to`, `selector`, `mode`, `depth`, `part`, `xpath`,
114
+ `action`, `xml`) plus a nested `props`. The client maintains no field list of its
115
+ own — run `cmd_op help` (or see the batch docs) for the full reference.
116
+
117
+ `send(..., as_json=False)` requests plain-text output (e.g. `view` / `raw` /
118
+ `dump`), mirroring the CLI's `--json` toggle.
119
+
120
+ ## Errors & resilience
121
+
122
+ - Transport/process failures raise `cmd_op.CmdOpError` (`.code` carries the
123
+ exit code). Business outcomes (e.g. `validate` failing, a bad path) are **not**
124
+ exceptions — they live in the returned envelope's `success` field, same as the
125
+ CLI's exit code.
126
+ - If the resident has gone (crash, idle-timeout, missing pipe), `send`/`batch`
127
+ transparently restart it and retry once. If it's alive but the pipe is
128
+ unresponsive (busy), they raise rather than risk racing the live resident.
129
+
130
+ ## Use it as an MCP server
131
+
132
+ The cmd_op binary that this SDK provisions is also an MCP stdio server, so
133
+ you can give Claude Code, Cursor, VS Code, LM Studio, or opencode direct
134
+ document tools without a separate package:
135
+
136
+ ```bash
137
+ cmd_op mcp claude # also: cursor, vscode, lmstudio, opencode
138
+ cmd_op mcp list
139
+ ```
140
+
141
+ The generic configuration for any MCP client:
142
+
143
+ ```json
144
+ {
145
+ "mcpServers": {
146
+ "cmd_op": {
147
+ "command": "cmd_op",
148
+ "args": ["mcp"]
149
+ }
150
+ }
151
+ }
152
+ ```
153
+
154
+ ## Versioning
155
+
156
+ This client derives the resident's pipe address from the document path the same
157
+ way cmd_op does. That derivation is the one piece coupled to cmd_op
158
+ internals, so keep the client version compatible with your installed cmd_op.
@@ -0,0 +1,142 @@
1
+ # cmd_op — Python SDK
2
+
3
+ A **thin** Python SDK for the [cmd_op](https://github.com/karlmoriaty/office-command-operate) **resident pipe**. It does one
4
+ thing: forward a cmd_op command to a running resident over its named pipe and
5
+ hand back the response — no per-command process spawn, so a loop of edits is
6
+ ~hundreds of times faster than shelling out to the CLI per command.
7
+
8
+ "Thin" is the point: there is **no second vocabulary** to learn. A command is the
9
+ same dict you'd put in a cmd_op `batch` list; the SDK just carries it over the
10
+ pipe. Anything a `doc.set_cell(...)` / `doc.add_paragraph(...)` method would do is
11
+ **fully supported** — you just spell it `doc.send({"command": "set", ...})`, with
12
+ the exact same effect. One uniform verb instead of dozens of per-element named
13
+ methods: same power, nothing extra to memorize, and new cmd_op features work
14
+ the day they ship without an SDK update.
15
+
16
+ ## The cmd_op CLI (auto-installed if missing)
17
+
18
+ `pip install cmd-op-sdk` installs **only this SDK** (the Python library); the
19
+ real work is done by the `cmd_op` binary. You don't have to install it
20
+ yourself — if `cmd_op` isn't found on your `PATH` (or in the default install
21
+ location), the SDK **provisions it on first use**: it runs cmd_op's official
22
+ installer (`install.sh` on Linux, `install.ps1` on Windows), fetched
23
+ straight from the repository. A one-line notice is
24
+ printed before it installs — it never does so silently. Pass `auto_install=False`
25
+ to `open()`/`create()` to disable this and require a pre-installed CLI instead.
26
+
27
+ To install the CLI ahead of time (or to control where it lands):
28
+
29
+ ```bash
30
+ python -m cmd_op install # runs cmd_op's official installer
31
+ # …or directly:
32
+ curl -fsSL https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.sh | bash
33
+ # Windows (PowerShell):
34
+ irm https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.ps1 | iex
35
+ ```
36
+
37
+ `cmd_op.install()` does the same from Python. If the CLI can't be found or
38
+ installed, the SDK raises a clear error pointing here (never a cryptic
39
+ `FileNotFoundError`).
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install cmd-op-sdk # once published — note: import name is `cmd_op`
45
+ # or, from a checkout of this repo:
46
+ pip install ./sdk/python
47
+ ```
48
+
49
+ The pip/distribution name is `cmd-op-sdk`, but you `import cmd_op`
50
+ (distribution name ≠ import name, like `pip install pillow` → `import PIL`).
51
+
52
+ Zero third-party dependencies (standard library only).
53
+
54
+ ## Quickstart
55
+
56
+ ```python
57
+ import cmd_op
58
+
59
+ # create() makes a new file and returns a live session handle;
60
+ # open() does the same for an existing file. Both return a Document.
61
+ with cmd_op.create("report.xlsx", "--force") as doc:
62
+ doc.send({"command": "set", "path": "/Sheet1/A1",
63
+ "props": {"text": "Region", "bold": "true"}})
64
+ doc.send({"command": "set", "path": "/Sheet1/B1", "props": {"formula": "=SUM(B2:B9)"}})
65
+
66
+ # read one back (returns the parsed JSON envelope)
67
+ node = doc.send({"command": "get", "path": "/Sheet1/A1"})
68
+ print(node["data"]["results"][0]["text"]) # -> Region
69
+
70
+ # many edits in ONE pipe round-trip
71
+ doc.batch([
72
+ {"command": "set", "path": "/Sheet1/A2", "props": {"text": "North"}},
73
+ {"command": "set", "path": "/Sheet1/A3", "props": {"text": "South"}},
74
+ ])
75
+
76
+ doc.send({"command": "save"})
77
+ # leaving `with` closes the resident (which flushes to disk)
78
+
79
+ # borrow an already-running resident without owning it: skip `with`/close()
80
+ d = cmd_op.open("report.xlsx")
81
+ print(d.send({"command": "view", "mode": "stats"}, as_json=False))
82
+ ```
83
+
84
+ See `demo.py` for a fuller example.
85
+
86
+ ## The command dict
87
+
88
+ `send(item)` and `batch([item, ...])` take the cmd_op **batch-item** shape:
89
+
90
+ ```jsonc
91
+ { "command": "set", // or "op"; picks the cmd_op command
92
+ "path": "/Sheet1/A1", // every key except command/op/props is forwarded
93
+ "props": { "text": "hi" } } // verbatim as a command argument
94
+ ```
95
+
96
+ Keys are cmd_op's own batch fields (`command`/`op`, `path`, `parent`, `type`,
97
+ `index`, `after`, `before`, `to`, `selector`, `mode`, `depth`, `part`, `xpath`,
98
+ `action`, `xml`) plus a nested `props`. The client maintains no field list of its
99
+ own — run `cmd_op help` (or see the batch docs) for the full reference.
100
+
101
+ `send(..., as_json=False)` requests plain-text output (e.g. `view` / `raw` /
102
+ `dump`), mirroring the CLI's `--json` toggle.
103
+
104
+ ## Errors & resilience
105
+
106
+ - Transport/process failures raise `cmd_op.CmdOpError` (`.code` carries the
107
+ exit code). Business outcomes (e.g. `validate` failing, a bad path) are **not**
108
+ exceptions — they live in the returned envelope's `success` field, same as the
109
+ CLI's exit code.
110
+ - If the resident has gone (crash, idle-timeout, missing pipe), `send`/`batch`
111
+ transparently restart it and retry once. If it's alive but the pipe is
112
+ unresponsive (busy), they raise rather than risk racing the live resident.
113
+
114
+ ## Use it as an MCP server
115
+
116
+ The cmd_op binary that this SDK provisions is also an MCP stdio server, so
117
+ you can give Claude Code, Cursor, VS Code, LM Studio, or opencode direct
118
+ document tools without a separate package:
119
+
120
+ ```bash
121
+ cmd_op mcp claude # also: cursor, vscode, lmstudio, opencode
122
+ cmd_op mcp list
123
+ ```
124
+
125
+ The generic configuration for any MCP client:
126
+
127
+ ```json
128
+ {
129
+ "mcpServers": {
130
+ "cmd_op": {
131
+ "command": "cmd_op",
132
+ "args": ["mcp"]
133
+ }
134
+ }
135
+ }
136
+ ```
137
+
138
+ ## Versioning
139
+
140
+ This client derives the resident's pipe address from the document path the same
141
+ way cmd_op does. That derivation is the one piece coupled to cmd_op
142
+ internals, so keep the client version compatible with your installed cmd_op.
@@ -0,0 +1,622 @@
1
+ r"""
2
+ cmd_op — a thin Python shell over cmd_op's resident pipe.
3
+
4
+ It does ONE thing: forward a command to the running resident over its named
5
+ pipe and hand back the response. There is NO second vocabulary to learn: a
6
+ command is the same dict you'd put in a cmd_op `batch` list — e.g.
7
+ {"command":"set","path":"/Sheet1/A1","props":{"text":"Hello"}}. `send` forwards
8
+ one; `batch` forwards many in a single round-trip.
9
+
10
+ Two surfaces, by design:
11
+ - bootstrap (infrequent): `create` / `open` spawn ONE CLI process — a file that
12
+ isn't open yet (or doesn't exist yet) has no resident to talk to.
13
+ - everything else (the hot path): `send` / `batch` are pure pipe round-trips,
14
+ no per-command process spawn.
15
+
16
+ import cmd_op
17
+ with cmd_op.create("report.xlsx", "--force") as doc: # make file + get handle
18
+ doc.send({"command": "set", "path": "/Sheet1/A1",
19
+ "props": {"text": "Hello"}})
20
+ print(doc.send({"command": "get", "path": "/Sheet1/A1"}))
21
+ doc.send({"command": "save"})
22
+ # ...or cmd_op.open("existing.xlsx") for a file that already exists.
23
+
24
+ The item keys are cmd_op's batch fields (command/op, path, parent, type,
25
+ index, after, before, to, selector, text, mode, depth, part, xpath, action,
26
+ xml) plus a nested `props` dict. Everything except command/op/props is
27
+ forwarded verbatim as a command argument; the resident dispatches it exactly
28
+ like the matching CLI command. See `cmd_op help` / the batch docs for the
29
+ field-and-prop reference — this shell adds none of its own.
30
+
31
+ Protocol (matches ResidentServer.cs / ResidentClient.cs):
32
+ - pipe name : cmd_op-<SHA256(fullpath)[:16] uppercase>;
33
+ fullpath upper-cased on macOS/Windows, left as-is on Linux.
34
+ - unix path : $TMPDIR/CoreFxPipe_<name> (+ "-ping"); $TMPDIR else /tmp
35
+ - win path : \\.\pipe\<name> (+ "-ping")
36
+ - framing : one request line + one response line, UTF-8, '\n' terminated;
37
+ one connection == one command.
38
+ - request : PascalCase {"Command","Args","Props","Json"}
39
+ - response : {"ExitCode","Stdout","Stderr"}
40
+ """
41
+
42
+ import os
43
+ import sys
44
+ import json
45
+ import time
46
+ import socket
47
+ import hashlib
48
+ import shutil
49
+ import threading
50
+ import subprocess
51
+
52
+ # Mirror cmd_op's TryResident busy-delivery policy (CommandBuilder.cs): a
53
+ # generous connect timeout + a few retries with backoff, applied identically to
54
+ # every command. The reply read itself blocks (no timeout) — like cmd_op's
55
+ # PipeReadLine — trusting the resident to answer once our turn comes up in its
56
+ # serialized queue. Because retries only re-attempt the CONNECT (before the
57
+ # command executes), re-sending is safe even for mutations; there is no
58
+ # "read timed out, resend" path that could double-apply.
59
+ _BUSY_CONNECT_TIMEOUT = 30.0 # = ResidentBusyConnectTimeoutMs (30000)
60
+ _BUSY_MAX_RETRIES = 3 # = ResidentBusyMaxRetries
61
+ # = CommandBuilder's DefaultOpenIdleSeconds. `open` upgrades a reused resident
62
+ # (which `create` may have auto-started with a short 60s timeout) to the 12min
63
+ # interactive window, so a long editing session over an SDK handle isn't cut
64
+ # short by the create-time timeout.
65
+ _OPEN_IDLE_SECONDS = 12 * 60
66
+
67
+ _IS_WIN = sys.platform.startswith("win")
68
+ _IS_MAC = sys.platform == "darwin"
69
+ _builtin_open = open # preserved; this module defines its own open() below
70
+
71
+ # cmd_op's official installer (README one-liner). install() shells out to it;
72
+ # the missing-CLI error points users at it / at install().
73
+ # Installer scripts: GitHub raw is the only source. There is no project mirror.
74
+ _INSTALL_SH_URL = "https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.sh"
75
+ _INSTALL_PS1_URL = "https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.ps1"
76
+ _MISSING_CLI = (
77
+ "cmd_op CLI not found: {bin!r} is not on PATH nor in the default install "
78
+ "location (~/.local/bin, or %LOCALAPPDATA%\\cmd_op on Windows). This SDK only forwards "
79
+ "commands to the cmd_op binary, which must be installed separately. Install it:\n"
80
+ " python -m cmd_op install # runs the official installer\n"
81
+ " # or: curl -fsSL " + _INSTALL_SH_URL + " | bash\n"
82
+ "Already installed elsewhere? pass binary=\"/path/to/cmd_op\"."
83
+ )
84
+
85
+
86
+ class CmdOpError(Exception):
87
+ """Raised on transport/process failure (could not reach the resident).
88
+ Business outcomes are NOT exceptions — they live in the returned envelope's
89
+ 'success' field, same as the CLI's exit code."""
90
+ def __init__(self, code, msg):
91
+ super().__init__(f"[exit {code}] {msg}")
92
+ self.code = code
93
+
94
+
95
+ # ---------------------------------------------------------------- pipe address
96
+ def _dotnet_tempdir():
97
+ # Mirror .NET Path.GetTempPath() on Unix exactly: $TMPDIR else /tmp.
98
+ return os.environ.get("TMPDIR") or "/tmp"
99
+
100
+
101
+ def _canonical_path(file_path):
102
+ """Match the path cmd_op's resident hashes into the pipe name. On Windows
103
+ it derives the name from GetFullPath, which expands 8.3 short components
104
+ (RUNNER~1, or any user name > 8 chars under %TEMP%) to their long form.
105
+ os.path.abspath does NOT expand 8.3, so a short path hashes to a different
106
+ pipe and every connect fails with ENOENT — hence realpath, which does expand
107
+ it. realpath needs the file to exist; fall back to the abspath when it
108
+ doesn't. realpath ALSO resolves symlinks/junctions, which GetFullPath does
109
+ not; harmless here because we hand this resolved path to the resident, so the
110
+ server's GetFullPath sees the already-resolved string and both sides hash the
111
+ same thing. Windows only — on unix cmd_op uses GetFullPath (no symlink
112
+ resolution), so realpath would diverge there (e.g. /tmp -> /private/tmp on
113
+ macOS)."""
114
+ resolved = os.path.abspath(file_path)
115
+ if _IS_WIN:
116
+ try:
117
+ return os.path.realpath(resolved)
118
+ except OSError:
119
+ pass
120
+ return resolved
121
+
122
+
123
+ def pipe_paths(file_path):
124
+ """(main, ping) pipe addresses for a document path. Exposed for debugging."""
125
+ full = _canonical_path(file_path)
126
+ if _IS_WIN:
127
+ # .NET Path.GetFullPath uses backslashes; os.path.realpath may return
128
+ # forward slashes, which would hash to a different pipe name.
129
+ full = full.replace("/", "\\").upper()
130
+ elif _IS_MAC:
131
+ full = full.upper() # Linux: case-sensitive, no upper
132
+ h = hashlib.sha256(full.encode("utf-8")).hexdigest().upper()[:16]
133
+ name = f"cmd_op-{h}"
134
+ if _IS_WIN:
135
+ return rf"\\.\pipe\{name}", rf"\\.\pipe\{name}-ping"
136
+ base = os.path.join(_dotnet_tempdir(), f"CoreFxPipe_{name}")
137
+ return base, base + "-ping"
138
+
139
+
140
+ # ---------------------------------------------------------------- transport
141
+ # One attempt: bound the CONNECT, then block on the reply (no read timeout) —
142
+ # exactly like cmd_op's TrySend (Connect(timeout) + blocking PipeReadLine).
143
+ def _send_unix(sock_path, line, connect_timeout):
144
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
145
+ try:
146
+ s.settimeout(connect_timeout)
147
+ s.connect(sock_path)
148
+ s.settimeout(None) # block on the reply; resident answers in turn
149
+ s.sendall(line)
150
+ buf = b""
151
+ while not buf.endswith(b"\n"):
152
+ chunk = s.recv(65536)
153
+ if not chunk:
154
+ break
155
+ buf += chunk
156
+ return buf
157
+ finally:
158
+ s.close()
159
+
160
+
161
+ def _send_win(pipe_path, line, connect_timeout):
162
+ deadline = time.time() + connect_timeout
163
+ while True: # bound the "open" (connect) phase
164
+ try:
165
+ f = _builtin_open(pipe_path, "r+b", buffering=0) # not the module open()
166
+ break
167
+ except FileNotFoundError:
168
+ # No pipe == no resident. Fail FAST, like _send_unix's connect()
169
+ # raising ENOENT immediately — do NOT spin to the deadline. This is
170
+ # what makes a max_retries=0 probe (_serves/alive) fail fast instead
171
+ # of sitting through the whole connect_timeout when nothing is there.
172
+ raise
173
+ except OSError:
174
+ # The pipe exists but the open lost the race (e.g. ERROR_PIPE_BUSY:
175
+ # every server instance is mid-handoff). The resident IS alive, so
176
+ # retry until the connect deadline.
177
+ if time.time() > deadline:
178
+ raise
179
+ time.sleep(0.02)
180
+ try:
181
+ # FileIO.write (raw, buffering=0) issues a single WriteFile and may
182
+ # return a short count, so loop until the whole request is out — a
183
+ # truncated request leaves the resident blocking for a newline that
184
+ # never comes, deadlocking the (untimed) reply read. Mirrors _send_unix's
185
+ # sendall() and the C# client's Stream.Write.
186
+ view = memoryview(line)
187
+ sent = 0
188
+ while sent < len(view):
189
+ n = f.write(view[sent:])
190
+ if n is None: # non-blocking handle not ready (shouldn't happen)
191
+ continue
192
+ sent += n
193
+ buf = b""
194
+ while not buf.endswith(b"\n"): # blocking read, like PipeReadLine
195
+ chunk = f.read(65536)
196
+ if not chunk:
197
+ break
198
+ buf += chunk
199
+ return buf
200
+ finally:
201
+ f.close()
202
+
203
+
204
+ def _rpc(sock_path, req, connect_timeout=_BUSY_CONNECT_TIMEOUT, max_retries=_BUSY_MAX_RETRIES):
205
+ """Forward one request, mirroring cmd_op's TrySend: bounded connect + a few
206
+ retries with backoff, then a blocking read. A retry only re-attempts the
207
+ connect (before the command runs), so it never double-applies a mutation. If
208
+ the command still can't be delivered, raise a busy/unresponsive error — never
209
+ fall back to touching the file directly (that would race the resident).
210
+
211
+ `max_retries` overrides the busy-retry count. Liveness probes (_serves) pass 0
212
+ so a missing/stale pipe fails FAST instead of sleeping through ~0.3s of backoff
213
+ — retrying a probe the resident isn't answering can't make it answer; the
214
+ busy-retry policy is for delivering a real command to a slow-but-live pipe."""
215
+ line = (json.dumps(req, ensure_ascii=False) + "\n").encode("utf-8")
216
+ send = _send_win if _IS_WIN else _send_unix
217
+ for attempt in range(max_retries + 1):
218
+ try:
219
+ raw = send(sock_path, line, connect_timeout)
220
+ break
221
+ except OSError as e:
222
+ if attempt >= max_retries:
223
+ raise CmdOpError(-1,
224
+ f"resident is running but the command could not be delivered "
225
+ f"(pipe busy or unresponsive); retry, or close and reopen [{e}]")
226
+ time.sleep(0.05 * (attempt + 1)) # = TrySend's 50*(n+1)ms backoff
227
+ # utf-8-sig: the resident's StreamWriter (Encoding.UTF8) prepends a BOM the
228
+ # C# StreamReader strips; we must too, or json.loads chokes on the leading .
229
+ text = raw.decode("utf-8-sig")
230
+ if not text.strip():
231
+ # Empty/closed reply: the resident accepted the connection but closed
232
+ # without a complete response (e.g. crashed mid-serve). We refuse to
233
+ # re-send — the command may already have been APPLIED before the resident
234
+ # died, so re-sending would double-apply a non-idempotent op — and raise
235
+ # instead. cmd_op's TrySend now matches: its retry covers only the
236
+ # connect phase (before the command is written); on an empty reply after a
237
+ # successful write it returns null without re-sending, the C# equivalent of
238
+ # this raise. _cmd's recovery then restarts a dead resident and retries once
239
+ # (a fresh connect, before re-send), and _serves()/alive() (which swallow
240
+ # CmdOpError) read an empty reply as "not alive".
241
+ raise CmdOpError(-1,
242
+ "resident closed the connection without a response "
243
+ "(it may have crashed mid-command); retry, or close and reopen")
244
+ return json.loads(text)
245
+
246
+
247
+ def _parse(resp):
248
+ """Return the useful payload: the parsed JSON envelope (dict/list) if Stdout is
249
+ a JSON object/array, otherwise the raw Stdout text ("" when empty). We accept
250
+ ONLY dict/list from json.loads — a text-mode reply that happens to BE a bare
251
+ JSON scalar ("42", "true", "null", a quoted string) must stay text, or the
252
+ caller can't tell literal text "42" from the number 42 (and None from a missing
253
+ key). Faithful to the response — no synthesizing a dict for view/raw text."""
254
+ out = resp.get("Stdout", "")
255
+ try:
256
+ v = json.loads(out)
257
+ except ValueError:
258
+ return out
259
+ return v if isinstance(v, (dict, list)) else out
260
+
261
+
262
+ def _strv(d):
263
+ # Drop None-valued props (omit), matching how _cmd() drops None args — a prop
264
+ # set to None means "don't send it", not "send empty string". Pass "" for
265
+ # an explicit empty value.
266
+ return {k: str(v) for k, v in d.items() if v is not None}
267
+
268
+
269
+ def _serves(ping_path, full_path, timeout=1.0):
270
+ """Is a resident alive on `ping_path` AND serving `full_path`? Probes the
271
+ always-responsive `-ping` pipe (cmd_op's TryConnect equivalent): it answers
272
+ even while the MAIN pipe is busy. The path-match guards against a stale socket
273
+ serving a different/renamed file. `full_path` must already be absolute.
274
+ Single-shot (max_retries=0): a probe should fail fast, not sit through the
275
+ busy-retry backoff that a real command delivery uses."""
276
+ try:
277
+ resp = _rpc(ping_path, {"Command": "__ping__"}, timeout, max_retries=0)
278
+ except CmdOpError:
279
+ return False
280
+ served = resp.get("Stdout", "").strip() # ping echoes the served file path
281
+ if not served:
282
+ return False
283
+ a = os.path.abspath(served)
284
+ return a == full_path or ((_IS_MAC or _IS_WIN) and a.lower() == full_path.lower())
285
+
286
+
287
+ def _install_dir_candidate(name):
288
+ """Where the official installer (install.sh / install.ps1) drops the binary:
289
+ ~/.local/bin on macOS/Linux, %LOCALAPPDATA%\\cmd_op on Windows. Used only
290
+ as a PATH-miss fallback (see _resolve_binary)."""
291
+ if _IS_WIN:
292
+ base = os.environ.get("LOCALAPPDATA")
293
+ if not base:
294
+ return None
295
+ exe = name if name.lower().endswith(".exe") else name + ".exe"
296
+ return os.path.join(base, "cmd_op", exe)
297
+ return os.path.join(os.path.expanduser("~"), ".local", "bin", name)
298
+
299
+
300
+ def _resolve_binary(binary):
301
+ """Resolve the cmd_op binary to invoke. Order: explicit path (a value with
302
+ a path separator) is trusted as-is; otherwise a bare name is looked up on
303
+ PATH; if PATH misses, fall back to the official installer's known location.
304
+
305
+ Why the fallback: the installer adds its dir to PATH via the shell rc file, so
306
+ a bare 'cmd_op' resolves in an interactive terminal — but NOT in processes
307
+ that never sourced that rc (IDE-spawned Python, cron, systemd, CI). The binary
308
+ is still sitting at the known install path; find it there instead of failing.
309
+
310
+ Idempotent: an already-resolved absolute path passes straight through, so it's
311
+ safe to call at every entry point (create + Document)."""
312
+ if os.sep in binary or (os.altsep and os.altsep in binary):
313
+ return binary # explicit path: trust the caller
314
+ found = shutil.which(binary)
315
+ if found:
316
+ return found # on PATH: normal case
317
+ cand = _install_dir_candidate(binary) # PATH miss: try the known install dir
318
+ if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
319
+ return cand
320
+ return binary # give up; _run_cli raises the helpful error
321
+
322
+
323
+ def _runs_ok(binary):
324
+ """True iff `<binary> --version` actually runs and exits 0. Accept only a
325
+ WORKING cmd_op — skip a present-but-broken file, and don't trigger a
326
+ needless install when a usable cmd_op is already there."""
327
+ try:
328
+ return subprocess.run([binary, "--version"], capture_output=True).returncode == 0
329
+ except OSError:
330
+ return False
331
+
332
+
333
+ def _ensure_binary(binary, auto_install=True):
334
+ """Resolve to a WORKING cmd_op, provisioning one if none is found and
335
+ auto_install is set. An explicit path (with a separator) is trusted as-is;
336
+ otherwise each candidate (PATH, then the installer's known location) is
337
+ accepted only when `cmd_op --version` actually runs — so a present-but-
338
+ broken binary is skipped and a usable one never triggers a needless install.
339
+ install() picks install.sh (unix) or install.ps1 (Windows), so auto-install
340
+ works on both."""
341
+ if os.sep in binary or (os.altsep and os.altsep in binary):
342
+ return binary # explicit path: trust the caller
343
+ for cand in filter(None, (shutil.which(binary), _install_dir_candidate(binary))):
344
+ if _runs_ok(cand):
345
+ return cand # a working cmd_op is already here
346
+ if auto_install:
347
+ print("cmd_op CLI not found — installing from GitHub ...", file=sys.stderr)
348
+ install() # CLI absent/unusable → official installer
349
+ for cand in filter(None, (shutil.which(binary), _install_dir_candidate(binary))):
350
+ if _runs_ok(cand):
351
+ return cand
352
+ return binary # give up; _run_cli raises the helpful error
353
+
354
+
355
+ def _run_cli(binary, argv):
356
+ """Run `binary <argv...>` (capturing output). A missing binary surfaces as a
357
+ clear CmdOpError with install guidance, not a raw FileNotFoundError."""
358
+ try:
359
+ # text=True alone decodes with locale.getencoding() — the ANSI code page
360
+ # on Windows (cp936/cp1252). The CLI always writes UTF-8, so a message
361
+ # carrying a non-ASCII path raised UnicodeDecodeError (or mojibake) out
362
+ # of subprocess instead of a clean CmdOpError. The resident-pipe
363
+ # route below already decodes utf-8; keep the two agreeing.
364
+ return subprocess.run([binary, *argv], capture_output=True,
365
+ text=True, encoding="utf-8", errors="replace")
366
+ except FileNotFoundError:
367
+ raise CmdOpError(127, _MISSING_CLI.format(bin=binary)) from None
368
+
369
+
370
+ # ---------------------------------------------------------------- the shell
371
+ class Document:
372
+ def __init__(self, path, binary="cmd_op", timeout=30.0):
373
+ # Canonical (Windows 8.3-expanded) so the pipe name AND the _serves()
374
+ # path comparison both match what the resident reports.
375
+ self.path = _canonical_path(path)
376
+ self.bin = _resolve_binary(binary)
377
+ self.timeout = timeout # connect timeout (s); the reply read blocks
378
+ self._main, self._ping = pipe_paths(self.path)
379
+ self._restart_lock = threading.Lock() # serialize dead-resident restarts
380
+ self._start()
381
+
382
+ def _start(self):
383
+ # If a resident is ALREADY serving this file, reuse it — no process spawn.
384
+ # Mirrors cmd_op, where a command after `create` reuses the resident
385
+ # `create` auto-started instead of re-running `open`. _serves() is a real
386
+ # liveness probe (ping the -ping pipe + verify the served path), not a
387
+ # socket-file-exists check, so a stale/dead socket fails the probe and
388
+ # falls through to `cmd_op open`, which replaces it via TryConnect.
389
+ # (A plain os.path.exists() here would wrongly skip on a stale socket.)
390
+ if _serves(self._ping, self.path):
391
+ return
392
+ # Otherwise spawn `cmd_op open` (one process). It's idempotent and uses
393
+ # the same TryConnect to start a fresh resident or replace a stale socket.
394
+ r = _run_cli(self.bin, ["open", self.path])
395
+ if r.returncode != 0:
396
+ raise CmdOpError(r.returncode, r.stderr or r.stdout)
397
+
398
+ # -- transport primitive: build {Command,Args,Props,Json}, forward, parse --
399
+ def _cmd(self, command, args=None, props=None, as_json=True, timeout=None):
400
+ # `as_json`, not `json`, so we don't shadow the imported json module.
401
+ # timeout=None uses this Document's default (self.timeout). It bounds the
402
+ # CONNECT/delivery (with retries); the reply read blocks, so a legitimately
403
+ # slow command isn't cut off — it waits for the resident, like cmd_op.
404
+ req = {"Command": command, "Json": as_json}
405
+ if args:
406
+ req["Args"] = {k: str(v) for k, v in args.items() if v is not None}
407
+ if props is not None:
408
+ req["Props"] = _strv(props)
409
+ t = self.timeout if timeout is None else timeout
410
+ try:
411
+ return _rpc(self._main, req, t)
412
+ except CmdOpError:
413
+ # Delivery failed after _rpc's own connect retries. Use the -ping pipe
414
+ # to tell DEAD from BUSY — cmd_op's own distinction (alive()):
415
+ # • ALIVE but main pipe unresponsive → do NOT bypass it. cmd_op
416
+ # deliberately dropped the direct-file fallback: a second writer
417
+ # racing the live resident loses data on its eventual save. Re-raise
418
+ # the busy error so the caller can retry or close+reopen.
419
+ # • DEAD (crashed / stale socket) → restart with one `cmd_op open`
420
+ # and retry ONCE. Safe across reads and mutations: mutations live in
421
+ # memory until save/close, so a crash loses them and disk holds the
422
+ # last save — replaying against the restarted (disk-state) resident
423
+ # reproduces the lost op once, with nothing live to double-apply.
424
+ if self.alive():
425
+ raise
426
+ # Serialize the restart across threads sharing this Document. Without
427
+ # the lock, N concurrent callers each see alive()==False and each spawn
428
+ # `cmd_op open`, leaving N-1 orphaned residents on the same file
429
+ # (which can then race each other's save). Re-check alive() inside the
430
+ # lock so only the first thread restarts; the rest find it back up.
431
+ with self._restart_lock:
432
+ if not self.alive():
433
+ self._start()
434
+ return _rpc(self._main, req, t)
435
+
436
+ # -- the surface: send ONE batch-shaped command, or a LIST of them ---------
437
+ def send(self, item, as_json=True, timeout=None):
438
+ """Forward ONE command in cmd_op's batch-item shape and return its
439
+ parsed result (the JSON envelope, or raw text for content commands).
440
+
441
+ `item` is exactly a dict you'd put in a `batch` list, e.g.
442
+ {"command": "set", "path": "/Sheet1/A1", "props": {"text": "hi"}}
443
+ {"command": "get", "path": "/Sheet1/A1"}
444
+ Keys are cmd_op's batch fields; `command` (or `op`) picks the command,
445
+ `props` becomes the property map, and every other key is forwarded
446
+ verbatim as a command argument — no field list maintained here, so new
447
+ cmd_op fields work without touching this shell.
448
+
449
+ `as_json=False` requests plain-text output (view/raw/dump), mirroring the
450
+ CLI's --json toggle."""
451
+ command = item.get("command") or item.get("op")
452
+ if not command:
453
+ raise CmdOpError(-1, "send(item): item needs a 'command' (or 'op') key")
454
+ args = {k: v for k, v in item.items() if k not in ("command", "op", "props")}
455
+ return _parse(self._cmd(command, args, item.get("props"),
456
+ as_json=as_json, timeout=timeout))
457
+
458
+ def batch(self, items, force=True, stop_on_error=False, timeout=None):
459
+ """Forward cmd_op's `batch` command: apply a LIST of the same item
460
+ dicts as `send` in ONE round-trip — the fast path for many writes. Same
461
+ contract as `send`, just plural."""
462
+ args = {"batchJson": json.dumps(items, ensure_ascii=False),
463
+ "force": force, "stopOnError": stop_on_error}
464
+ return _parse(self._cmd("batch", args, timeout=timeout))
465
+
466
+ def _set_idle_timeout(self, seconds):
467
+ # Best-effort idle-timeout upgrade, served on the always-responsive ping
468
+ # pipe (bypasses _commandLock, answers even while the main pipe is busy).
469
+ # Mirrors ResidentClient.SendSetIdleTimeout: a failure is non-fatal — the
470
+ # resident is still usable, it just keeps its original idle schedule.
471
+ # Single-shot (max_retries=0): don't sit through the busy backoff for a
472
+ # best-effort nicety.
473
+ try:
474
+ _rpc(self._ping, {"Command": "__set-idle-timeout__",
475
+ "Args": {"seconds": str(seconds)}},
476
+ self.timeout, max_retries=0)
477
+ except CmdOpError:
478
+ pass
479
+
480
+ def alive(self, timeout=1.0):
481
+ """Return True iff a resident is alive AND serving this file. Probes the
482
+ always-responsive `-ping` pipe (cmd_op's TryConnect), which answers even
483
+ while the MAIN pipe is busy — so it distinguishes "alive but busy" from
484
+ "gone". This is the discriminator `_cmd` uses on a delivery failure (busy →
485
+ raise, gone → restart+retry); send/batch already auto-recover from a gone
486
+ resident, so call this only when you want to check liveness yourself."""
487
+ return _serves(self._ping, self.path, timeout)
488
+
489
+ # -- lifecycle ------------------------------------------------------------
490
+ def close(self):
491
+ # = `cmd_op close`: stop the resident. It flushes the in-memory doc to
492
+ # disk as it shuts down (handler.Dispose), so no separate save is needed —
493
+ # verified: a set followed by __close__ alone lands on disk.
494
+ #
495
+ # The resident acks AFTER shutting down, so a missing/empty ack (lost to a
496
+ # crash or the 5s write-timeout) still means "closed". A real shutdown
497
+ # data-loss is a NON-empty error response, so it surfaces through _parse.
498
+ try:
499
+ return _parse(_rpc(self._ping, {"Command": "__close__"}, self.timeout))
500
+ except CmdOpError:
501
+ # Only swallow if the resident is actually gone. If it's still alive
502
+ # (ping pipe was momentarily unreachable/busy), the close did NOT take
503
+ # effect — re-raise, or the caller wrongly believes the file is released
504
+ # and may race a re-open/overwrite.
505
+ if self.alive():
506
+ raise
507
+ return "" # resident gone / ack lost — end state is "closed"
508
+
509
+ def __enter__(self):
510
+ return self
511
+
512
+ def __exit__(self, *a):
513
+ # `with` means "I manage this session" → close on exit. To only borrow a
514
+ # resident another program owns, DON'T use `with` and DON'T call close():
515
+ # d = cmd_op.open(f); d.send(...) # left running
516
+ self.close()
517
+
518
+
519
+ def create(path, *args, binary="cmd_op", timeout=30.0, auto_install=True):
520
+ """Create a blank Office document and return a live `Document` handle for it.
521
+
522
+ Parallel to `open`: both return the session handle you actually work with —
523
+ they differ only in the file's expected state. `open` requires an existing
524
+ file; `create` makes a new one (like file mode "x" vs "r"). Extra CLI flags
525
+ pass through verbatim, so there's no option list maintained here:
526
+ with cmd_op.create("report.xlsx", "--force") as doc:
527
+ doc.send({"command": "set", "path": "/Sheet1/A1", "props": {"text": "hi"}})
528
+ cmd_op.create("doc", "--type", "docx")
529
+
530
+ One CLI spawn (`cmd_op create`), which also auto-starts a resident for the
531
+ new file; the returned Document binds to THAT resident (no second spawn).
532
+ Raises CmdOpError on failure, inheriting cmd_op's exact semantics:
533
+ • file held by a LIVE resident → file_locked (close it first). We do NOT
534
+ silently close+overwrite it — in a shared workspace that resident may be
535
+ another owner's active session.
536
+ • file exists without --force → file_exists (pass "--force" to overwrite)."""
537
+ full = os.path.abspath(path)
538
+ binary = _ensure_binary(binary, auto_install)
539
+ r = _run_cli(binary, ["create", full, *args])
540
+ if r.returncode != 0:
541
+ raise CmdOpError(r.returncode, r.stderr or r.stdout)
542
+ # create auto-started a resident for the new file; bind a handle to it
543
+ # (Document.__init__ -> _start -> _serves finds it alive, so no extra spawn).
544
+ return Document(full, binary=binary, timeout=timeout)
545
+
546
+
547
+ def open(path, binary="cmd_op", timeout=30.0, auto_install=True):
548
+ """Open an EXISTING document and return a live `Document` handle (parallel to
549
+ `create`, which makes a new file). `cmd_op open` is idempotent: it reuses a
550
+ resident already serving this file or starts one — and if a live resident is
551
+ already up, no process is spawned at all.
552
+
553
+ Lifecycle:
554
+ Owner — `with cmd_op.open(f) as d: ...` (exit closes the resident)
555
+ Borrow — `d = cmd_op.open(f); d.send(...)` (no `with`/close → left running)
556
+
557
+ Failure model (applies to every send/batch on the handle):
558
+ • resident DEAD/gone (crash, idle-timeout, missing pipe) → transparently
559
+ restarted and the command retried once; the caller sees no error.
560
+ • resident ALIVE but the pipe is unresponsive (busy) → raises CmdOpError
561
+ — never a deadlock, and never bypassing the live resident (that would race
562
+ its save and lose data). Retry, or close() and reopen.
563
+
564
+ `timeout` bounds command DELIVERY (connect + retries) in seconds, mirroring
565
+ cmd_op's TrySend; the reply read itself blocks (a busy resident answers in
566
+ turn). Override per call via send(..., timeout=...) / batch(..., timeout=...);
567
+ use alive() to probe liveness."""
568
+ doc = Document(path, binary=_ensure_binary(binary, auto_install), timeout=timeout)
569
+ # Mirror CLI `open`: when reusing a resident `create` auto-started with a
570
+ # short 60s timeout, upgrade it to the 12min interactive window. (If _start
571
+ # spawned `cmd_op open` instead, that path already set 12min; re-sending
572
+ # is idempotent.)
573
+ doc._set_idle_timeout(_OPEN_IDLE_SECONDS)
574
+ return doc
575
+
576
+
577
+ def install():
578
+ """Install the cmd_op CLI binary via its OFFICIAL installer — install.sh on
579
+ unix, install.ps1 on Windows. Reuses cmd_op's own installers (platform
580
+ detection + checksum + ~/.local/bin or %LOCALAPPDATA%\\cmd_op), rather than
581
+ reimplementing download logic that would drift from upstream.
582
+
583
+ Called automatically by open()/create() when the CLI is missing (pass
584
+ auto_install=False to disable), and exposed directly as `python -m cmd_op
585
+ install`. Returns None on success; raises CmdOpError on failure. Output is
586
+ NOT captured, so the installer's progress and checksum lines stream to the
587
+ user."""
588
+ if _IS_WIN:
589
+ print(f"Installing cmd_op via {_INSTALL_PS1_URL} ...", file=sys.stderr)
590
+ # Windows PowerShell (powershell.exe) ships with the OS; -ExecutionPolicy
591
+ # Bypass lets the remote script run without changing machine policy.
592
+ ps = f"$s = irm '{_INSTALL_PS1_URL}'; $s | iex"
593
+ r = subprocess.run(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps])
594
+ if r.returncode != 0:
595
+ raise CmdOpError(r.returncode,
596
+ f"cmd_op install failed (exit {r.returncode}). Run manually:\n"
597
+ f" irm {_INSTALL_PS1_URL} | iex")
598
+ return None
599
+ print(f"Installing cmd_op via {_INSTALL_SH_URL} ...", file=sys.stderr)
600
+ # curl | bash — the script is the only source, no retry layer. Output is
601
+ # NOT captured, so progress and checksum lines stream to the user.
602
+ sh = f"curl -fsSL {_INSTALL_SH_URL} | bash"
603
+ r = subprocess.run(["bash", "-c", sh])
604
+ if r.returncode != 0:
605
+ raise CmdOpError(r.returncode,
606
+ f"cmd_op install failed (exit {r.returncode}). Run manually:\n"
607
+ f" curl -fsSL {_INSTALL_SH_URL} | bash")
608
+ return None
609
+
610
+
611
+ # Advertised surface = the command shell + its error. pipe_paths stays importable
612
+ # (cmd_op.pipe_paths) as a debug helper but isn't part of the command API.
613
+ __all__ = ["open", "create", "install", "Document", "CmdOpError"]
614
+
615
+
616
+ if __name__ == "__main__":
617
+ # `python -m cmd_op install` — bootstrap the CLI binary.
618
+ if len(sys.argv) >= 2 and sys.argv[1] == "install":
619
+ install()
620
+ else:
621
+ print("usage: python -m cmd_op install", file=sys.stderr)
622
+ sys.exit(2)
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: cmd-op-sdk
3
+ Version: 1.3.2
4
+ Summary: Thin Python SDK for the cmd_op resident pipe — forwards cmd_op commands to a running resident, no per-command process spawn. The same CLI is an MCP server for AI agents.
5
+ Author: karlmoriaty
6
+ Maintainer: karlmoriaty
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/karlmoriaty/office-command-operate
9
+ Project-URL: Repository, https://github.com/karlmoriaty/office-command-operate
10
+ Keywords: cmd_op,office,docx,xlsx,pptx,ooxml,mcp,ai-agents,office-automation
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Operating System :: Microsoft :: Windows
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+
17
+ # cmd_op — Python SDK
18
+
19
+ A **thin** Python SDK for the [cmd_op](https://github.com/karlmoriaty/office-command-operate) **resident pipe**. It does one
20
+ thing: forward a cmd_op command to a running resident over its named pipe and
21
+ hand back the response — no per-command process spawn, so a loop of edits is
22
+ ~hundreds of times faster than shelling out to the CLI per command.
23
+
24
+ "Thin" is the point: there is **no second vocabulary** to learn. A command is the
25
+ same dict you'd put in a cmd_op `batch` list; the SDK just carries it over the
26
+ pipe. Anything a `doc.set_cell(...)` / `doc.add_paragraph(...)` method would do is
27
+ **fully supported** — you just spell it `doc.send({"command": "set", ...})`, with
28
+ the exact same effect. One uniform verb instead of dozens of per-element named
29
+ methods: same power, nothing extra to memorize, and new cmd_op features work
30
+ the day they ship without an SDK update.
31
+
32
+ ## The cmd_op CLI (auto-installed if missing)
33
+
34
+ `pip install cmd-op-sdk` installs **only this SDK** (the Python library); the
35
+ real work is done by the `cmd_op` binary. You don't have to install it
36
+ yourself — if `cmd_op` isn't found on your `PATH` (or in the default install
37
+ location), the SDK **provisions it on first use**: it runs cmd_op's official
38
+ installer (`install.sh` on Linux, `install.ps1` on Windows), fetched
39
+ straight from the repository. A one-line notice is
40
+ printed before it installs — it never does so silently. Pass `auto_install=False`
41
+ to `open()`/`create()` to disable this and require a pre-installed CLI instead.
42
+
43
+ To install the CLI ahead of time (or to control where it lands):
44
+
45
+ ```bash
46
+ python -m cmd_op install # runs cmd_op's official installer
47
+ # …or directly:
48
+ curl -fsSL https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.sh | bash
49
+ # Windows (PowerShell):
50
+ irm https://raw.githubusercontent.com/karlmoriaty/office-command-operate/main/install.ps1 | iex
51
+ ```
52
+
53
+ `cmd_op.install()` does the same from Python. If the CLI can't be found or
54
+ installed, the SDK raises a clear error pointing here (never a cryptic
55
+ `FileNotFoundError`).
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install cmd-op-sdk # once published — note: import name is `cmd_op`
61
+ # or, from a checkout of this repo:
62
+ pip install ./sdk/python
63
+ ```
64
+
65
+ The pip/distribution name is `cmd-op-sdk`, but you `import cmd_op`
66
+ (distribution name ≠ import name, like `pip install pillow` → `import PIL`).
67
+
68
+ Zero third-party dependencies (standard library only).
69
+
70
+ ## Quickstart
71
+
72
+ ```python
73
+ import cmd_op
74
+
75
+ # create() makes a new file and returns a live session handle;
76
+ # open() does the same for an existing file. Both return a Document.
77
+ with cmd_op.create("report.xlsx", "--force") as doc:
78
+ doc.send({"command": "set", "path": "/Sheet1/A1",
79
+ "props": {"text": "Region", "bold": "true"}})
80
+ doc.send({"command": "set", "path": "/Sheet1/B1", "props": {"formula": "=SUM(B2:B9)"}})
81
+
82
+ # read one back (returns the parsed JSON envelope)
83
+ node = doc.send({"command": "get", "path": "/Sheet1/A1"})
84
+ print(node["data"]["results"][0]["text"]) # -> Region
85
+
86
+ # many edits in ONE pipe round-trip
87
+ doc.batch([
88
+ {"command": "set", "path": "/Sheet1/A2", "props": {"text": "North"}},
89
+ {"command": "set", "path": "/Sheet1/A3", "props": {"text": "South"}},
90
+ ])
91
+
92
+ doc.send({"command": "save"})
93
+ # leaving `with` closes the resident (which flushes to disk)
94
+
95
+ # borrow an already-running resident without owning it: skip `with`/close()
96
+ d = cmd_op.open("report.xlsx")
97
+ print(d.send({"command": "view", "mode": "stats"}, as_json=False))
98
+ ```
99
+
100
+ See `demo.py` for a fuller example.
101
+
102
+ ## The command dict
103
+
104
+ `send(item)` and `batch([item, ...])` take the cmd_op **batch-item** shape:
105
+
106
+ ```jsonc
107
+ { "command": "set", // or "op"; picks the cmd_op command
108
+ "path": "/Sheet1/A1", // every key except command/op/props is forwarded
109
+ "props": { "text": "hi" } } // verbatim as a command argument
110
+ ```
111
+
112
+ Keys are cmd_op's own batch fields (`command`/`op`, `path`, `parent`, `type`,
113
+ `index`, `after`, `before`, `to`, `selector`, `mode`, `depth`, `part`, `xpath`,
114
+ `action`, `xml`) plus a nested `props`. The client maintains no field list of its
115
+ own — run `cmd_op help` (or see the batch docs) for the full reference.
116
+
117
+ `send(..., as_json=False)` requests plain-text output (e.g. `view` / `raw` /
118
+ `dump`), mirroring the CLI's `--json` toggle.
119
+
120
+ ## Errors & resilience
121
+
122
+ - Transport/process failures raise `cmd_op.CmdOpError` (`.code` carries the
123
+ exit code). Business outcomes (e.g. `validate` failing, a bad path) are **not**
124
+ exceptions — they live in the returned envelope's `success` field, same as the
125
+ CLI's exit code.
126
+ - If the resident has gone (crash, idle-timeout, missing pipe), `send`/`batch`
127
+ transparently restart it and retry once. If it's alive but the pipe is
128
+ unresponsive (busy), they raise rather than risk racing the live resident.
129
+
130
+ ## Use it as an MCP server
131
+
132
+ The cmd_op binary that this SDK provisions is also an MCP stdio server, so
133
+ you can give Claude Code, Cursor, VS Code, LM Studio, or opencode direct
134
+ document tools without a separate package:
135
+
136
+ ```bash
137
+ cmd_op mcp claude # also: cursor, vscode, lmstudio, opencode
138
+ cmd_op mcp list
139
+ ```
140
+
141
+ The generic configuration for any MCP client:
142
+
143
+ ```json
144
+ {
145
+ "mcpServers": {
146
+ "cmd_op": {
147
+ "command": "cmd_op",
148
+ "args": ["mcp"]
149
+ }
150
+ }
151
+ }
152
+ ```
153
+
154
+ ## Versioning
155
+
156
+ This client derives the resident's pipe address from the document path the same
157
+ way cmd_op does. That derivation is the one piece coupled to cmd_op
158
+ internals, so keep the client version compatible with your installed cmd_op.
@@ -0,0 +1,7 @@
1
+ README.md
2
+ cmd_op.py
3
+ pyproject.toml
4
+ cmd_op_sdk.egg-info/PKG-INFO
5
+ cmd_op_sdk.egg-info/SOURCES.txt
6
+ cmd_op_sdk.egg-info/dependency_links.txt
7
+ cmd_op_sdk.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ cmd_op
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"] # >=77 for the PEP 639 SPDX `license` string
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ # Distribution (pip) name. NOT the import name — the module stays `cmd_op`
7
+ # (`import cmd_op`), like `pip install pillow` → `import PIL`.
8
+ name = "cmd-op-sdk"
9
+ version = "1.3.2"
10
+ description = "Thin Python SDK for the cmd_op resident pipe — forwards cmd_op commands to a running resident, no per-command process spawn. The same CLI is an MCP server for AI agents."
11
+ readme = "README.md"
12
+ requires-python = ">=3.8"
13
+ license = "Apache-2.0" # PEP 639 SPDX expression (do NOT also add a License:: classifier — PyPI rejects the combo)
14
+ authors = [{ name = "karlmoriaty" }]
15
+ maintainers = [{ name = "karlmoriaty" }]
16
+ keywords = ["cmd_op", "office", "docx", "xlsx", "pptx", "ooxml", "mcp", "ai-agents", "office-automation"]
17
+ dependencies = [] # standard library only
18
+ classifiers = [
19
+ "Programming Language :: Python :: 3",
20
+ "Operating System :: POSIX :: Linux",
21
+ "Operating System :: Microsoft :: Windows",
22
+ ]
23
+ # TODO(maintainer): add a contact email here if you want one published on PyPI.
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/karlmoriaty/office-command-operate"
27
+ Repository = "https://github.com/karlmoriaty/office-command-operate"
28
+
29
+ # IMPORTANT: this package is only the SDK. It shells out to the `cmd_op`
30
+ # CLI binary, which must be installed separately and on PATH (Homebrew, etc.).
31
+ # pip cannot install that binary for you — see README.
32
+
33
+ [tool.setuptools]
34
+ py-modules = ["cmd_op"] # single-file module: cmd_op.py
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+