taskcarry 0.3.2__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.
Files changed (105) hide show
  1. taskcarry/__init__.py +3 -0
  2. taskcarry/__main__.py +4 -0
  3. taskcarry/adapter_contracts.py +166 -0
  4. taskcarry/agy_turns.py +282 -0
  5. taskcarry/api.py +111 -0
  6. taskcarry/board.py +313 -0
  7. taskcarry/board_assets/board.css +1087 -0
  8. taskcarry/board_assets/board.js +1187 -0
  9. taskcarry/board_assets/browse.js +214 -0
  10. taskcarry/board_assets/index.html +43 -0
  11. taskcarry/board_assets/taskcarry-icon.ico +0 -0
  12. taskcarry/board_assets/taskcarry-mark.svg +28 -0
  13. taskcarry/board_data.py +466 -0
  14. taskcarry/chat_joins.py +157 -0
  15. taskcarry/cli.py +119 -0
  16. taskcarry/codex_capture.py +184 -0
  17. taskcarry/codex_host.py +293 -0
  18. taskcarry/collaboration_exchange.py +316 -0
  19. taskcarry/connection.py +159 -0
  20. taskcarry/continuity.py +300 -0
  21. taskcarry/contracts.py +165 -0
  22. taskcarry/conversation_capture.py +669 -0
  23. taskcarry/core.py +896 -0
  24. taskcarry/cycle_contracts.py +73 -0
  25. taskcarry/discovery.py +434 -0
  26. taskcarry/discovery_contracts.py +52 -0
  27. taskcarry/exchange_contracts.py +67 -0
  28. taskcarry/exchange_endpoint.py +377 -0
  29. taskcarry/exchange_packets.py +142 -0
  30. taskcarry/experience_contracts.py +129 -0
  31. taskcarry/experience_exchange.py +214 -0
  32. taskcarry/experience_notes.py +433 -0
  33. taskcarry/experience_storage.py +125 -0
  34. taskcarry/experience_tools.py +26 -0
  35. taskcarry/feishu/__init__.py +1 -0
  36. taskcarry/feishu/display.py +122 -0
  37. taskcarry/feishu/project_watch.py +145 -0
  38. taskcarry/feishu/review_sets.py +80 -0
  39. taskcarry/feishu/sender.py +42 -0
  40. taskcarry/feishu/subscription.py +193 -0
  41. taskcarry/feishu/windows_agent.py +287 -0
  42. taskcarry/feishu/windows_secret.py +34 -0
  43. taskcarry/gitops.py +170 -0
  44. taskcarry/governance.py +88 -0
  45. taskcarry/governance_cycle.py +775 -0
  46. taskcarry/identification.py +82 -0
  47. taskcarry/integration.py +663 -0
  48. taskcarry/maintenance.py +118 -0
  49. taskcarry/mcp.py +183 -0
  50. taskcarry/member_join.py +184 -0
  51. taskcarry/member_routing.py +145 -0
  52. taskcarry/onboarding.py +272 -0
  53. taskcarry/onboarding_complete.py +252 -0
  54. taskcarry/path_batches.py +19 -0
  55. taskcarry/preservation.py +257 -0
  56. taskcarry/project_collaboration.py +453 -0
  57. taskcarry/project_history.py +166 -0
  58. taskcarry/project_identity.py +51 -0
  59. taskcarry/project_recovery.py +824 -0
  60. taskcarry/recovery_contracts.py +25 -0
  61. taskcarry/recovery_files.py +153 -0
  62. taskcarry/recovery_git.py +234 -0
  63. taskcarry/remote_capture.py +89 -0
  64. taskcarry/remote_transfer.py +356 -0
  65. taskcarry/role_connection.py +215 -0
  66. taskcarry/setup.py +597 -0
  67. taskcarry/shared_workbench.py +480 -0
  68. taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
  69. taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
  70. taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
  71. taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
  72. taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
  73. taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
  74. taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
  75. taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
  76. taskcarry/source_review_set.py +80 -0
  77. taskcarry/state_format.py +47 -0
  78. taskcarry/store.py +472 -0
  79. taskcarry/task_context.py +141 -0
  80. taskcarry/text_handback.py +98 -0
  81. taskcarry/transfer_contracts.py +18 -0
  82. taskcarry/updates.py +351 -0
  83. taskcarry/workbench.py +625 -0
  84. taskcarry/workbench_contracts.py +32 -0
  85. taskcarry/workbuddy_capture.py +451 -0
  86. taskcarry/workbuddy_setup.py +212 -0
  87. taskcarry/worker_channel.py +859 -0
  88. taskcarry/worker_contracts.py +190 -0
  89. taskcarry/worker_storage.py +60 -0
  90. taskcarry/worker_tools.py +111 -0
  91. taskcarry-0.3.2.dist-info/METADATA +203 -0
  92. taskcarry-0.3.2.dist-info/RECORD +105 -0
  93. taskcarry-0.3.2.dist-info/WHEEL +5 -0
  94. taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
  95. taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
  96. taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
  97. taskcarry-0.3.2.dist-info/top_level.txt +2 -0
  98. taskcarry_https/__init__.py +1 -0
  99. taskcarry_https/consent.py +207 -0
  100. taskcarry_https/reader.py +132 -0
  101. taskcarry_https/review.py +116 -0
  102. taskcarry_https/server.py +163 -0
  103. taskcarry_https/team.py +335 -0
  104. taskcarry_https/team_host.py +109 -0
  105. taskcarry_https/web_host.py +82 -0
taskcarry/cli.py ADDED
@@ -0,0 +1,119 @@
1
+ """One JSON command interface shared with the MCP adapter."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+ import sys
8
+
9
+ ACTIONS = (
10
+ "init", "status", "agenda", "task", "checkpoint", "restore", "artifact", "experience",
11
+ "workspace", "submit", "reconcile", "adopt", "doctor", "setup", "mcp",
12
+ "upgrade", "observe", "run", "issue", "fix", "identify", "context", "governance", "connect",
13
+ "codex", "update_source", "update_check", "update_assess", "onboarding", "schedule_plan", "preserve",
14
+ "identity", "cycle", "facts", "source_scan", "workbench", "recovery", "transfer", "discovery", "endpoint", "join_worker", "member_verify", "workbuddy_chat", "board",
15
+ )
16
+ from .worker_tools import SCHEMAS as WORKER_SCHEMAS
17
+ ACTIONS += tuple(WORKER_SCHEMAS)
18
+
19
+
20
+ class ArgumentError(ValueError):
21
+ pass
22
+
23
+
24
+ class Parser(argparse.ArgumentParser):
25
+ def error(self, message):
26
+ raise ArgumentError(message)
27
+
28
+
29
+ def envelope_error(exc):
30
+ return {"ok": False, "error": {
31
+ "code": getattr(exc, "code", "INVALID_ARGUMENT" if isinstance(exc, (ValueError, TypeError)) else "INTERNAL_ERROR"),
32
+ "message": getattr(exc, "message", str(exc)),
33
+ "details": getattr(exc, "details", None),
34
+ }}
35
+
36
+
37
+ def main(argv=None):
38
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
39
+ if hasattr(stream, "reconfigure"):
40
+ stream.reconfigure(encoding="utf-8")
41
+ parser = Parser(description="TaskCarry: project-local governance")
42
+ parser.add_argument("--project", required=True, help="Explicit governance project directory")
43
+ parser.add_argument("--binding", help="Trusted member identity for a restricted endpoint")
44
+ parser.add_argument("--role", choices=['reader', 'worker', 'governor'], help="Maximum role for this endpoint")
45
+ parser.add_argument("--project-id", help="Optional expected stable project identity for a restricted endpoint")
46
+ parser.add_argument("--offline", action="store_true", help="Use a pinned local Git view/outbox instead of a live project control")
47
+ parser.add_argument("--open", dest="open_browser", action="store_true", help="Open the local board in your browser")
48
+ parser.add_argument("--view-only", action="store_true", help="Show the board without changing local reminder settings")
49
+ parser.add_argument("action", choices=ACTIONS)
50
+ source = parser.add_mutually_exclusive_group()
51
+ source.add_argument("--json", dest="arguments_json", help="Action arguments as a JSON object")
52
+ source.add_argument("--input", type=Path, help="UTF-8 JSON file containing action arguments")
53
+ try:
54
+ args = parser.parse_args(argv)
55
+ if args.action == "board":
56
+ if any((args.binding, args.role, args.project_id, args.offline, args.input, args.arguments_json is not None)):
57
+ raise ArgumentError("Open the board locally for one explicit project directory")
58
+ from .board import serve
59
+ return serve(Path(args.project), open_browser=args.open_browser, settings_enabled=not args.view_only)
60
+ if args.open_browser or args.view_only:
61
+ raise ArgumentError("--open and --view-only are board options")
62
+ if bool(args.binding) != bool(args.role) or args.project_id and not args.binding:
63
+ raise ArgumentError('--binding and --role must be supplied together; --project-id requires both')
64
+ if args.offline and args.binding:
65
+ raise ArgumentError('An offline endpoint uses its reviewed connection identity, not a caller override')
66
+ caller = None
67
+ if args.binding:
68
+ from .worker_channel import Caller
69
+ caller = Caller(args.binding, args.role, args.project_id)
70
+ if args.action == "mcp":
71
+ if args.input is not None or args.arguments_json is not None:
72
+ raise ArgumentError("MCP takes its requests on stdin, not --json or --input")
73
+ from .mcp import serve
74
+ return serve(Path(args.project), caller=caller, offline=args.offline)
75
+ text = args.arguments_json or "{}"
76
+ if args.input is not None:
77
+ if args.input.stat().st_size > 1024 * 1024:
78
+ raise ArgumentError("Input JSON exceeds the 1 MiB limit")
79
+ text = args.input.read_text(encoding="utf-8-sig")
80
+ if len(text.encode("utf-8")) > 1024 * 1024:
81
+ raise ArgumentError("Input JSON exceeds the 1 MiB limit")
82
+ arguments = json.loads(text)
83
+ if not isinstance(arguments, dict):
84
+ raise ArgumentError("Action arguments must be a JSON object")
85
+ if args.action == "join_worker":
86
+ if caller is not None or args.offline:
87
+ raise ArgumentError("Use the local working chat's directory to accept a project invitation")
88
+ from .member_join import join_workspace
89
+ if set(arguments) - {"invitation", "mode", "plan_id", "edition", "settings_scope"}:
90
+ raise ArgumentError("Choose an invitation, settings scope, edition, mode and reviewed plan_id")
91
+ result = join_workspace(Path(args.project), **arguments)
92
+ elif args.action == "member_verify":
93
+ if caller is not None or args.offline or set(arguments) != {"server", "observed"}:
94
+ raise ArgumentError("Provide the workspace connection name and its native role readback")
95
+ from .member_routing import verify_member
96
+ result = verify_member(Path(args.project), **arguments)
97
+ elif args.action == "workbuddy_chat":
98
+ if caller is not None or args.offline:
99
+ raise ArgumentError("Configure the selected local WorkBuddy conversation from its working folder")
100
+ if set(arguments) - {"mode", "server", "conversation_id", "settings_scope", "edition", "plan_id"}:
101
+ raise ArgumentError("Choose the member, native conversation, settings scope and reviewed plan")
102
+ from .workbuddy_setup import configure
103
+ result = configure(Path(args.project), **arguments)
104
+ elif args.offline:
105
+ from .exchange_contracts import offline_invoke
106
+ result = offline_invoke(Path(args.project), args.action, arguments)
107
+ elif args.action == "setup":
108
+ if caller is not None:
109
+ raise ArgumentError('Restricted endpoints cannot change client configuration')
110
+ from .setup import configure
111
+ result = configure(Path(args.project), **arguments)
112
+ else:
113
+ from .api import invoke
114
+ result = invoke(Path(args.project), args.action, arguments, caller=caller)
115
+ output, exit_code = {"ok": True, "result": result}, 0
116
+ except Exception as exc:
117
+ output, exit_code = envelope_error(exc), 1
118
+ sys.stdout.write(json.dumps(output, ensure_ascii=False) + "\n")
119
+ return exit_code
@@ -0,0 +1,184 @@
1
+ """Identify local Codex chats and confirm a final reply for an opted-in turn."""
2
+ from contextlib import closing
3
+ import os
4
+ from pathlib import Path
5
+ import re
6
+ import shutil
7
+ import sqlite3
8
+ import subprocess
9
+ from uuid import UUID
10
+
11
+ from .agy_turns import visible_body
12
+ from .codex_host import CodexHost
13
+ from .store import GovernanceError
14
+ from .core import _linked
15
+
16
+ _desktop_reader = None
17
+
18
+ def valid_id(value):
19
+ try:
20
+ return isinstance(value, str) and str(UUID(value)) == value
21
+ except ValueError:
22
+ return False
23
+
24
+
25
+ def local_path(value):
26
+ if not isinstance(value, str):
27
+ return None
28
+ if os.name == 'nt' and value.startswith('\\\\?\\') and re.match(r'^[a-zA-Z]:\\', value[4:]):
29
+ value = value[4:]
30
+ path = Path(value)
31
+ return path if path.is_absolute() else None
32
+
33
+
34
+ def chats(home, workspace, cid=None, *, archived=False):
35
+ """Index metadata only. A workspace must match a top-level user chat exactly."""
36
+ codex_home = Path(os.getenv('CODEX_HOME') or Path(home) / '.codex')
37
+ index_dir = Path(os.getenv('CODEX_SQLITE_HOME') or codex_home)
38
+ if not index_dir.is_absolute() or not codex_home.is_absolute() or not index_dir.is_dir():
39
+ return {}
40
+ databases = [(int(m[1]), p) for p in index_dir.glob('state_*.sqlite')
41
+ if (m := re.fullmatch(r'state_(\d{1,5})\.sqlite', p.name))]
42
+ if not databases:
43
+ return {}
44
+ db = max(databases)[1]
45
+ if any(_linked(p) for p in (db, *db.parents)):
46
+ return {}
47
+ roots = [str(workspace)]
48
+ if os.name == 'nt':
49
+ roots.append('\\\\?\\' + str(workspace))
50
+ marks = ','.join('?' for _ in roots)
51
+ collate = ' COLLATE NOCASE' if os.name == 'nt' else ''
52
+ query = ("SELECT id,rollout_path FROM threads WHERE archived=? AND thread_source IN ('user','agent_created_thread') "
53
+ "AND source IN ('vscode','cli') AND agent_path IS NULL AND attached_thread_parent_id IS NULL "
54
+ f"AND cwd{collate} IN ({marks})")
55
+ if cid is not None:
56
+ query += ' AND id=?'
57
+ roots.append(cid)
58
+ found = {}
59
+ try:
60
+ with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=0.25)) as conn:
61
+ for ident, raw in conn.execute(query, [int(archived), *roots]):
62
+ if archived:
63
+ if valid_id(ident):
64
+ found[ident] = None # The archive flag remains authoritative if the rollout has moved.
65
+ continue
66
+ path = local_path(raw)
67
+ if not valid_id(ident) or not path or not path.is_relative_to(codex_home / 'sessions'):
68
+ continue
69
+ parts = path.relative_to(codex_home / 'sessions').parts
70
+ if (len(parts) == 4 and all(re.fullmatch(pattern, part) for pattern, part in
71
+ zip((r'\d{4}', r'\d{2}', r'\d{2}'), parts[:3]))
72
+ and path.name.startswith('rollout-') and path.name.endswith('-' + ident + '.jsonl')
73
+ and path.is_file() and not any(_linked(p) for p in (path, *path.parents))):
74
+ found[ident] = path
75
+ except (sqlite3.Error, OSError):
76
+ return {}
77
+ return found
78
+
79
+
80
+ def windows_app_reader():
81
+ """Resolve the current user's registered Codex desktop package when PATH lacks its CLI."""
82
+ system = os.environ.get('SystemRoot')
83
+ if not system:
84
+ return None
85
+ powershell = Path(system) / 'System32/WindowsPowerShell/v1.0/powershell.exe'
86
+ if not powershell.is_absolute() or not powershell.is_file():
87
+ return None
88
+ query = ("[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);"
89
+ "$p=Get-AppxPackage -Name OpenAI.Codex -ErrorAction Stop | "
90
+ "Where-Object PackageFamilyName -eq OpenAI.Codex_2p2nqsd0c76g0 | "
91
+ "Sort-Object Version -Descending | Select-Object -First 1;"
92
+ "if($p){[Console]::Write($p.InstallLocation)}")
93
+ try:
94
+ result = subprocess.run([str(powershell), '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', query],
95
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=8,
96
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0), check=True)
97
+ install = Path(result.stdout.decode('utf-8').strip())
98
+ binary = install / 'app/resources/codex.exe'
99
+ return str(binary) if install.is_absolute() and binary.is_file() else None
100
+ except (OSError, subprocess.SubprocessError, UnicodeError, ValueError):
101
+ return None
102
+
103
+
104
+ def reader(home):
105
+ global _desktop_reader
106
+ executable = shutil.which('codex.exe' if os.name == 'nt' else 'codex')
107
+ if not executable and os.name == 'nt':
108
+ if not _desktop_reader or not Path(_desktop_reader).is_file():
109
+ _desktop_reader = windows_app_reader()
110
+ executable = _desktop_reader
111
+ if not executable:
112
+ raise GovernanceError('HOST_UNAVAILABLE', 'The local Codex history reader is unavailable.')
113
+ host = CodexHost(executable, os.getenv('CODEX_HOME') or Path(home) / '.codex')
114
+ if os.environ.get('CODEX_SQLITE_HOME'):
115
+ host.env['CODEX_SQLITE_HOME'] = os.environ['CODEX_SQLITE_HOME']
116
+ return host
117
+
118
+
119
+ def turns(host, cid, *, limit=32, cursor=None):
120
+ """Read identifiers and completion states without loading message items."""
121
+ page = host._run([('thread/turns/list', {'threadId': cid, 'limit': limit, 'cursor': cursor,
122
+ 'sortDirection': 'desc', 'itemsView': 'notLoaded'})])['results'][0]
123
+ host._validate_page(page, limit)
124
+ rows = []
125
+ for item in page['data']:
126
+ if not valid_id(item.get('id')) or item.get('items') or not isinstance(item.get('status'), str):
127
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Unexpected Codex turn metadata.')
128
+ rows.append((item['id'], item['status']))
129
+ return rows, page.get('nextCursor')
130
+
131
+
132
+ def new_turns(host, cid, frontier):
133
+ """Stop at the consent boundary even if the local history has changed."""
134
+ rows = []
135
+ cursor = None
136
+ seen = set()
137
+ while True:
138
+ page, cursor = turns(host, cid, cursor=cursor)
139
+ for tid, state in page:
140
+ if tid == frontier:
141
+ return list(reversed(rows))
142
+ if tid in seen:
143
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Duplicate turn while paging through Codex history.')
144
+ seen.add(tid)
145
+ rows.append((tid, state))
146
+ if not cursor:
147
+ if frontier is not None:
148
+ raise GovernanceError('CAPTURE_HISTORY_CHANGED', 'The saved conversation boundary is unavailable.')
149
+ return list(reversed(rows))
150
+ if not page:
151
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Empty continuation page in Codex history.')
152
+
153
+
154
+ def visible_pair(host, cid, tid):
155
+ """Project the visible question and final answer of one completed turn."""
156
+ base = {'threadId': cid, 'turnId': tid, 'limit': 1,
157
+ 'deferOutput': {'commandExecution': True, 'mcpToolCall': True}}
158
+ result = host._run([('thread/items/list', {**base, 'sortDirection': direction})
159
+ for direction in ('asc', 'desc')])['results']
160
+ items = []
161
+ for page in result:
162
+ host._validate_page(page, 1)
163
+ if not page['data']:
164
+ return None
165
+ row = page['data'][0]
166
+ if row.get('turnId') != tid or not isinstance(row.get('item'), dict):
167
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex returned an unexpected turn item.')
168
+ items.append(row['item'])
169
+ question, answer = items
170
+ moderation = answer.get('moderation') or {}
171
+ if (question.get('type') != 'userMessage' or answer.get('type') != 'agentMessage'
172
+ or answer.get('phase') != 'final_answer' or answer.get('delivery') == 'async'
173
+ or not isinstance(moderation, dict) or moderation.get('moderated') or moderation.get('display')):
174
+ return None
175
+ content = question.get('content')
176
+ if not isinstance(content, list) or not all(isinstance(part, dict) for part in content):
177
+ return None
178
+ parts = [part['text'] for part in content if part.get('type') == 'text' and isinstance(part.get('text'), str)]
179
+ user, user_gap = visible_body('\n'.join(parts))
180
+ final, final_gap = visible_body(answer.get('text'))
181
+ if user is None or final is None:
182
+ return None
183
+ return {'turn_id': tid, 'user': user, 'assistant': final,
184
+ 'omissions': user_gap or final_gap or len(parts) != len(content)}
@@ -0,0 +1,293 @@
1
+ """Bounded local Codex history reader. No agent turns or host mutations.
2
+
3
+ App Server itself may maintain caches/logs in the selected Codex home. This
4
+ adapter guarantees a read-method allowlist, not a zero-write host process.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import queue
13
+ import subprocess
14
+ import threading
15
+ import time
16
+
17
+ from .store import GovernanceError
18
+
19
+
20
+ TESTED_CODEX_VERSIONS = ('0.166.0-alpha.6', '0.171.0-alpha.13.2')
21
+ METHODS = frozenset(('initialize', 'thread/list', 'thread/read', 'thread/turns/list', 'thread/items/list'))
22
+ MAX_BYTES = 2 * 1024 * 1024
23
+
24
+
25
+ def _text(value, name, maximum=4096):
26
+ if not isinstance(value, str) or not value.strip() or len(value) > maximum:
27
+ raise GovernanceError('INVALID_ARGUMENT', name + ' must be bounded nonempty text.')
28
+ return value
29
+
30
+
31
+ def _page(limit, cursor):
32
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 50:
33
+ raise GovernanceError('INVALID_ARGUMENT', 'limit must be 1-50.')
34
+ if cursor is not None:
35
+ _text(cursor, 'cursor', 8192)
36
+
37
+
38
+ class _Process:
39
+ """Drain both pipes with bounded retained bytes and one total deadline."""
40
+ def __init__(self, command, cwd, env, timeout, max_bytes):
41
+ self.deadline = time.monotonic() + timeout
42
+ self.max_bytes = max_bytes
43
+ self.used = 0
44
+ self.lock = threading.Lock()
45
+ self.messages = queue.Queue()
46
+ self.threads = []
47
+ self.writers = []
48
+ self.stderr = bytearray()
49
+ flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
50
+ try:
51
+ self.process = subprocess.Popen(command, cwd=cwd, env=env, stdin=subprocess.PIPE,
52
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
53
+ creationflags=flags, shell=False)
54
+ except OSError as exc:
55
+ raise GovernanceError('HOST_UNAVAILABLE', 'Could not start the selected Codex executable.',
56
+ {'error': str(exc)}) from exc
57
+ for name in ('stdout', 'stderr'):
58
+ thread = threading.Thread(target=self._drain, args=(name,), daemon=True)
59
+ thread.start()
60
+ self.threads.append(thread)
61
+
62
+ def _drain(self, name):
63
+ stream = getattr(self.process, name)
64
+ pending = bytearray()
65
+ try:
66
+ while True:
67
+ block = stream.read1(4096)
68
+ if not block:
69
+ break
70
+ with self.lock:
71
+ self.used += len(block)
72
+ if self.used > self.max_bytes:
73
+ self.messages.put(('error', 'HOST_OUTPUT_LIMIT'))
74
+ return
75
+ if name == 'stderr':
76
+ self.stderr.extend(block[:max(0, 4096 - len(self.stderr))])
77
+ continue
78
+ pending.extend(block)
79
+ while b'\n' in pending:
80
+ line, _, pending = pending.partition(b'\n')
81
+ self.messages.put(('line', bytes(line)))
82
+ if pending:
83
+ self.messages.put(('line', bytes(pending)))
84
+ except (OSError, ValueError):
85
+ pass
86
+ finally:
87
+ self.messages.put(('eof', name))
88
+
89
+ def receive(self):
90
+ remaining = self.deadline - time.monotonic()
91
+ if remaining <= 0:
92
+ raise GovernanceError('HOST_TIMEOUT', 'Codex history reading exceeded its time limit.')
93
+ try:
94
+ kind, value = self.messages.get(timeout=remaining)
95
+ except queue.Empty as exc:
96
+ raise GovernanceError('HOST_TIMEOUT', 'Codex history reading exceeded its time limit.') from exc
97
+ if kind == 'error':
98
+ raise GovernanceError(value, 'Codex output exceeded the configured byte limit.')
99
+ return kind, value
100
+
101
+ def send(self, message):
102
+ payload = json.dumps(message).encode('utf-8') + b'\n'
103
+ if len(payload) > self.max_bytes:
104
+ raise GovernanceError('HOST_INPUT_LIMIT', 'Codex request exceeded the configured byte limit.')
105
+ remaining = self.deadline - time.monotonic()
106
+ if remaining <= 0:
107
+ raise GovernanceError('HOST_TIMEOUT', 'Codex history reading exceeded its time limit.')
108
+ outcome = []
109
+ def write():
110
+ try:
111
+ self.process.stdin.write(payload)
112
+ self.process.stdin.flush()
113
+ except (OSError, ValueError) as exc:
114
+ outcome.append(exc)
115
+ writer = threading.Thread(target=write, daemon=True)
116
+ self.writers.append(writer)
117
+ writer.start()
118
+ writer.join(timeout=remaining)
119
+ if writer.is_alive():
120
+ # Closing the buffered stdin while this thread owns its lock can
121
+ # deadlock on Windows. Termination first releases pipe backpressure.
122
+ if self.process.poll() is None:
123
+ self.process.kill()
124
+ raise GovernanceError('HOST_TIMEOUT', 'Codex stopped reading input before the request deadline.')
125
+ if outcome:
126
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex closed its input pipe.') from outcome[0]
127
+
128
+ def close(self):
129
+ if any(writer.is_alive() for writer in self.writers):
130
+ if self.process.poll() is None:
131
+ self.process.kill()
132
+ self.process.wait(timeout=2)
133
+ for writer in self.writers:
134
+ writer.join(timeout=2)
135
+ try:
136
+ self.process.stdin.close()
137
+ except (OSError, ValueError):
138
+ pass
139
+ if self.process.poll() is None:
140
+ try:
141
+ self.process.wait(timeout=1)
142
+ except subprocess.TimeoutExpired:
143
+ self.process.terminate()
144
+ try:
145
+ self.process.wait(timeout=2)
146
+ except subprocess.TimeoutExpired:
147
+ self.process.kill()
148
+ self.process.wait(timeout=2)
149
+ for thread in self.threads:
150
+ thread.join(timeout=2)
151
+ self.process.stdout.close()
152
+ self.process.stderr.close()
153
+
154
+
155
+ class CodexHost:
156
+ def __init__(self, executable, codex_home=None, timeout=15, max_bytes=MAX_BYTES):
157
+ path = Path(_text(executable, 'executable')).expanduser()
158
+ if not path.is_absolute() or not path.is_file() or path.suffix.lower() in ('.cmd', '.bat', '.ps1'):
159
+ raise GovernanceError('HOST_UNAVAILABLE', 'Select an existing absolute native Codex executable path.')
160
+ home = Path(codex_home or os.environ.get('CODEX_HOME') or Path.home() / '.codex').expanduser()
161
+ if not home.is_absolute() or not home.is_dir():
162
+ raise GovernanceError('HOST_UNAVAILABLE', 'Select an existing absolute Codex home directory.')
163
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 1 <= timeout <= 60:
164
+ raise GovernanceError('INVALID_ARGUMENT', 'timeout must be 1-60 seconds.')
165
+ if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or not 1024 <= max_bytes <= MAX_BYTES:
166
+ raise GovernanceError('INVALID_ARGUMENT', 'max_bytes must be 1024-2097152.')
167
+ self.executable, self.home = path.resolve(), home.resolve()
168
+ self.timeout, self.max_bytes = timeout, max_bytes
169
+ self.env = dict(os.environ, CODEX_HOME=str(self.home), CODEX_SQLITE_HOME=str(self.home))
170
+
171
+ def _version(self):
172
+ child = _Process([str(self.executable), '--version'], self.home, self.env, self.timeout, 16384)
173
+ try:
174
+ output = []
175
+ while True:
176
+ kind, value = child.receive()
177
+ if kind == 'eof' and value == 'stdout':
178
+ break
179
+ if kind == 'line':
180
+ output.append(value.decode('utf-8', errors='replace'))
181
+ value = '\n'.join(output).strip()
182
+ version = value.removeprefix('codex-cli ')
183
+ if version not in TESTED_CODEX_VERSIONS:
184
+ raise GovernanceError('HOST_VERSION_UNVERIFIED', 'This Codex version has not passed the history adapter contract.',
185
+ {'reported_version': value, 'tested_versions': list(TESTED_CODEX_VERSIONS),
186
+ 'fallback': 'Use host-provided read tools or a selected handoff.'})
187
+ return version
188
+ finally:
189
+ child.close()
190
+
191
+ @staticmethod
192
+ def _request(child, method, params, request_id):
193
+ if method not in METHODS:
194
+ raise GovernanceError('HOST_METHOD_FORBIDDEN', 'Only history read methods are supported.')
195
+ child.send({'method': method, 'id': request_id, 'params': params})
196
+ while True:
197
+ kind, value = child.receive()
198
+ if kind == 'eof' and value == 'stdout':
199
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex ended before returning the requested result.',
200
+ {'stderr': child.stderr.decode('utf-8', errors='replace')})
201
+ if kind != 'line' or not value.strip():
202
+ continue
203
+ try:
204
+ message = json.loads(value)
205
+ except (ValueError, UnicodeDecodeError) as exc:
206
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex returned invalid JSON.') from exc
207
+ if not isinstance(message, dict):
208
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex returned a non-object message.')
209
+ if message.get('id') != request_id:
210
+ if 'method' in message and 'id' in message:
211
+ raise GovernanceError('HOST_INTERACTION_REQUIRED', 'A read operation unexpectedly requested host action.',
212
+ {'method': message['method']})
213
+ continue
214
+ if 'error' in message:
215
+ raise GovernanceError('HOST_REQUEST_FAILED', 'The Codex history request failed.',
216
+ {'method': method, 'original_error': message['error']})
217
+ if not isinstance(message.get('result'), dict):
218
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex result must be an object.')
219
+ return message['result']
220
+
221
+ def _run(self, requests):
222
+ version = self._version()
223
+ child = _Process([str(self.executable), 'app-server', '--listen', 'stdio://'],
224
+ self.home, self.env, self.timeout, self.max_bytes)
225
+ try:
226
+ handshake = self._request(child, 'initialize', {
227
+ 'clientInfo': {'name': 'taskcarry_history_reader', 'version': '1.0.0'},
228
+ 'capabilities': {'experimentalApi': True}}, 1)
229
+ child.send({'method': 'initialized', 'params': {}})
230
+ results = [self._request(child, method, params, number)
231
+ for number, (method, params) in enumerate(requests, 2)]
232
+ return {'source': {'kind': 'codex_local_app_server', 'executable': str(self.executable),
233
+ 'codex_home': str(self.home), 'version': version,
234
+ 'id': hashlib.sha256(str(self.home).encode()).hexdigest()},
235
+ 'handshake': handshake, 'results': results, 'read_methods_only': True,
236
+ 'agent_turn_started': False, 'host_startup_may_write_caches': True,
237
+ 'content_is_untrusted': True,
238
+ 'coverage': 'Selected local Codex home and its effective host configuration; a configured sqlite_home may locate its index elsewhere. No cloud or other-host completeness claim.'}
239
+ finally:
240
+ child.close()
241
+
242
+ def capabilities(self):
243
+ result = self._run([])
244
+ result.update(methods=sorted(METHODS - {'initialize'}), state_db_only=True,
245
+ tested_versions=list(TESTED_CODEX_VERSIONS), history_read_verified=False)
246
+ return result
247
+
248
+ def list_threads(self, limit=20, cursor=None, archived=False):
249
+ _page(limit, cursor)
250
+ if not isinstance(archived, bool):
251
+ raise GovernanceError('INVALID_ARGUMENT', 'archived must be boolean.')
252
+ result = self._run([('thread/list', {'limit': limit, 'cursor': cursor, 'archived': archived,
253
+ 'useStateDbOnly': True, 'modelProviders': [],
254
+ 'sourceKinds': ['cli', 'vscode', 'exec', 'appServer'],
255
+ 'sortKey': 'updated_at', 'sortDirection': 'desc'})])
256
+ page = result.pop('results')[0]
257
+ self._validate_page(page, limit)
258
+ result.update(page=page, archived=archived, state_db_only=True, full_history_read=False)
259
+ return result
260
+
261
+ @staticmethod
262
+ def _validate_page(page, limit):
263
+ if not isinstance(page.get('data'), list) or len(page['data']) > limit:
264
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex returned an invalid or oversized page.')
265
+ if page.get('nextCursor') is not None and not isinstance(page['nextCursor'], str):
266
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex returned an invalid cursor.')
267
+
268
+ def read_thread(self, thread_id, limit=20, cursor=None):
269
+ _text(thread_id, 'thread_id', 256)
270
+ _page(limit, cursor)
271
+ result = self._run([('thread/read', {'threadId': thread_id, 'includeTurns': False}),
272
+ ('thread/turns/list', {'threadId': thread_id, 'limit': limit, 'cursor': cursor,
273
+ 'sortDirection': 'desc', 'itemsView': 'full'})])
274
+ metadata, page = result.pop('results')
275
+ self._validate_page(page, limit)
276
+ if not isinstance(metadata.get('thread'), dict) or metadata['thread'].get('id') != thread_id:
277
+ raise GovernanceError('HOST_PROTOCOL_ERROR', 'Codex returned a different thread identity.')
278
+ result.update(thread=metadata['thread'], page=page, requested_thread_id=thread_id,
279
+ full_history_read=cursor is None and page.get('nextCursor') is None,
280
+ history_scope='Persisted turns exposed by this App Server; not unsaved or unindexed history.')
281
+ return result
282
+
283
+
284
+ def codex_read(action, executable, codex_home=None, limit=20, cursor=None, archived=False,
285
+ thread_id=None, timeout=15, max_bytes=MAX_BYTES):
286
+ if action not in ('capabilities', 'list', 'read'):
287
+ raise GovernanceError('INVALID_ARGUMENT', 'action must be capabilities, list or read.')
288
+ host = CodexHost(executable, codex_home, timeout, max_bytes)
289
+ if action == 'capabilities':
290
+ return host.capabilities()
291
+ if action == 'list':
292
+ return host.list_threads(limit, cursor, archived)
293
+ return host.read_thread(thread_id, limit, cursor)