officectrl-sdk 0.1.7__py3-none-any.whl

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