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
@@ -0,0 +1,32 @@
1
+ """Public schemas for versioned workbench navigation (no engine imports)."""
2
+
3
+
4
+ def obj(properties, required=()):
5
+ return {"type": "object", "properties": properties, "required": list(required), "additionalProperties": False}
6
+
7
+
8
+ TEXT = {"type": "string"}
9
+ SOURCE = obj({"source_id": TEXT, "revision": TEXT, "collection": TEXT,
10
+ "local_id": TEXT, "path": TEXT}, ("source_id", "revision"))
11
+ WRITE = obj({"path": TEXT, "mode": {"type": "string", "enum": ["managed_section", "exact"]},
12
+ "section_id": TEXT, "text": TEXT,
13
+ "expected_sha256": {"type": ["string", "null"]}}, ("path", "text"))
14
+ TARGET = obj({"workspace": TEXT, "task_id": TEXT, "thread_id": TEXT, "source_id": TEXT,
15
+ "replaces_thread_id": TEXT,
16
+ "host": {"type": "string", "enum": ["codex", "none"]},
17
+ "code_assessment": obj({"status": {"type": "string", "enum": ["NO_CODE_DEPENDENCY", "ALREADY_CONTAINS", "SEPARATE_CODE_PLAN_REQUIRED"]},
18
+ "reason": TEXT}, ("status", "reason")),
19
+ "writes": {"type": "array", "items": WRITE, "maxItems": 16}},
20
+ ("workspace", "task_id", "thread_id", "code_assessment"))
21
+ PROOF = obj({"workspace": TEXT, "plan_id": TEXT, "view_id": TEXT, "task_id": TEXT,
22
+ "source_id": TEXT, "thread_id": TEXT, "turn_id": TEXT, "evidence_path": TEXT,
23
+ "evidence_sha256": TEXT, "reviewer": TEXT, "observed_at": TEXT},
24
+ ("workspace", "plan_id", "view_id", "task_id", "source_id", "thread_id", "turn_id",
25
+ "evidence_path", "evidence_sha256", "reviewer", "observed_at"))
26
+ SCHEMAS = {"workbench": obj({
27
+ "action": {"type": "string", "enum": ["freeze", "plan", "execute", "status", "consume"]},
28
+ "body": TEXT, "sources": {"type": "array", "items": SOURCE, "minItems": 1, "maxItems": 50}, "view_id": TEXT,
29
+ "targets": {"type": "array", "items": TARGET, "minItems": 1, "maxItems": 24}, "plan_id": TEXT, "workspace": TEXT,
30
+ "routing": {"type": "string", "enum": ["shared"]}, "thread_id": TEXT,
31
+ "proof": PROOF, "limit": {"type": "integer", "minimum": 1, "maximum": 100}, "cursor": TEXT}, ("action",))}
32
+ DESCRIPTIONS = {"workbench": "Freeze navigation and explicit source revisions; plan then publish private workbench entries without changing Git, tasks or professional instructions. Read current publication and separate reviewed-consumption evidence, or record that evidence. Generated entries do not prove host loading or business acceptance."}
@@ -0,0 +1,451 @@
1
+ """WorkBuddy's local visible-turn callbacks. The project board owns consent."""
2
+ import argparse
3
+ import base64
4
+ from contextlib import ExitStack, contextmanager
5
+ from dataclasses import dataclass
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ import secrets
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from urllib.error import HTTPError
16
+ from urllib.request import ProxyHandler, Request, build_opener
17
+
18
+ from .agy_turns import MAX_MESSAGE, MAX_WINDOW
19
+ from .core import _linked
20
+ from .member_join import NoRedirect, checked_url, read_configuration
21
+ from .member_routing import connector_path
22
+ from .setup import SetupError, atomic_write, encoded, safe_target, setup_lock
23
+
24
+
25
+ CONFIG = '.taskcarry/workbuddy-chat.json'
26
+ PENDING = '.taskcarry/workbuddy-turn.json'
27
+ STATUS = '.taskcarry/workbuddy-chat-status.json'
28
+ EVENTS = ('UserPromptSubmit', 'Stop')
29
+ MAX_BODY = 1024 * 1024
30
+ END_WAIT_SECONDS = 10
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class AwaitingEnd:
35
+ final_sha256: str
36
+ observed_size: int
37
+
38
+
39
+ def digest(text):
40
+ return hashlib.sha256(text.encode('utf-8')).hexdigest()
41
+
42
+
43
+ def session_id(value):
44
+ return isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,127}', value) is not None
45
+
46
+
47
+ def device_call(root, cfg, action, **fields):
48
+ target = connector_path(root, Path(cfg['host_home']), cfg.get('settings_scope', 'project'))
49
+ entry = read_configuration(target).get('mcpServers', {}).get(cfg['server'])
50
+ if not isinstance(entry, dict) or entry.get('url') != cfg['endpoint']:
51
+ raise ValueError('The selected project connection changed.')
52
+ url = checked_url(cfg['endpoint'].removesuffix('/mcp') + '/join')
53
+ auth = entry.get('headers', {}).get('Authorization', '')
54
+ if not re.fullmatch(r'Bearer [a-zA-Z0-9_-]{32,128}', auth):
55
+ raise ValueError('Missing project member credential.')
56
+ body = encoded(dict(action=action, session=digest(cfg['session_id']), **fields))
57
+ if len(body) > MAX_BODY:
58
+ raise ValueError('This exchange exceeds the device transport limit.')
59
+ request = Request(cfg['endpoint'].removesuffix('/mcp') + '/member-capture', data=body,
60
+ headers={'Authorization':auth, 'Content-Type':'application/json', 'Accept':'application/json'})
61
+ handlers = [NoRedirect()]
62
+ if url.hostname.endswith('.ts.net'):
63
+ handlers.append(ProxyHandler({}))
64
+ for attempt in range(2):
65
+ try:
66
+ with build_opener(*handlers).open(request, timeout=3) as response:
67
+ raw = response.read(8193)
68
+ if len(raw) > 8192 or response.headers.get_content_type() != 'application/json':
69
+ raise ValueError('Unexpected project response.')
70
+ result = json.loads(raw)
71
+ if not isinstance(result, dict) or 'state' not in result:
72
+ raise ValueError('Incomplete project response.')
73
+ return result
74
+ except HTTPError as exc:
75
+ if exc.code != 503 or attempt:
76
+ raise
77
+ time.sleep(0.12)
78
+
79
+
80
+ def ordinary(path):
81
+ return not any(_linked(p) for p in (path, *path.parents))
82
+
83
+
84
+ def transcript(cfg, data):
85
+ raw = data.get('transcript_path')
86
+ if not isinstance(raw, str):
87
+ return None
88
+ path = Path(raw)
89
+ project_files = Path(cfg['host_home']) / 'projects'
90
+ if (not path.is_absolute() or '..' in path.parts or not ordinary(path)
91
+ or not path.is_relative_to(project_files) or path.name != cfg['session_id'] + '.jsonl'):
92
+ return None
93
+ return path
94
+
95
+
96
+ def file_mark(path):
97
+ try:
98
+ stat = path.stat()
99
+ return [stat.st_dev, stat.st_ino], stat.st_size
100
+ except FileNotFoundError:
101
+ return None, 0
102
+
103
+
104
+ def text_blocks(row, kind):
105
+ blocks = row.get('content')
106
+ if not isinstance(blocks, list):
107
+ return None
108
+ texts = [b['text'] for b in blocks if isinstance(b, dict) and b.get('type') == kind
109
+ and isinstance(b.get('text'), str)]
110
+ return '\n'.join(texts) if texts else None
111
+
112
+
113
+ def capture_input(prompt, host_turn):
114
+ proof = {'prompt_hash': digest(prompt)}
115
+ if os.name == 'nt' and isinstance(host_turn, str) and host_turn and len(prompt.encode('utf-8')) <= MAX_MESSAGE:
116
+ # Only the active, authorized slot can contain input. Windows protects
117
+ # it for this user between callbacks. The host's model input may differ.
118
+ from .feishu.windows_secret import transform
119
+ try:
120
+ proof['sealed_input'] = base64.b64encode(transform(prompt.encode('utf-8'), encrypt=True)).decode('ascii')
121
+ except OSError:
122
+ pass # Exact transcript matching still works without protected storage.
123
+ return proof
124
+
125
+
126
+ def callback_input(start):
127
+ if 'sealed_input' not in start or not start.get('host_turn') or os.name != 'nt':
128
+ return None
129
+ from .feishu.windows_secret import transform
130
+ try:
131
+ value = transform(base64.b64decode(start['sealed_input'], validate=True), encrypt=False).decode('utf-8')
132
+ except (ValueError, OSError, UnicodeError):
133
+ return None
134
+ return value if digest(value) == start['prompt_hash'] else None
135
+
136
+
137
+ def bookkeeping(row):
138
+ """After end_turn, a metadata-only tail cannot replace the completed answer."""
139
+ kind = row.get('type')
140
+ if not isinstance(kind, str) or any(word in kind.lower() for word in (
141
+ 'tool', 'function', 'reasoning', 'cancel', 'abort', 'interrupt', 'error', 'fail')):
142
+ return False
143
+ return not any(key in row for key in (
144
+ 'role', 'content', 'message', 'text', 'payload', 'input', 'output', 'tool_calls', 'error'))
145
+
146
+
147
+ def finished_pair(path, root, cfg, start, final_hint, submitted=None, *, report_pending_end=False, require_end=False):
148
+ """Read one scoped, completed visible exchange after the submit callback."""
149
+ identity, end = file_mark(path)
150
+ if not identity or (start['identity'] is not None and identity != start['identity']) or end <= start['offset']:
151
+ return None
152
+ floor = max(0, end - MAX_WINDOW)
153
+ with path.open('rb') as handle:
154
+ handle.seek(floor)
155
+ if floor:
156
+ handle.readline(MAX_WINDOW)
157
+ chunk = handle.read(end - handle.tell())
158
+ if not chunk or not chunk.endswith(b'\n'):
159
+ return None
160
+ question = reply = reply_request = None
161
+ native_input = new_user = ended = False
162
+ position = end - len(chunk)
163
+ for line in chunk.splitlines(keepends=True):
164
+ position += len(line)
165
+ try:
166
+ row = json.loads(line)
167
+ except (ValueError, UnicodeError):
168
+ if position > start['offset']:
169
+ return None
170
+ question = reply = None
171
+ continue
172
+ if not isinstance(row, dict):
173
+ return None
174
+ if (row.get('sessionId') not in (None, cfg['session_id'])
175
+ or (row.get('cwd') is not None and (not isinstance(row['cwd'], str) or Path(row['cwd']) != root))):
176
+ if position > start['offset']:
177
+ return None
178
+ question = reply = None
179
+ continue
180
+ kind = row.get('type')
181
+ if kind == 'message' and row.get('role') == 'user':
182
+ question = reply = reply_request = None
183
+ native_input = ended = False
184
+ if row.get('isMeta') or row.get('isSidechain'):
185
+ continue
186
+ if position > start['offset']:
187
+ if new_user:
188
+ return None
189
+ new_user = True
190
+ content = text_blocks(row, 'input_text')
191
+ if not content:
192
+ continue
193
+ if digest(content) == start['prompt_hash']:
194
+ question = content
195
+ elif new_user and submitted is not None:
196
+ question = submitted
197
+ native_input = True
198
+ else:
199
+ # Older pending records have only the digest. Never recover
200
+ # a different string from workspace instructions in this row.
201
+ question = next((s for s in content.splitlines() if digest(s) == start['prompt_hash']), None)
202
+ elif kind == 'message' and row.get('role') == 'assistant':
203
+ reply = reply_request = None
204
+ ended = False
205
+ if not question or position <= start['offset'] or row.get('isSidechain') or row.get('isMeta'):
206
+ continue
207
+ blocks = row.get('content')
208
+ if (not isinstance(blocks, list) or row.get('tool_calls')
209
+ or any(isinstance(b,dict) and b.get('type') in (
210
+ 'function_call','tool_call','tool_use','function_call_output','tool_result') for b in blocks)):
211
+ continue
212
+ candidate = text_blocks(row, 'output_text')
213
+ if row.get('status') == 'completed' or (row.get('status') is None and candidate == final_hint):
214
+ reply = candidate
215
+ reply_request = row.get('requestId')
216
+ elif 'stopReason' in row:
217
+ receipt = row.get('requestId')
218
+ ended = bool(reply and row.get('stopReason') == 'end_turn' and isinstance(receipt, str) and receipt
219
+ and (not reply_request or reply_request == receipt) and not row.get('isSidechain')
220
+ and not any(k in row for k in ('error','role','content','tool_calls')))
221
+ if not ended:
222
+ reply = reply_request = None
223
+ elif kind in ('usage', 'session_meta', 'turn_end', 'file-history-snapshot') or (ended and bookkeeping(row)):
224
+ continue
225
+ else:
226
+ reply = reply_request = None
227
+ ended = False
228
+ if not question or not reply or (final_hint is not None and final_hint != reply):
229
+ return None
230
+ if (native_input or require_end) and not (new_user and ended):
231
+ if new_user and report_pending_end:
232
+ return AwaitingEnd(digest(reply), end)
233
+ return None
234
+ return question, reply
235
+
236
+
237
+ def read_json(path):
238
+ return json.loads(path.read_text(encoding='utf-8-sig'))
239
+
240
+
241
+ def note(root, state, **metadata):
242
+ atomic_write(safe_target(root, STATUS), encoded(dict(status=state, **metadata)))
243
+
244
+
245
+ @contextmanager
246
+ def capture_lock(root):
247
+ # A local finalizer can briefly hold the same lock while retiring its slot.
248
+ with ExitStack() as stack:
249
+ for attempt in range(15):
250
+ try:
251
+ stack.enter_context(setup_lock(root))
252
+ break
253
+ except SetupError as exc:
254
+ if exc.code != 'SETUP_BUSY' or attempt == 14:
255
+ raise
256
+ time.sleep(0.025)
257
+ yield
258
+
259
+
260
+ def launch_end_check(root, job):
261
+ workspace = base64.urlsafe_b64encode(str(root).encode('utf-8')).decode('ascii')
262
+ args = [sys.executable, '-I', '-B', '-X', 'utf8', '-m', 'taskcarry.workbuddy_capture',
263
+ '--workspace64', workspace, '--finish']
264
+ options = {'creationflags': subprocess.CREATE_NO_WINDOW} if os.name == 'nt' else {'start_new_session': True}
265
+ # WorkBuddy must see EOF on its hook pipes before it writes the terminal row.
266
+ # Pass the protected question through a private pipe. No host handles or task text are inherited.
267
+ process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
268
+ close_fds=True, **options)
269
+ with process.stdin as pipe:
270
+ pipe.write(encoded(job))
271
+
272
+
273
+ def matching_check(path, check_id):
274
+ try:
275
+ start = read_json(path)
276
+ except FileNotFoundError:
277
+ return None
278
+ if start.get('end_check', {}).get('id') == check_id:
279
+ return start
280
+ return None
281
+
282
+
283
+ def finish_after_stop(root, job, call=device_call):
284
+ """Confirm only the Stop callback's already visible candidate, after the host regains control."""
285
+ check_id = job.get('id')
286
+ if not isinstance(check_id, str) or not re.fullmatch(r'[0-9a-f]{32}', check_id):
287
+ return
288
+ pending = safe_target(root, PENDING)
289
+ start = matching_check(pending, check_id)
290
+ if not start:
291
+ return
292
+ check = start['end_check']
293
+ cfg = read_json(safe_target(root, CONFIG))
294
+ path = transcript(cfg, {'transcript_path': check['transcript']})
295
+ until = time.monotonic() + min(END_WAIT_SECONDS, check['expires_at'] - time.time())
296
+ seen = check['observed_size']
297
+ outcome = 'complete_visible_pair_unavailable'
298
+ details = {}
299
+ try:
300
+ if path is None or cfg['session_id'] != check['session_id']:
301
+ return
302
+ while time.monotonic() < until:
303
+ if not matching_check(pending, check_id):
304
+ return
305
+ identity, size = file_mark(path)
306
+ if not identity or (start['identity'] is not None and identity != start['identity']) or size < seen:
307
+ break
308
+ if size == seen:
309
+ time.sleep(0.15)
310
+ continue
311
+ seen = size
312
+ grant = call(root, cfg, 'status')
313
+ if grant['state'] != 'active' or grant['generation'] != start['generation']:
314
+ outcome = 'consent_changed'
315
+ break
316
+ submitted = callback_input({**start, 'sealed_input': job['protected_input']})
317
+ if submitted is None:
318
+ break
319
+ pair = finished_pair(path, root, cfg, start, None, submitted, require_end=True)
320
+ if not pair:
321
+ continue
322
+ if (digest(pair[1]) != check['final_sha256'] or time.monotonic() >= until
323
+ or not matching_check(pending, check_id)):
324
+ break
325
+ result = call(root, cfg, 'complete', request_id=start['request_id'], ticket=start['ticket'],
326
+ generation=start['generation'], user=pair[0], assistant=pair[1])
327
+ outcome = 'shared' if result.get('accepted') else 'consent_changed'
328
+ if result.get('accepted'):
329
+ details['sha256'] = result['sha256']
330
+ break
331
+ except (OSError, ValueError, KeyError):
332
+ outcome = 'project_or_host_unavailable'
333
+ finally:
334
+ with capture_lock(root):
335
+ if matching_check(pending, check_id):
336
+ pending.unlink(missing_ok=True)
337
+ note(root, outcome, **details)
338
+
339
+
340
+ def handle(root, data, call=device_call, *, defer=launch_end_check):
341
+ cfg = read_json(safe_target(root, CONFIG))
342
+ event = data.get('hook_event_name')
343
+ if (event not in EVENTS or data.get('session_id') != cfg['session_id'] or not data.get('cwd')
344
+ or Path(data['cwd']) != root or data.get('agent_id') or data.get('subagent_id')):
345
+ return
346
+ path = transcript(cfg, data)
347
+ with capture_lock(root):
348
+ pending = safe_target(root, PENDING)
349
+ if event == 'UserPromptSubmit':
350
+ # Invalidate any prior unfinished exchange even when this request is offline.
351
+ pending.unlink(missing_ok=True)
352
+ prompt = data.get('prompt')
353
+ if path is None or not isinstance(prompt, str) or not prompt.strip():
354
+ return note(root, 'host_source_unavailable')
355
+ ident, offset = file_mark(path)
356
+ host_turn = data.get('generation_id') or data.get('turn_id')
357
+ request_id = digest(host_turn) if isinstance(host_turn, str) and host_turn else secrets.token_hex(16)
358
+ result = call(root, cfg, 'begin', request_id=request_id)
359
+ ticket = result.get('ticket')
360
+ if result['state'] != 'active' or not ticket:
361
+ return note(root, 'sharing_off')
362
+ atomic_write(pending, encoded(dict(request_id=request_id, host_turn=host_turn, ticket=ticket,
363
+ generation=result['generation'], identity=ident, offset=offset, **capture_input(prompt, host_turn))))
364
+ return note(root, 'awaiting_final')
365
+ if not pending.is_file():
366
+ return
367
+ start = read_json(pending)
368
+ host_turn = data.get('generation_id') or data.get('turn_id')
369
+ if start.get('host_turn') and host_turn and start['host_turn'] != host_turn:
370
+ return
371
+ if path is None or data.get('error') or data.get('interrupted') or data.get('stop_hook_active'):
372
+ pending.unlink(missing_ok=True)
373
+ return note(root, 'incomplete_exchange')
374
+ grant = call(root, cfg, 'status')
375
+ if grant['state'] != 'active' or grant['generation'] != start['generation']:
376
+ pending.unlink(missing_ok=True)
377
+ return note(root, 'consent_changed')
378
+ if 'end_check' in start:
379
+ if time.time() >= start['end_check']['expires_at']:
380
+ pending.unlink(missing_ok=True)
381
+ note(root, 'complete_visible_pair_unavailable')
382
+ return
383
+ submitted = callback_input(start)
384
+ pair = None
385
+ for delay in (0, 0.08, 0.2, 0.4):
386
+ if delay:
387
+ time.sleep(delay)
388
+ pair = finished_pair(path, root, cfg, start, data.get('last_assistant_message') or None, submitted,
389
+ report_pending_end=True)
390
+ if isinstance(pair, AwaitingEnd):
391
+ # The input and candidate are already identified. Some hosts append
392
+ # end_turn only after this callback has exited.
393
+ check_id = secrets.token_hex(16)
394
+ protected = start.pop('sealed_input')
395
+ start['end_check'] = dict(id=check_id, session_id=cfg['session_id'], transcript=str(path),
396
+ final_sha256=pair.final_sha256, observed_size=pair.observed_size,
397
+ expires_at=time.time() + END_WAIT_SECONDS)
398
+ atomic_write(pending, encoded(start))
399
+ note(root, 'awaiting_end_marker')
400
+ try:
401
+ defer(root, {'id': check_id, 'protected_input': protected})
402
+ except OSError:
403
+ pending.unlink(missing_ok=True)
404
+ note(root, 'project_or_host_unavailable')
405
+ return
406
+ if pair:
407
+ break
408
+ if pair is None:
409
+ if start.pop('sealed_input', None) is not None:
410
+ atomic_write(pending, encoded(start))
411
+ return note(root, 'complete_visible_pair_unavailable')
412
+ result = call(root, cfg, 'complete', request_id=start['request_id'], ticket=start['ticket'],
413
+ generation=start['generation'], user=pair[0], assistant=pair[1])
414
+ pending.unlink(missing_ok=True)
415
+ return note(root, 'shared' if result.get('accepted') else 'consent_changed',
416
+ sha256=result.get('sha256'))
417
+
418
+
419
+ def main():
420
+ parser = argparse.ArgumentParser()
421
+ parser.add_argument('--workspace64', required=True)
422
+ parser.add_argument('--finish', action='store_true')
423
+ args = parser.parse_args()
424
+ root = None
425
+ selected = False
426
+ try:
427
+ root = Path(base64.urlsafe_b64decode(args.workspace64).decode('utf-8'))
428
+ raw = sys.stdin.buffer.read(MAX_BODY + 1)
429
+ if len(raw) <= MAX_BODY and ordinary(root):
430
+ data = json.loads(raw)
431
+ if args.finish:
432
+ if isinstance(data, dict):
433
+ finish_after_stop(root, data)
434
+ return
435
+ cfg = read_json(safe_target(root, CONFIG))
436
+ selected = isinstance(data, dict) and data.get('session_id') == cfg['session_id'] and Path(data.get('cwd','')) == root
437
+ if selected:
438
+ handle(root, data)
439
+ except Exception:
440
+ # A disconnected project must not prevent the user from chatting or leak
441
+ # the hook payload into host logs. Status contains only a fixed reason.
442
+ if selected:
443
+ try:
444
+ note(root, 'project_or_host_unavailable')
445
+ except Exception:
446
+ pass
447
+ print('{}')
448
+
449
+
450
+ if __name__ == '__main__':
451
+ main()