pidriver 0.1.0__tar.gz → 0.2.0__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.
Files changed (69) hide show
  1. {pidriver-0.1.0 → pidriver-0.2.0}/PKG-INFO +53 -1
  2. {pidriver-0.1.0 → pidriver-0.2.0}/README.md +52 -0
  3. {pidriver-0.1.0 → pidriver-0.2.0}/pyproject.toml +6 -1
  4. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/__init__.py +49 -5
  5. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/_install.py +104 -1
  6. pidriver-0.2.0/src/pidriver/assets/pi_login.mjs +115 -0
  7. pidriver-0.2.0/src/pidriver/auth.py +254 -0
  8. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/config.py +14 -1
  9. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/errors.py +10 -0
  10. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/events.py +43 -0
  11. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/interaction.py +18 -1
  12. pidriver-0.2.0/src/pidriver/models.py +160 -0
  13. pidriver-0.2.0/src/pidriver/workspace.py +108 -0
  14. pidriver-0.2.0/tests/test_auth.py +81 -0
  15. pidriver-0.2.0/tests/test_event_summary.py +56 -0
  16. pidriver-0.2.0/tests/test_install_resolve.py +62 -0
  17. pidriver-0.2.0/tests/test_models.py +96 -0
  18. pidriver-0.2.0/tests/test_workspace.py +80 -0
  19. {pidriver-0.1.0 → pidriver-0.2.0}/.gitignore +0 -0
  20. {pidriver-0.1.0 → pidriver-0.2.0}/.sc/last-chat-settings.json +0 -0
  21. {pidriver-0.1.0 → pidriver-0.2.0}/LICENSE +0 -0
  22. {pidriver-0.1.0 → pidriver-0.2.0}/examples/basic_prompt.py +0 -0
  23. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/_transport.py +0 -0
  24. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/client.py +0 -0
  25. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/manager.py +0 -0
  26. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/py.typed +0 -0
  27. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/session.py +0 -0
  28. {pidriver-0.1.0 → pidriver-0.2.0}/src/pidriver/usage.py +0 -0
  29. {pidriver-0.1.0 → pidriver-0.2.0}/tests/conftest.py +0 -0
  30. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/README.md +0 -0
  31. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/_capture_driver.py +0 -0
  32. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/agent_end.json +0 -0
  33. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/agent_start.json +0 -0
  34. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_request.confirm.json +0 -0
  35. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_request.editor.json +0 -0
  36. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_request.input.json +0 -0
  37. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_request.select.approval.json +0 -0
  38. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_request.select.ask.json +0 -0
  39. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_request.setWidget.json +0 -0
  40. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_response.approve.json +0 -0
  41. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_response.confirm.json +0 -0
  42. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_response.editor.json +0 -0
  43. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_response.input.json +0 -0
  44. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/extension_ui_response.value.json +0 -0
  45. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/message_start_assistant.json +0 -0
  46. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/message_start_user.json +0 -0
  47. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/message_update.text_delta.json +0 -0
  48. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/message_update.thinking_delta.json +0 -0
  49. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/message_update.toolcall_end.json +0 -0
  50. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/message_update.toolcall_start.json +0 -0
  51. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/ready.json +0 -0
  52. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/response_prompt_ack.json +0 -0
  53. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/tool_execution_end.json +0 -0
  54. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/tool_execution_start.json +0 -0
  55. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/tool_execution_update.json +0 -0
  56. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/turn_end.json +0 -0
  57. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/frames/turn_start.json +0 -0
  58. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/payloads/get_session_stats.response.json +0 -0
  59. {pidriver-0.1.0 → pidriver-0.2.0}/tests/fixtures/payloads/get_state.response.json +0 -0
  60. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_config.py +0 -0
  61. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_events.py +0 -0
  62. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_fixtures_replay.py +0 -0
  63. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_install.py +0 -0
  64. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_manager.py +0 -0
  65. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_replay_session.py +0 -0
  66. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_session.py +0 -0
  67. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_transport.py +0 -0
  68. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_ui_methods.py +0 -0
  69. {pidriver-0.1.0 → pidriver-0.2.0}/tests/test_usage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pidriver
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Async Python driver for the pi coding agent (pi --mode rpc), built for isolated, headless project work.
5
5
  Project-URL: Homepage, https://github.com/bobuk/pidriver
6
6
  Project-URL: Repository, https://github.com/bobuk/pidriver
@@ -522,6 +522,58 @@ handler = chain(
522
522
  )
523
523
  ```
524
524
 
525
+ ## Workspace jail
526
+
527
+ Run an agent loose inside a project without letting it run anywhere on disk. `resolve_project`
528
+ maps a user-supplied *name* to a real directory only if it is explicitly allow-listed and lives
529
+ physically under `root` — rejecting path separators and symlink escapes.
530
+
531
+ ```python
532
+ from pidriver import resolve_project, list_candidate_projects, ProjectError
533
+
534
+ try:
535
+ cwd = resolve_project("myrepo", root=PROJECTS_ROOT, allowlist=("myrepo", "docs"))
536
+ except ProjectError as exc:
537
+ ... # empty / not allow-listed / not a dir / escapes root (incl. via symlink)
538
+
539
+ # Offer a picker: every immediate sub-dir of a root, flagged git / selected.
540
+ projects = list_candidate_projects(PROJECTS_ROOT, allowlist=("myrepo",)) # list[ProjectDir]
541
+ ```
542
+
543
+ ## Model discovery
544
+
545
+ `list_models` runs `pi --list-models` under the same isolation env the agent uses and parses the
546
+ table into typed `ModelInfo` rows; `parse_models` is the pure parser (handy for tests / cached
547
+ output). When a provider is set the result is narrowed to it.
548
+
549
+ ```python
550
+ from pidriver import list_models, parse_models
551
+
552
+ models = await list_models(config, provider="anthropic") # list[ModelInfo]
553
+ for m in models:
554
+ print(m.id, m.context) # "anthropic/claude-opus-4-8" "200K"
555
+ ```
556
+
557
+ ## Provider OAuth login
558
+
559
+ Some providers authenticate via OAuth (Claude Pro/Max, Codex, …) instead of an API key. `PiOAuthLogin`
560
+ drives a bundled Node helper that reuses pi's own `AuthStorage` (no version skew), writing
561
+ credentials into the isolated `<agent_dir>/auth.json`. Requires `node` on PATH and a resolvable pi
562
+ install.
563
+
564
+ ```python
565
+ from pidriver import PiOAuthLogin
566
+
567
+ login = PiOAuthLogin(config) # config.agent_dir receives auth.json
568
+ info = await login.start("anthropic") # {"session", "url", "instructions"}
569
+ # user opens info["url"], authorizes, copies the code:
570
+ await login.submit_code(info["session"], code) # accepts a bare code or a callback URL
571
+ ```
572
+
573
+ `valid_extension_source(src)` validates a `pi install` argument, and `resolve_node_modules(config)`
574
+ locates pi's bundled Node libraries (package identity from `config.npm_package`, so the omp fork
575
+ works too) — both exported for hosts building their own extension/auth tooling.
576
+
525
577
  ## Development
526
578
 
527
579
  ```sh
@@ -498,6 +498,58 @@ handler = chain(
498
498
  )
499
499
  ```
500
500
 
501
+ ## Workspace jail
502
+
503
+ Run an agent loose inside a project without letting it run anywhere on disk. `resolve_project`
504
+ maps a user-supplied *name* to a real directory only if it is explicitly allow-listed and lives
505
+ physically under `root` — rejecting path separators and symlink escapes.
506
+
507
+ ```python
508
+ from pidriver import resolve_project, list_candidate_projects, ProjectError
509
+
510
+ try:
511
+ cwd = resolve_project("myrepo", root=PROJECTS_ROOT, allowlist=("myrepo", "docs"))
512
+ except ProjectError as exc:
513
+ ... # empty / not allow-listed / not a dir / escapes root (incl. via symlink)
514
+
515
+ # Offer a picker: every immediate sub-dir of a root, flagged git / selected.
516
+ projects = list_candidate_projects(PROJECTS_ROOT, allowlist=("myrepo",)) # list[ProjectDir]
517
+ ```
518
+
519
+ ## Model discovery
520
+
521
+ `list_models` runs `pi --list-models` under the same isolation env the agent uses and parses the
522
+ table into typed `ModelInfo` rows; `parse_models` is the pure parser (handy for tests / cached
523
+ output). When a provider is set the result is narrowed to it.
524
+
525
+ ```python
526
+ from pidriver import list_models, parse_models
527
+
528
+ models = await list_models(config, provider="anthropic") # list[ModelInfo]
529
+ for m in models:
530
+ print(m.id, m.context) # "anthropic/claude-opus-4-8" "200K"
531
+ ```
532
+
533
+ ## Provider OAuth login
534
+
535
+ Some providers authenticate via OAuth (Claude Pro/Max, Codex, …) instead of an API key. `PiOAuthLogin`
536
+ drives a bundled Node helper that reuses pi's own `AuthStorage` (no version skew), writing
537
+ credentials into the isolated `<agent_dir>/auth.json`. Requires `node` on PATH and a resolvable pi
538
+ install.
539
+
540
+ ```python
541
+ from pidriver import PiOAuthLogin
542
+
543
+ login = PiOAuthLogin(config) # config.agent_dir receives auth.json
544
+ info = await login.start("anthropic") # {"session", "url", "instructions"}
545
+ # user opens info["url"], authorizes, copies the code:
546
+ await login.submit_code(info["session"], code) # accepts a bare code or a callback URL
547
+ ```
548
+
549
+ `valid_extension_source(src)` validates a `pi install` argument, and `resolve_node_modules(config)`
550
+ locates pi's bundled Node libraries (package identity from `config.npm_package`, so the omp fork
551
+ works too) — both exported for hosts building their own extension/auth tooling.
552
+
501
553
  ## Development
502
554
 
503
555
  ```sh
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pidriver"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Async Python driver for the pi coding agent (pi --mode rpc), built for isolated, headless project work."
5
5
  readme = "README.md"
6
6
  license = { text = "MIT" }
@@ -36,6 +36,11 @@ build-backend = "hatchling.build"
36
36
  [tool.hatch.build.targets.wheel]
37
37
  packages = ["src/pidriver"]
38
38
 
39
+ # Ship the Node OAuth helper (pidriver.auth loads it via importlib.resources). Explicit
40
+ # so the data file lands in the wheel regardless of default file selection.
41
+ [tool.hatch.build.targets.wheel.force-include]
42
+ "src/pidriver/assets/pi_login.mjs" = "pidriver/assets/pi_login.mjs"
43
+
39
44
  [tool.pytest.ini_options]
40
45
  asyncio_mode = "auto"
41
46
  testpaths = ["tests"]
@@ -9,11 +9,16 @@ Layers:
9
9
  * :mod:`pidriver.config` — :class:`PiConfig` (isolation knobs, ``to_argv``/``to_env``).
10
10
  * :mod:`pidriver._transport` — :class:`PiTransport` protocol + :class:`SubprocessTransport`
11
11
  (the swap boundary).
12
- * :mod:`pidriver.events` — the typed :class:`Event` hierarchy + :func:`parse_event`.
13
- * :mod:`pidriver.interaction` — answering the agent's questions (handlers + policies).
12
+ * :mod:`pidriver.events` — the typed :class:`Event` hierarchy + :func:`parse_event`, plus
13
+ :func:`event_summary` (event → human line) and :func:`is_freetext_option`.
14
+ * :mod:`pidriver.interaction` — answering the agent's questions (handlers + policies),
15
+ plus the opt-in :data:`ASK_FIRST_SYSTEM_PROMPT`.
14
16
  * :mod:`pidriver.session` — :class:`PiSession` (the live RPC session).
15
17
  * :mod:`pidriver.client` — :class:`PiClient` (start sessions).
16
18
  * :mod:`pidriver.manager` — :class:`PiSessionManager` (registry, idle reaper, ``stop_all``).
19
+ * :mod:`pidriver.workspace` — :func:`resolve_project` (the project jail) + project listing.
20
+ * :mod:`pidriver.models` — :func:`list_models` / :func:`parse_models` (model discovery).
21
+ * :mod:`pidriver.auth` — :class:`PiOAuthLogin` (provider OAuth via pi's own AuthStorage).
17
22
  * :mod:`pidriver.usage` — :class:`UsageTotals`.
18
23
  * :mod:`pidriver.errors` — exception hierarchy.
19
24
 
@@ -34,10 +39,22 @@ Quick start::
34
39
 
35
40
  from __future__ import annotations
36
41
 
37
- from ._install import ensure_binary, ensure_extensions, install_pi
42
+ from ._install import (
43
+ ensure_binary,
44
+ ensure_extensions,
45
+ install_pi,
46
+ resolve_node_modules,
47
+ valid_extension_source,
48
+ )
38
49
  from ._transport import PiTransport, SubprocessTransport
50
+ from .auth import PiOAuthLogin, auth_context, extract_oauth_code
39
51
  from .client import PiClient, TransportFactory
40
- from .config import PROVIDER_API_KEY_ENV, PiConfig
52
+ from .config import (
53
+ PI_CLAUDE_CLI_EXTENSION,
54
+ PI_CLAUDE_CLI_PROVIDER,
55
+ PROVIDER_API_KEY_ENV,
56
+ PiConfig,
57
+ )
41
58
  from .errors import (
42
59
  PiCommandError,
43
60
  PiDriverError,
@@ -46,6 +63,7 @@ from .errors import (
46
63
  PiProtocolError,
47
64
  PiStartError,
48
65
  PiTimeoutError,
66
+ ProjectError,
49
67
  SessionNotFoundError,
50
68
  TransportClosedError,
51
69
  )
@@ -64,9 +82,12 @@ from .events import (
64
82
  ToolStart,
65
83
  ToolUpdate,
66
84
  Usage,
85
+ event_summary,
86
+ is_freetext_option,
67
87
  parse_event,
68
88
  )
69
89
  from .interaction import (
90
+ ASK_FIRST_SYSTEM_PROMPT,
70
91
  AskHost,
71
92
  AutoApprove,
72
93
  DenyAll,
@@ -76,16 +97,20 @@ from .interaction import (
76
97
  response_to_wire,
77
98
  )
78
99
  from .manager import ManagedSession, PiSessionManager
100
+ from .models import ModelInfo, list_models, parse_models
79
101
  from .session import PiSession
80
102
  from .usage import UsageTotals
103
+ from .workspace import ProjectDir, list_candidate_projects, list_projects, resolve_project
81
104
 
82
- __version__ = "0.1.0"
105
+ __version__ = "0.2.0"
83
106
 
84
107
  __all__ = [
85
108
  "__version__",
86
109
  # config
87
110
  "PiConfig",
88
111
  "PROVIDER_API_KEY_ENV",
112
+ "PI_CLAUDE_CLI_PROVIDER",
113
+ "PI_CLAUDE_CLI_EXTENSION",
89
114
  # transport
90
115
  "PiTransport",
91
116
  "SubprocessTransport",
@@ -93,6 +118,8 @@ __all__ = [
93
118
  "ensure_binary",
94
119
  "ensure_extensions",
95
120
  "install_pi",
121
+ "valid_extension_source",
122
+ "resolve_node_modules",
96
123
  # client / session
97
124
  "PiClient",
98
125
  "TransportFactory",
@@ -115,6 +142,8 @@ __all__ = [
115
142
  "Error",
116
143
  "Channel",
117
144
  "parse_event",
145
+ "event_summary",
146
+ "is_freetext_option",
118
147
  # interaction
119
148
  "InteractionRequest",
120
149
  "InteractionKind",
@@ -126,6 +155,20 @@ __all__ = [
126
155
  "DenyAll",
127
156
  "chain",
128
157
  "response_to_wire",
158
+ "ASK_FIRST_SYSTEM_PROMPT",
159
+ # workspace
160
+ "resolve_project",
161
+ "list_projects",
162
+ "list_candidate_projects",
163
+ "ProjectDir",
164
+ # models
165
+ "ModelInfo",
166
+ "parse_models",
167
+ "list_models",
168
+ # auth
169
+ "PiOAuthLogin",
170
+ "auth_context",
171
+ "extract_oauth_code",
129
172
  # errors
130
173
  "PiDriverError",
131
174
  "PiNotFoundError",
@@ -136,4 +179,5 @@ __all__ = [
136
179
  "PiTimeoutError",
137
180
  "TransportClosedError",
138
181
  "SessionNotFoundError",
182
+ "ProjectError",
139
183
  ]
@@ -27,7 +27,14 @@ from pathlib import Path
27
27
  from .config import PiConfig
28
28
  from .errors import PiInstallError, PiNotFoundError
29
29
 
30
- __all__ = ["ensure_binary", "ensure_extensions", "install_pi", "managed_binary_path"]
30
+ __all__ = [
31
+ "ensure_binary",
32
+ "ensure_extensions",
33
+ "install_pi",
34
+ "managed_binary_path",
35
+ "valid_extension_source",
36
+ "resolve_node_modules",
37
+ ]
31
38
 
32
39
  log = logging.getLogger(__name__)
33
40
 
@@ -200,3 +207,99 @@ def ensure_extensions(
200
207
  log.warning("pi: `pi install %s` failed (exit %s): %s", source, result.returncode, tail)
201
208
  else:
202
209
  log.info("pi: installed extension %s", source)
210
+
211
+
212
+ # Remote ``pi install`` source forms; anything else must be a local path.
213
+ _EXTENSION_SOURCE_PREFIXES: tuple[str, ...] = ("npm:", "git:", "https://", "ssh://", "git@")
214
+
215
+
216
+ def valid_extension_source(source: str) -> bool:
217
+ """True if ``source`` is a usable ``pi install`` argument.
218
+
219
+ Accepts the remote forms (``npm:``, ``git:``, ``https://``, ``ssh://``,
220
+ ``git@``) and local paths (``./``, ``../``, ``/``). Blank or otherwise-shaped
221
+ strings are rejected — handy for validating operator-supplied extension lists
222
+ before they reach :func:`ensure_extensions`.
223
+ """
224
+ source = source.strip()
225
+ if not source:
226
+ return False
227
+ if source.startswith(_EXTENSION_SOURCE_PREFIXES):
228
+ return True
229
+ return source.startswith(("./", "../", "/"))
230
+
231
+
232
+ def _package_components(npm_package: str) -> tuple[str, ...]:
233
+ """Split an npm package id into node_modules path components (scope-aware)."""
234
+ return tuple(part for part in npm_package.split("/") if part)
235
+
236
+
237
+ def _find_package_node_modules(start: Path, package: tuple[str, ...]) -> Path | None:
238
+ """Walk up from ``start``, returning the first node_modules tree holding ``package``."""
239
+ for candidate in (start, *start.parents):
240
+ if candidate.name == "node_modules" and candidate.joinpath(*package).exists():
241
+ return candidate
242
+ node_modules = candidate / "node_modules"
243
+ if node_modules.joinpath(*package).exists():
244
+ return node_modules
245
+ global_node_modules = candidate / "lib" / "node_modules"
246
+ if global_node_modules.joinpath(*package).exists():
247
+ return global_node_modules
248
+ return None
249
+
250
+
251
+ def _resolve_mise_node_modules(
252
+ package: tuple[str, ...], tool: str, *, runner: Runner
253
+ ) -> Path | None:
254
+ """Resolve ``package``'s node_modules when pi is installed by mise and PATH is a shim."""
255
+ mise = shutil.which("mise")
256
+ if not mise:
257
+ return None
258
+ try:
259
+ result = runner(
260
+ [mise, "where", tool], capture_output=True, text=True, timeout=10
261
+ )
262
+ except (OSError, subprocess.SubprocessError):
263
+ return None
264
+ if result.returncode != 0:
265
+ return None
266
+ install_path = result.stdout.strip()
267
+ if not install_path:
268
+ return None
269
+ return _find_package_node_modules(Path(install_path).resolve(), package)
270
+
271
+
272
+ def resolve_node_modules(config: PiConfig, *, runner: Runner = subprocess.run) -> Path | None:
273
+ """Locate the node_modules tree containing the installed pi npm package.
274
+
275
+ Searches, in order: the pidriver-managed install (``<install_dir>/lib/node_modules``,
276
+ or ``<install_dir>/node_modules`` on Windows), a mise-managed install
277
+ (``mise where npm:<package>``), then a ``pi`` resolved on PATH (walking up from the
278
+ bin to its node_modules). Package identity comes from ``config.npm_package`` so this
279
+ works for the omp/oh-my-pi fork too. Returns ``None`` when no install is found.
280
+
281
+ Useful for tools that need pi's *bundled* Node libraries (e.g. its ``AuthStorage``
282
+ for the OAuth flow — see :mod:`pidriver.auth`), not just the ``pi`` executable.
283
+ """
284
+ package = _package_components(config.npm_package)
285
+ if not package:
286
+ return None
287
+
288
+ if config.install_dir is not None:
289
+ base = Path(config.install_dir)
290
+ managed = base / "node_modules" if _is_windows() else base / "lib" / "node_modules"
291
+ if managed.joinpath(*package).exists():
292
+ return managed
293
+
294
+ mise_node_modules = _resolve_mise_node_modules(
295
+ package, f"npm:{config.npm_package}", runner=runner
296
+ )
297
+ if mise_node_modules is not None:
298
+ return mise_node_modules
299
+
300
+ found = shutil.which(config.binary) or shutil.which("pi")
301
+ if found:
302
+ node_modules = _find_package_node_modules(Path(found).resolve(), package)
303
+ if node_modules is not None:
304
+ return node_modules
305
+ return None
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ // pi OAuth/login helper for pidriver (driven by pidriver.auth).
3
+ //
4
+ // Reuses pi's own AuthStorage (public export of @earendil-works/pi-coding-agent, which bundles
5
+ // the pi-ai OAuth providers — so there is no version skew and nothing extra to install). Resolve
6
+ // it by running with NODE_PATH=<pi install_dir>/lib/node_modules. Credentials are read/written at
7
+ // PI_AUTH_PATH (the isolated <agent_dir>/auth.json).
8
+ //
9
+ // Commands:
10
+ // node pi_login.mjs list -> {"providers":[{id,name}], "status":{provider:type}}
11
+ // node pi_login.mjs logout <provider> -> {"ok":true}
12
+ // node pi_login.mjs login <provider> -> JSONL events on stdout; reads the auth code from stdin
13
+ //
14
+ // login protocol (one JSON object per line on stdout):
15
+ // {"event":"auth","url":"...","instructions":"..."} # open this URL in a browser
16
+ // {"event":"need_code","message":"...","placeholder":"..."} # then write the code as one stdin line
17
+ // {"event":"progress","message":"..."}
18
+ // {"event":"done"} # credentials saved to PI_AUTH_PATH
19
+ // {"event":"error","message":"..."}
20
+
21
+ import { readFileSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import readline from "node:readline";
24
+ import { pathToFileURL } from "node:url";
25
+
26
+ function emit(o) {
27
+ process.stdout.write(JSON.stringify(o) + "\n");
28
+ }
29
+
30
+ // Import pi's bundled AuthStorage from the managed install (PI_NODE_MODULES = <install>/lib/node_modules).
31
+ // We import the package's entry by absolute path: its `exports` map only declares the ESM `import`
32
+ // condition, so require.resolve can't find it, but a direct file import resolves its nested pi-ai too.
33
+ async function loadAuthStorage() {
34
+ const nm = process.env.PI_NODE_MODULES;
35
+ if (!nm) throw new Error("PI_NODE_MODULES is not set");
36
+ const pkgDir = join(nm, "@earendil-works", "pi-coding-agent");
37
+ const pkg = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"));
38
+ const rel = pkg?.exports?.["."]?.import || pkg.main || "./dist/index.js";
39
+ const mod = await import(pathToFileURL(join(pkgDir, rel)).href);
40
+ if (!mod.AuthStorage) throw new Error("AuthStorage not exported by pi-coding-agent");
41
+ return mod.AuthStorage;
42
+ }
43
+
44
+ async function readLine() {
45
+ return await new Promise((resolve) => {
46
+ const rl = readline.createInterface({ input: process.stdin });
47
+ rl.once("line", (line) => {
48
+ rl.close();
49
+ resolve(String(line).trim());
50
+ });
51
+ });
52
+ }
53
+
54
+ function selectLoginOption(prompt) {
55
+ const options = Array.isArray(prompt?.options) ? prompt.options : [];
56
+ const selected = options.find((option) => {
57
+ const haystack = String(`${option?.id || ""} ${option?.label || ""}`).toLowerCase();
58
+ return haystack.includes("browser") || haystack.includes("default");
59
+ }) || options[0];
60
+ emit({
61
+ event: "select",
62
+ message: prompt?.message || "Select login method",
63
+ options: options.map((option) => ({ id: option.id, label: option.label })),
64
+ selected: selected?.id || "",
65
+ });
66
+ return selected?.id;
67
+ }
68
+
69
+ async function main() {
70
+ const AuthStorage = await loadAuthStorage();
71
+ const storage = AuthStorage.create(process.env.PI_AUTH_PATH);
72
+ const [cmd, providerId] = process.argv.slice(2);
73
+
74
+ if (cmd === "list") {
75
+ const providers = storage.getOAuthProviders().map((p) => ({ id: p.id, name: p.name }));
76
+ const all = storage.getAll() || {};
77
+ const status = {};
78
+ for (const [k, v] of Object.entries(all)) status[k] = v && v.type ? v.type : "unknown";
79
+ emit({ providers, status });
80
+ return;
81
+ }
82
+
83
+ if (cmd === "logout") {
84
+ if (!providerId) throw new Error("logout requires a provider id");
85
+ storage.logout(providerId);
86
+ emit({ ok: true });
87
+ return;
88
+ }
89
+
90
+ if (cmd === "login") {
91
+ if (!providerId) throw new Error("login requires a provider id");
92
+ const askCode = async (prompt) => {
93
+ emit({ event: "need_code", message: (prompt && prompt.message) || "Paste the authorization code",
94
+ placeholder: (prompt && prompt.placeholder) || "" });
95
+ return await readLine();
96
+ };
97
+ await storage.login(providerId, {
98
+ onAuth: (info) => emit({ event: "auth", url: info.url, instructions: info.instructions || "" }),
99
+ onDeviceCode: (info) => emit({ event: "device_code", ...info }),
100
+ onProgress: (m) => emit({ event: "progress", message: String(m) }),
101
+ onManualCodeInput: async () => askCode(),
102
+ onPrompt: async (prompt) => askCode(prompt),
103
+ onSelect: async (prompt) => selectLoginOption(prompt),
104
+ });
105
+ emit({ event: "done" });
106
+ return;
107
+ }
108
+
109
+ throw new Error(`unknown command: ${cmd}`);
110
+ }
111
+
112
+ main().catch((e) => {
113
+ emit({ event: "error", message: (e && e.message) || String(e) });
114
+ process.exit(1);
115
+ });