@oira-oira/pi 0.0.0-stage → 0.14.0

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,3 @@
1
+ # Optional key transport only. Install into a private venv, never global Python.
2
+ mcp==2.2.0
3
+ keyring==25.7.0
@@ -0,0 +1,380 @@
1
+ """Optional local MCP transport. Secrets enter through stdin and stay in the OS vault.
2
+
3
+ Install the adjacent key-requirements.txt into a private venv. This file is
4
+ rendered for one app/environment; it never chooses a remote from user input.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ from contextlib import asynccontextmanager
10
+ import getpass
11
+ import json
12
+ import logging
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import shlex
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ from uuid import UUID
21
+ from urllib.parse import urlsplit
22
+
23
+ ORIGIN = 'https://oira-oira.com'
24
+ APP = 'pi'
25
+ ENVIRONMENT = 'production'
26
+ PLUGIN = 'oira'
27
+ LOOPBACK_HOSTS = ''.split(',')
28
+ SCHEMA = 'oira_plugin_key.v1'
29
+ DEFAULT_TIMEOUT_SECONDS = 30
30
+ CONTEXT_TIMEOUT_SECONDS = 360
31
+ CONTEXT_LONG_READ_TOOLS = frozenset({'oira_check_context', 'oira_context_check_status'})
32
+ TOOLS = frozenset({
33
+ 'oira_prepare_work_update',
34
+ 'oira_connection_status', 'oira_submit_work_update', 'oira_work_update_status',
35
+ 'oira_verify_setup',
36
+ 'oira_finish_history_import', 'oira_bind_context_session', 'oira_revoke_context_session',
37
+ 'oira_check_context', 'oira_context_check_status', 'oira_cancel_context_check',
38
+ 'oira_context_interventions', 'oira_ack_context_intervention',
39
+ })
40
+
41
+
42
+ class KeySetupError(Exception):
43
+ pass
44
+
45
+
46
+ class Parser(argparse.ArgumentParser):
47
+ def error(self, message):
48
+ # argparse's default error quotes unexpected arguments, which could
49
+ # include an accidentally supplied key. Accept secrets only on stdin.
50
+ raise KeySetupError('invalid_arguments')
51
+
52
+
53
+ def host_for(secret):
54
+ match = re.fullmatch(r'oira_k1\.([0-9a-f-]{36})\.[A-Za-z0-9_-]{43}', secret or '')
55
+ if match is None:
56
+ raise KeySetupError('installation_key_invalid')
57
+ try:
58
+ return str(UUID(match[1]))
59
+ except ValueError:
60
+ raise KeySetupError('installation_key_invalid') from None
61
+
62
+
63
+ def vault():
64
+ # Same native-only policy as oira_runtime.credentials; no plaintext backend.
65
+ try:
66
+ if sys.platform == 'darwin':
67
+ from keyring.backends.macOS import Keyring
68
+ elif sys.platform == 'win32':
69
+ from keyring.backends.Windows import WinVaultKeyring as Keyring
70
+ elif sys.platform.startswith('linux'):
71
+ from keyring.backends.SecretService import Keyring
72
+ else:
73
+ raise KeySetupError('credential_store_unavailable')
74
+ instance = Keyring()
75
+ if instance.priority <= 0:
76
+ raise KeySetupError('credential_store_unavailable')
77
+ return instance
78
+ except Exception:
79
+ raise KeySetupError('credential_store_unavailable') from None
80
+
81
+
82
+ def service():
83
+ return f'oira.plugin-key.v1:{ORIGIN}:{APP}'
84
+
85
+
86
+ def valid_environment():
87
+ parts = urlsplit(ORIGIN)
88
+ return bool(APP in {'codex', 'claude', 'kiro', 'copilot', 'cursor', 'pi', 'antigravity', 'jcode'}
89
+ and ENVIRONMENT in {'production', 'development'}
90
+ and parts.hostname and not parts.username and not parts.password
91
+ and not parts.path and not parts.query and not parts.fragment
92
+ and (parts.scheme == 'https' or ENVIRONMENT == 'development'
93
+ and parts.scheme == 'http' and parts.hostname in LOOPBACK_HOSTS))
94
+
95
+
96
+ def metadata_path():
97
+ return Path(__file__).resolve().parent.parent / 'references' / 'key-installation.json'
98
+
99
+
100
+ def read_metadata(path):
101
+ try:
102
+ if path.is_symlink() or path.stat().st_size > 4096:
103
+ raise ValueError()
104
+ value = json.loads(path.read_text(encoding='utf-8'))
105
+ if (set(value) != {'schema', 'origin', 'app', 'host_uuid'}
106
+ or value['schema'] != SCHEMA or value['origin'] != ORIGIN or value['app'] != APP
107
+ or str(UUID(value['host_uuid'])) != value['host_uuid']):
108
+ raise ValueError()
109
+ return value
110
+ except (OSError, ValueError, TypeError, KeyError):
111
+ raise KeySetupError('installation_metadata_invalid') from None
112
+
113
+
114
+ def save_secret(secret, path, store):
115
+ host = host_for(secret)
116
+ if path.is_symlink():
117
+ raise KeySetupError('installation_metadata_invalid')
118
+ if path.exists() and read_metadata(path)['host_uuid'] != host:
119
+ raise KeySetupError('installation_owner_conflict')
120
+ try:
121
+ store.set_password(service(), host, secret)
122
+ if store.get_password(service(), host) != secret:
123
+ raise KeySetupError('credential_store_unavailable')
124
+ except Exception:
125
+ raise KeySetupError('credential_store_unavailable') from None
126
+ # Only nonsecret installation identity is written to disk. A failed metadata
127
+ # write can be retried with the same key; it must not issue a new credential.
128
+ path.parent.mkdir(parents=True, exist_ok=True)
129
+ value = {'schema': SCHEMA, 'origin': ORIGIN, 'app': APP, 'host_uuid': host}
130
+ fd, temporary = tempfile.mkstemp(prefix='.oira-key-', dir=path.parent)
131
+ try:
132
+ with os.fdopen(fd, 'w', encoding='utf-8') as file:
133
+ json.dump(value, file)
134
+ os.replace(temporary, path)
135
+ finally:
136
+ if os.path.exists(temporary):
137
+ os.unlink(temporary)
138
+ return value
139
+
140
+
141
+ def load_secret(path, store):
142
+ value = read_metadata(path)
143
+ try:
144
+ secret = store.get_password(service(), value['host_uuid'])
145
+ if host_for(secret) != value['host_uuid']:
146
+ raise KeySetupError('authentication_required')
147
+ return secret
148
+ except Exception:
149
+ raise KeySetupError('authentication_required') from None
150
+
151
+
152
+ def prepare_plugin():
153
+ """Keep the complete native plugin; replace only its transport and interpreter.
154
+
155
+ Run from a private, persistent copy of the official package before native
156
+ installation. No vault access, host settings, hook trust or project grants.
157
+ """
158
+ if APP not in {'codex', 'claude'}:
159
+ raise KeySetupError('native_key_plugin_unsupported')
160
+ root = Path(__file__).resolve().parents[3]
161
+ name = PLUGIN
162
+ manifest = root / ('.codex-plugin' if APP == 'codex' else '.claude-plugin') / 'plugin.json'
163
+ package = json.loads(manifest.read_text(encoding='utf-8'))
164
+ if root.name != name or package.get('name') != name:
165
+ raise KeySetupError('complete_plugin_required')
166
+ version = package.get('version')
167
+ if not isinstance(version, str) or len(version) > 100 or not re.fullmatch(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?', version):
168
+ raise KeySetupError('package_version_invalid')
169
+ python = Path(sys.executable).absolute()
170
+ if python.parent.resolve().is_relative_to(root):
171
+ # A host copies the plugin into its cache. Never copy a whole venv or
172
+ # depend on its relocated executable/shebangs.
173
+ raise KeySetupError('venv_must_be_outside_plugin')
174
+ wrapper = root / 'hooks/reporting_hook.py'
175
+ def plain_path(path):
176
+ return not any(part.is_symlink() for part in (path, *path.parents) if part.is_relative_to(root.parent))
177
+
178
+ for required in (wrapper, root / 'hooks/oira_hooks.py', root / 'hooks/oira_local.py'):
179
+ if not plain_path(required) or not required.is_file():
180
+ raise KeySetupError('complete_plugin_required')
181
+ mcp = root / '.mcp.json'
182
+ hooks = root / 'hooks/hooks.json'
183
+ descriptor = metadata_path().with_name('key-plugin.json')
184
+ market = root.parent / ('.agents/plugins/marketplace.json' if APP == 'codex' else '.claude-plugin/marketplace.json')
185
+ source_server = 'oira' if APP == 'claude' else name
186
+ expected_mcp = {'mcpServers': {source_server: {'type': 'http', 'url': ORIGIN + '/mcp'}}}
187
+ variable = 'PLUGIN_ROOT' if APP == 'codex' else 'CLAUDE_PLUGIN_ROOT'
188
+ original_command = 'python3 "${' + variable + '}/hooks/reporting_hook.py" --app ' + APP + ' --environment ' + ENVIRONMENT + ' event'
189
+ original_hooks = {'hooks': {event: [{'hooks': [{'type': 'command', 'command': original_command, 'timeout': 5}]}]
190
+ for event in ('SessionStart', 'UserPromptSubmit', 'Stop')}}
191
+ argv = [str(python), str(wrapper), '--app', APP, '--environment', ENVIRONMENT, 'event']
192
+ command = subprocess.list2cmdline(argv) if os.name == 'nt' else shlex.join(argv)
193
+ prepared_hooks = {'hooks': {event: [{'hooks': [{'type': 'command', 'command': command, 'timeout': 5}]}]
194
+ for event in original_hooks['hooks']}}
195
+ prepared_mcp = {'mcpServers': {name + '-key': {'command': str(python), 'args': [str(Path(__file__).resolve()), 'serve']}}}
196
+ info = {'schema': 'oira_key_plugin.v1', 'app': APP, 'environment': ENVIRONMENT,
197
+ 'origin': ORIGIN, 'plugin_root': str(root), 'python': str(python)}
198
+ previous_info = dict(info)
199
+ info['package_version'] = version
200
+ entry = {'name': name, 'source': {'source': 'local', 'path': './' + name},
201
+ 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Productivity'}
202
+ if APP == 'claude':
203
+ entry = {'name': name, 'source': './' + name}
204
+ marketplace = {'name': name + '-key', 'plugins': [entry]}
205
+ if APP == 'claude':
206
+ marketplace['owner'] = {'name': 'Oira-Oira'}
207
+ changes = ((mcp, expected_mcp, prepared_mcp), (hooks, original_hooks, prepared_hooks),
208
+ (descriptor, previous_info, info), (market, None, marketplace))
209
+ # Validate every file before any write. Repeated preparation is idempotent;
210
+ # foreign edits or another app/environment are a repair, never overwritten.
211
+ for path, original, prepared in changes:
212
+ if not plain_path(path):
213
+ raise KeySetupError('plugin_configuration_conflict')
214
+ if path.exists():
215
+ current = json.loads(path.read_text(encoding='utf-8'))
216
+ if path == descriptor and isinstance(current, dict) and current != prepared:
217
+ prior = dict(current)
218
+ old_version = prior.pop('package_version', None)
219
+ if prior == previous_info and (old_version is None or isinstance(old_version, str)
220
+ and len(old_version) <= 100 and re.fullmatch(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?', old_version)):
221
+ current = previous_info
222
+ if current != prepared and (original is None or current != original):
223
+ raise KeySetupError('plugin_configuration_conflict')
224
+ for path, _, prepared in changes:
225
+ path.parent.mkdir(parents=True, exist_ok=True)
226
+ fd, temporary = tempfile.mkstemp(prefix='.oira-config-', dir=path.parent)
227
+ try:
228
+ with os.fdopen(fd, 'w', encoding='utf-8') as file:
229
+ json.dump(prepared, file, indent=2)
230
+ file.write('\n')
231
+ os.replace(temporary, path)
232
+ finally:
233
+ if os.path.exists(temporary):
234
+ os.unlink(temporary)
235
+ return {'prepared': True, **info, 'marketplace': name + '-key',
236
+ 'marketplace_root': str(root.parent), 'native_installation': 'required',
237
+ 'hook_trust': 'required' if APP == 'codex' else 'host_managed'}
238
+
239
+
240
+ @asynccontextmanager
241
+ async def remote_session(secret, *, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
242
+ import httpx2
243
+ from mcp import ClientSession
244
+ from mcp.client.streamable_http import streamable_http_client
245
+ async with httpx2.AsyncClient(headers={'Authorization': 'Bearer ' + secret},
246
+ timeout=timeout_seconds, follow_redirects=False) as http:
247
+ async with streamable_http_client(ORIGIN + '/mcp', http_client=http) as streams:
248
+ async with ClientSession(streams[0], streams[1], read_timeout_seconds=timeout_seconds) as remote:
249
+ await remote.initialize()
250
+ yield remote
251
+
252
+
253
+ async def login(secret):
254
+ host = host_for(secret)
255
+ async with remote_session(secret) as remote:
256
+ result = await remote.call_tool('oira_connection_status')
257
+ status = result.structured_content
258
+ if status is None:
259
+ texts = [block.text for block in result.content if getattr(block, 'type', '') == 'text']
260
+ status = json.loads(texts[0]) if len(texts) == 1 else {}
261
+ if result.is_error or status.get('host_authorization_uuid') != host:
262
+ raise KeySetupError('installation_authentication_failed')
263
+ return save_secret(secret, metadata_path(), vault())
264
+
265
+
266
+ def make_server(session_factory):
267
+ from mcp.server import Server
268
+ from mcp.types import CallToolResult, TextContent
269
+
270
+ async def list_tools(context, params):
271
+ try:
272
+ async with session_factory() as remote:
273
+ result = await remote.list_tools()
274
+ except Exception:
275
+ # An outage is not a successful discovery of zero capabilities.
276
+ # Keep the local server alive so discovery can be tried again.
277
+ from mcp.shared.exceptions import MCPError
278
+ from mcp.types import INTERNAL_ERROR
279
+ raise MCPError(INTERNAL_ERROR, 'oira_transport_unavailable') from None
280
+ # A bounded allowlist prevents an unrelated remote tool becoming part
281
+ # of this integration. Preserve the server's canonical DTOs unchanged.
282
+ result.tools = [tool for tool in result.tools if tool.name in TOOLS]
283
+ result.next_cursor = None
284
+ return result
285
+
286
+ async def call_tool(context, params):
287
+ if params.name not in TOOLS:
288
+ return CallToolResult(is_error=True, content=[TextContent(type='text', text='operation_unavailable')])
289
+ try:
290
+ # Deployments and idle HTTP expiry can close the upstream stream.
291
+ # Each operation owns its connection in this task, including its
292
+ # cleanup; no dead session or cross-task anyio cancel scope is kept.
293
+ # Never replay a mutation on failure: its response may be lost
294
+ # after capture. The caller recovers the same update_ref by status.
295
+ timeout = (CONTEXT_TIMEOUT_SECONDS if params.name in CONTEXT_LONG_READ_TOOLS
296
+ else DEFAULT_TIMEOUT_SECONDS)
297
+ async with session_factory(timeout_seconds=timeout) as remote:
298
+ return await remote.call_tool(params.name, params.arguments or {})
299
+ except Exception:
300
+ # Transport exceptions may contain headers/URLs/input. Never put
301
+ # their repr or traceback into model-visible tool output.
302
+ return CallToolResult(is_error=True, content=[TextContent(type='text', text='oira_transport_unavailable')])
303
+
304
+ setup_guidance = (
305
+ 'For setup, follow the setup-verification reference, wait for hook review and verify real local '
306
+ 'execution where applicable, then use oira_verify_setup for a non-work acknowledgment. '
307
+ 'Persist setup sessions\' exact exclusion through the installed hook helper before enabling reports. '
308
+ if APP in {'codex', 'claude'} else
309
+ 'This host has no qualified automatic hooks or history import. Do not install hook helpers or '
310
+ 'enable those capabilities. Use oira_verify_setup for a non-work acknowledgment. '
311
+ )
312
+ return Server('oira-key', instructions=(
313
+ 'Use the installed Oira skill and this vault-backed transport. Check oira_connection_status first; '
314
+ 'freeze an explicitly approved oira_coding_target.v1 expected_target and pass it on every operation. '
315
+ 'Report material work facts only within the user\'s saved reporting choice, through canonical local '
316
+ 'preflight and stable update-ref/status recovery. Never send transcripts, prompts, tool output, files '
317
+ 'or credentials. With separate company-context consent and available context tools, consult Oira '
318
+ 'for accepted decisions, constraints and related work before making unsupported assumptions. '
319
+ 'Context reads and history import are separate from reporting. If a capability is not exposed, '
320
+ 'report it as unavailable; do not substitute OAuth or invent a result. ' + setup_guidance +
321
+ 'Never invent a work update. '
322
+ 'Setup/verification chats are excluded from work and history import, even after setup finishes. '
323
+ 'A working chat first observed midrun declares work/context before its real progress/results; '
324
+ 'never manufacture a native start or send empty setup/start work. '
325
+ 'A key, project grant or saved binding does not override native approval to disclose work. '
326
+ 'On an approval refusal stop, explain it and wait for explicit human approval; never minimize, '
327
+ 'reword or switch transport to bypass it. A setup acknowledgment is not permission or a real work receipt.'
328
+ ), on_list_tools=list_tools, on_call_tool=call_tool)
329
+
330
+
331
+ async def serve():
332
+ from mcp.server.stdio import stdio_server
333
+ secret = load_secret(metadata_path(), vault())
334
+ server = make_server(lambda **kwargs: remote_session(secret, **kwargs))
335
+ async with stdio_server() as (read, write):
336
+ await server.run(read, write, server.create_initialization_options())
337
+
338
+
339
+ def main():
340
+ parser = Parser(description=__doc__)
341
+ parser.add_argument('action', choices=('login', 'serve', 'forget-local', 'prepare-plugin'))
342
+ parser.add_argument('--stdin', action='store_true')
343
+ # SDK/HTTP debug logging must not expose credentials or request bodies.
344
+ logging.disable(logging.CRITICAL)
345
+ try:
346
+ args = parser.parse_args()
347
+ if not valid_environment():
348
+ raise KeySetupError('unrendered_package')
349
+ if args.action == 'prepare-plugin':
350
+ print(json.dumps(prepare_plugin()))
351
+ elif args.action == 'login':
352
+ if not args.stdin and not sys.stdin.isatty():
353
+ raise KeySetupError('interactive_secret_input_required')
354
+ secret = (sys.stdin.readline(512).strip() if args.stdin and not sys.stdin.isatty()
355
+ else getpass.getpass('Oira installation key: '))
356
+ import anyio
357
+ result = anyio.run(login, secret)
358
+ print(json.dumps({'authenticated': True, **result}))
359
+ elif args.action == 'serve':
360
+ import anyio
361
+ anyio.run(serve)
362
+ else:
363
+ path = metadata_path()
364
+ value = read_metadata(path)
365
+ store = vault()
366
+ if store.get_password(service(), value['host_uuid']):
367
+ store.delete_password(service(), value['host_uuid'])
368
+ path.unlink()
369
+ print('{"local_credential_removed":true,"server_revocation":"unchanged"}')
370
+ return 0
371
+ except KeyboardInterrupt:
372
+ return 130
373
+ except Exception as exc:
374
+ code = str(exc) if isinstance(exc, KeySetupError) else 'key_setup_unavailable'
375
+ print(json.dumps({'ok': False, 'error': code}), file=sys.stderr)
376
+ return 1
377
+
378
+
379
+ if __name__ == '__main__':
380
+ raise SystemExit(main())