codex-desk 0.1.0a29__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.
codex_desk/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Project-bound native Codex workbench."""
2
+
3
+ __version__ = "0.1.0a29"
codex_desk/drafts.py ADDED
@@ -0,0 +1,93 @@
1
+ """Private, revisioned next-task preparation for an existing Desk session."""
2
+
3
+ MAX_DRAFT_CHARS = 200_000
4
+
5
+
6
+ class DraftConflict(ValueError):
7
+ """The caller's revision is stale; current is the saved draft to review."""
8
+
9
+ def __init__(self, current):
10
+ self.current = dict(current)
11
+ super().__init__(
12
+ "Prepared task changed in another page. Review the current draft before saving again.")
13
+
14
+
15
+ def _session_mode(store, session):
16
+ if not isinstance(session, str) or not session or session == 'native-catalog':
17
+ raise ValueError('Select an existing project session')
18
+ row = store.db.execute('SELECT mode FROM sessions WHERE id=?', (session,)).fetchone()
19
+ if row is None:
20
+ raise ValueError('Session not found')
21
+ return row[0] if row[0] in ('native', 'plan') else 'native'
22
+
23
+
24
+ def _ensure_table(store):
25
+ store.db.execute('''CREATE TABLE IF NOT EXISTS drafts(
26
+ session_id TEXT PRIMARY KEY NOT NULL,
27
+ text TEXT NOT NULL,
28
+ mode TEXT NOT NULL,
29
+ revision INTEGER NOT NULL,
30
+ writer TEXT,
31
+ edit_sequence INTEGER)''')
32
+ columns = {row[1] for row in store.db.execute('PRAGMA table_info(drafts)')}
33
+ for column, definition in (('writer', 'TEXT'), ('edit_sequence', 'INTEGER')):
34
+ if column not in columns:
35
+ store.db.execute(f'ALTER TABLE drafts ADD COLUMN {column} {definition}')
36
+
37
+
38
+ def _read(store, session, initial_mode):
39
+ row = store.db.execute(
40
+ 'SELECT text,mode,revision FROM drafts WHERE session_id=?', (session,)).fetchone()
41
+ if row is None:
42
+ return {'text': '', 'mode': initial_mode, 'revision': 0}
43
+ return {'text': row[0], 'mode': row[1], 'revision': row[2]}
44
+
45
+
46
+ def load_draft(store, session):
47
+ """Return a saved draft, or revision zero using the session's last mode."""
48
+ with store.lock, store.db:
49
+ # Schema upgrades are serialized with saves on other Store connections.
50
+ store.db.execute('BEGIN IMMEDIATE')
51
+ initial_mode = _session_mode(store, session)
52
+ _ensure_table(store)
53
+ return _read(store, session, initial_mode)
54
+
55
+
56
+ def save_draft(store, session, text, mode, expected_revision, writer=None, sequence=None):
57
+ """Save by revision; newer same-page edits can recover a delayed save reply."""
58
+ if not isinstance(text, str) or len(text) > MAX_DRAFT_CHARS:
59
+ raise ValueError(f'Prepared task must be text of at most {MAX_DRAFT_CHARS:,} characters')
60
+ if mode not in ('native', 'plan'):
61
+ raise ValueError('Choose Work or Plan mode')
62
+ if type(expected_revision) is not int or expected_revision < 0:
63
+ raise ValueError('Use a nonnegative draft revision')
64
+ identified = writer is not None or sequence is not None
65
+ if identified and (not isinstance(writer, str) or not writer or len(writer) > 128
66
+ or type(sequence) is not int or not 0 <= sequence <= 2**63 - 1):
67
+ raise ValueError('Use a page writer ID and a nonnegative edit sequence')
68
+ with store.lock, store.db:
69
+ # Start the SQLite write transaction before reading the revision. This
70
+ # also protects against another Store connection to the same state file.
71
+ store.db.execute('BEGIN IMMEDIATE')
72
+ initial_mode = _session_mode(store, session)
73
+ _ensure_table(store)
74
+ current = _read(store, session, initial_mode)
75
+ lineage = store.db.execute(
76
+ 'SELECT writer,edit_sequence FROM drafts WHERE session_id=?', (session,)).fetchone()
77
+ same_writer = identified and lineage is not None and lineage[0] == writer
78
+ if same_writer and sequence <= lineage[1]:
79
+ if sequence == lineage[1] and current['text'] == text and current['mode'] == mode:
80
+ # A keepalive or retry of the same committed edit needs no new revision.
81
+ return current
82
+ raise DraftConflict(current)
83
+ same_page_recovery = (same_writer and sequence > lineage[1]
84
+ and expected_revision < current['revision'])
85
+ if current['revision'] != expected_revision and not same_page_recovery:
86
+ raise DraftConflict(current)
87
+ saved = {'text': text, 'mode': mode, 'revision': current['revision'] + 1}
88
+ store.db.execute('''INSERT INTO drafts(session_id,text,mode,revision,writer,edit_sequence)
89
+ VALUES(?,?,?,?,?,?) ON CONFLICT(session_id) DO UPDATE SET
90
+ text=excluded.text,mode=excluded.mode,revision=excluded.revision,
91
+ writer=excluded.writer,edit_sequence=excluded.edit_sequence''',
92
+ (session, saved['text'], saved['mode'], saved['revision'], writer, sequence))
93
+ return saved
codex_desk/evidence.py ADDED
@@ -0,0 +1,207 @@
1
+ """Readable native tool evidence for the editable handoff, without media payloads."""
2
+ import json
3
+ from urllib.parse import urlsplit, urlunsplit
4
+
5
+
6
+ def _inline_description(value, label='Inline media'):
7
+ if not isinstance(value, str):
8
+ return f'[{label}: unavailable payload]'
9
+ if value.lower().startswith('data:'):
10
+ header, separator, body = value.partition(',')
11
+ mime = header[5:].split(';', 1)[0][:80] or 'unspecified MIME type'
12
+ return f'[{label}: {mime}; inline payload {len(body) if separator else 0} characters]'
13
+ return f'[{label}: inline payload {len(value)} characters]'
14
+
15
+
16
+ def public_uri(value, label='Media'):
17
+ """A plain descriptor; never read a local resource or fetch a URL."""
18
+ if not isinstance(value, str):
19
+ return '[Unavailable URI]'
20
+ if value.lower().startswith('data:'):
21
+ return _inline_description(value, label)
22
+ try:
23
+ parsed = urlsplit(value)
24
+ # Preserve a public address, not access tokens or URL credentials.
25
+ host = parsed.netloc.rsplit('@', 1)[-1]
26
+ return urlunsplit((parsed.scheme, host, parsed.path, '', ''))
27
+ except ValueError:
28
+ return '[Invalid URI]'
29
+
30
+
31
+ def _review_value(value):
32
+ """Keep JSON structure, excluding application-private metadata and binary data."""
33
+ if isinstance(value, dict):
34
+ result = {}
35
+ kind = value.get('type')
36
+ for key, entry in value.items():
37
+ if key == '_meta':
38
+ continue
39
+ if key == 'blob' and isinstance(entry, str):
40
+ result[key] = _inline_description(entry, 'Resource blob')
41
+ elif key == 'data' and kind in ('image', 'audio'):
42
+ result[key] = _inline_description(entry, kind.capitalize())
43
+ elif key in ('uri', 'url', 'imageUrl', 'audioUrl') and isinstance(entry, str):
44
+ result[key] = public_uri(entry)
45
+ else:
46
+ result[key] = _review_value(entry)
47
+ return result
48
+ if isinstance(value, list):
49
+ return [_review_value(entry) for entry in value]
50
+ if isinstance(value, str) and value.lower().startswith('data:'):
51
+ return _inline_description(value)
52
+ return value
53
+
54
+
55
+ def review_json(value):
56
+ return json.dumps(_review_value(value), ensure_ascii=False, indent=2)
57
+
58
+
59
+ def _annotations(block):
60
+ annotations = block.get('annotations')
61
+ if not isinstance(annotations, dict):
62
+ return ''
63
+ public = {}
64
+ audience = annotations.get('audience')
65
+ if isinstance(audience, list) and all(isinstance(v, str) and v in ('user', 'assistant') for v in audience):
66
+ public['audience'] = audience
67
+ priority = annotations.get('priority')
68
+ if isinstance(priority, (int, float)) and not isinstance(priority, bool):
69
+ public['priority'] = priority
70
+ if isinstance(annotations.get('lastModified'), str):
71
+ public['lastModified'] = annotations['lastModified']
72
+ return '\nAnnotations: ' + review_json(public) if public else ''
73
+
74
+
75
+ def _text(value):
76
+ return value if isinstance(value, str) else '[Unavailable text content]'
77
+
78
+
79
+ def content_text(block):
80
+ """MCP content is arbitrary JSON; dynamic content has separate tagged shapes."""
81
+ if not isinstance(block, dict):
82
+ return '[Unsupported content block]'
83
+ kind = block.get('type')
84
+ if kind in ('text', 'inputText'):
85
+ text = 'Text\n' + _text(block.get('text'))
86
+ elif kind in ('image', 'audio'):
87
+ label = kind.capitalize()
88
+ mime = block.get('mimeType') if isinstance(block.get('mimeType'), str) else 'unspecified MIME type'
89
+ data = block.get('data')
90
+ payload = f'inline payload {len(data)} characters' if isinstance(data, str) else 'no inline payload'
91
+ text = f'[{label}: {mime}; {payload}]'
92
+ elif kind in ('inputImage', 'inputAudio'):
93
+ label, key = ('Image', 'imageUrl') if kind == 'inputImage' else ('Audio', 'audioUrl')
94
+ uri = public_uri(block.get(key), label)
95
+ text = uri if uri.startswith(f'[{label}:') else f'[{label}: {uri}]'
96
+ elif kind in ('resource_link', 'resourceLink'):
97
+ lines = ['Resource link', 'URI: ' + public_uri(block.get('uri'), 'Resource')]
98
+ for key in ('name', 'title', 'description', 'mimeType'):
99
+ if isinstance(block.get(key), str):
100
+ lines.append(key + ': ' + block[key])
101
+ if isinstance(block.get('size'), (int, float)) and not isinstance(block['size'], bool):
102
+ lines.append('size: ' + str(block['size']))
103
+ text = '\n'.join(lines)
104
+ elif kind == 'resource':
105
+ resource = block.get('resource')
106
+ if not isinstance(resource, dict):
107
+ text = '[Unavailable embedded resource]'
108
+ else:
109
+ lines = ['Embedded resource', 'URI: ' + public_uri(resource.get('uri'), 'Resource')]
110
+ if isinstance(resource.get('mimeType'), str):
111
+ lines.append('MIME type: ' + resource['mimeType'])
112
+ if 'text' in resource:
113
+ lines.extend(['Text:', _text(resource['text'])])
114
+ if 'blob' in resource:
115
+ lines.append(_inline_description(resource['blob'], 'Resource blob'))
116
+ text = '\n'.join(lines)
117
+ else:
118
+ label = kind[:80] if isinstance(kind, str) else 'unknown'
119
+ return '[Unsupported content type: ' + label + ']'
120
+ return text + _annotations(block)
121
+
122
+
123
+ def tool_text(item):
124
+ dynamic = item.get('type') == 'dynamicToolCall'
125
+ scope = item.get('namespace') if dynamic else item.get('server')
126
+ tool = item.get('tool') if isinstance(item.get('tool'), str) else '(unnamed)'
127
+ name = str(scope) + '.' + tool if scope else tool
128
+ lines = [('Dynamic tool: ' if dynamic else 'MCP tool: ') + name,
129
+ 'Status: ' + str(item.get('status', 'unknown'))]
130
+ if item.get('durationMs') is not None:
131
+ lines.append('Duration: ' + str(item['durationMs']) + ' ms')
132
+ if dynamic and item.get('success') is not None:
133
+ lines.append('Success: ' + review_json(item['success']))
134
+ error = item.get('error')
135
+ if error is not None:
136
+ message = error.get('message') if isinstance(error, dict) else None
137
+ lines.append('Error: ' + (_text(message) if message is not None else '[Unavailable error message]'))
138
+ lines.extend(['Arguments:', review_json(item.get('arguments'))])
139
+ result = item.get('result')
140
+ content = item.get('contentItems') if dynamic else result.get('content') if isinstance(result, dict) else None
141
+ if content is not None:
142
+ if isinstance(content, list):
143
+ if not content:
144
+ lines.append('Content: no content blocks')
145
+ for index, block in enumerate(content, 1):
146
+ lines.append('Content ' + str(index) + ' — ' + content_text(block))
147
+ else:
148
+ lines.append('[Unsupported content list]')
149
+ if not dynamic and isinstance(result, dict) and 'structuredContent' in result:
150
+ lines.extend(['Structured content:', review_json(result['structuredContent'])])
151
+ return '\n'.join(lines)
152
+
153
+
154
+ def _reported(value, fallback='unknown'):
155
+ return value if isinstance(value, str) and value else fallback
156
+
157
+
158
+ def _collaboration_output(value):
159
+ if isinstance(value, str):
160
+ return value
161
+ if isinstance(value, (dict, list)):
162
+ return review_json(value)
163
+ return '[Unavailable output]'
164
+
165
+
166
+ def collaboration_text(item):
167
+ """Format only the public fields carried by a native collaboration item."""
168
+ if not isinstance(item, dict):
169
+ return '[Unsupported collaboration item]'
170
+ kind = item.get('type')
171
+ if kind == 'subAgentActivity':
172
+ lines = ['Subagent activity', 'Kind: ' + _reported(item.get('kind')),
173
+ 'Agent path: ' + _reported(item.get('agentPath'), 'unavailable'),
174
+ 'Agent thread: ' + _reported(item.get('agentThreadId'), 'unavailable')]
175
+ # These fields are resolved at creation, rather than tool requests.
176
+ for key, label in (('model', 'Resolved model'), ('reasoningEffort', 'Resolved effort')):
177
+ if isinstance(item.get(key), str) and item[key]:
178
+ lines.append(label + ': ' + item[key])
179
+ return '\n'.join(lines)
180
+ if kind != 'collabAgentToolCall':
181
+ return '[Unsupported collaboration item]'
182
+
183
+ lines = ['Collaboration tool: ' + _reported(item.get('tool')),
184
+ 'Status: ' + _reported(item.get('status')),
185
+ 'Source thread: ' + _reported(item.get('senderThreadId'), 'unavailable')]
186
+ for key, label in (('model', 'Requested model'), ('reasoningEffort', 'Requested effort')):
187
+ if isinstance(item.get(key), str) and item[key]:
188
+ lines.append(label + ': ' + item[key])
189
+ if item.get('prompt') is not None:
190
+ prompt = item['prompt'] if isinstance(item['prompt'], str) else '[Unavailable text content]'
191
+ lines.extend(['Prompt sent:', prompt])
192
+
193
+ states = item.get('agentsStates')
194
+ states = {key: value for key, value in states.items() if key != '_meta'} if isinstance(states, dict) else {}
195
+ receivers = item.get('receiverThreadIds')
196
+ receivers = [value for value in receivers if isinstance(value, str) and value] if isinstance(receivers, list) else []
197
+ # Keep target order and include states reported outside the target list.
198
+ receivers += [value for value in states if isinstance(value, str) and value and value not in receivers]
199
+ if not receivers:
200
+ lines.append('Receiver threads: none reported')
201
+ for receiver in receivers:
202
+ state = states.get(receiver)
203
+ lines.append('Receiver thread: ' + receiver)
204
+ lines.append('Last known status: ' + _reported(state.get('status') if isinstance(state, dict) else None, 'unavailable'))
205
+ if isinstance(state, dict) and state.get('message') is not None:
206
+ lines.extend(['Output:', _collaboration_output(state['message'])])
207
+ return '\n'.join(lines)
@@ -0,0 +1,255 @@
1
+ """Private prepared follow-ups and explicit, revision-bound admission receipts."""
2
+ from contextlib import contextmanager
3
+ import uuid
4
+
5
+
6
+ MAX_FOLLOWUP_CHARS = 200_000
7
+
8
+
9
+ class FollowupConflict(ValueError):
10
+ def __init__(self, current):
11
+ self.current = current
12
+ super().__init__('Follow-up preparation changed. Review the current entry or reservation.')
13
+
14
+
15
+ def _identifier(value):
16
+ if not isinstance(value, str) or not value:
17
+ raise ValueError('Select a follow-up entry')
18
+
19
+
20
+ def _revision(value):
21
+ if type(value) is not int or value < 1:
22
+ raise ValueError('Use the entry revision you reviewed')
23
+
24
+
25
+ def _preparation(text, mode):
26
+ if not isinstance(text, str) or not text.strip() or len(text) > MAX_FOLLOWUP_CHARS:
27
+ raise ValueError(f'Enter a follow-up task of 1–{MAX_FOLLOWUP_CHARS:,} characters')
28
+ if mode not in ('native', 'plan'):
29
+ raise ValueError('Choose Work or Plan mode')
30
+
31
+
32
+ @contextmanager
33
+ def _transaction(store, session):
34
+ with store.lock, store.db:
35
+ store.db.execute('BEGIN IMMEDIATE')
36
+ if not isinstance(session, str) or not session or session == 'native-catalog':
37
+ raise ValueError('Select an existing project session')
38
+ if store.db.execute('SELECT 1 FROM sessions WHERE id=?', (session,)).fetchone() is None:
39
+ raise ValueError('Session not found')
40
+ for statement in ('''CREATE TABLE IF NOT EXISTS followups(
41
+ id TEXT PRIMARY KEY NOT NULL, session_id TEXT NOT NULL,
42
+ text TEXT NOT NULL, mode TEXT NOT NULL, position INTEGER NOT NULL,
43
+ revision INTEGER NOT NULL, state TEXT NOT NULL
44
+ CHECK(state IN ('queued','reserved','needs_review')))''',
45
+ 'CREATE INDEX IF NOT EXISTS followups_order ON followups(session_id,position,id)',
46
+ '''CREATE TABLE IF NOT EXISTS followup_reservations(
47
+ session_id TEXT PRIMARY KEY NOT NULL, token TEXT UNIQUE NOT NULL,
48
+ entry_id TEXT NOT NULL, entry_revision INTEGER NOT NULL,
49
+ text TEXT NOT NULL, mode TEXT NOT NULL,
50
+ state TEXT NOT NULL CHECK(state IN ('reserved','unknown')))'''):
51
+ store.db.execute(statement)
52
+ yield
53
+
54
+
55
+ def _as_entry(row):
56
+ return dict(zip(('id', 'text', 'mode', 'order', 'revision', 'state'), row))
57
+
58
+
59
+ def _entries(store, session):
60
+ return [_as_entry(row) for row in store.db.execute(
61
+ 'SELECT id,text,mode,position,revision,state FROM followups WHERE session_id=? ORDER BY position,id',
62
+ (session,))]
63
+
64
+
65
+ def _entry(store, session, identifier):
66
+ _identifier(identifier)
67
+ row = store.db.execute(
68
+ 'SELECT id,text,mode,position,revision,state FROM followups WHERE session_id=? AND id=?',
69
+ (session, identifier)).fetchone()
70
+ if row is None:
71
+ raise ValueError('Follow-up entry not found in this session')
72
+ return _as_entry(row)
73
+
74
+
75
+ def _reservation(store, session):
76
+ row = store.db.execute(
77
+ 'SELECT token,entry_id,entry_revision,text,mode,state FROM followup_reservations WHERE session_id=?',
78
+ (session,)).fetchone()
79
+ if row is None:
80
+ return None
81
+ return {'session_id': session, **dict(zip(
82
+ ('token', 'entry_id', 'revision', 'text', 'mode', 'state'), row))}
83
+
84
+
85
+ def _snapshot(store, session):
86
+ return {'entries': _entries(store, session), 'reservation': _reservation(store, session)}
87
+
88
+
89
+ def _renumber(store, session):
90
+ for position, entry in enumerate(_entries(store, session), 1):
91
+ store.db.execute('UPDATE followups SET position=? WHERE id=?', (position, entry['id']))
92
+
93
+
94
+ def _ids(values):
95
+ if not isinstance(values, list) or any(not isinstance(value, str) or not value for value in values):
96
+ raise ValueError('Use a list of follow-up entry IDs')
97
+ if len(values) != len(set(values)):
98
+ raise ValueError('Each follow-up entry must occur once')
99
+
100
+
101
+ def _expected_order(store, session, expected_order):
102
+ if expected_order is not None:
103
+ _ids(expected_order)
104
+ if expected_order != [entry['id'] for entry in _entries(store, session)]:
105
+ raise FollowupConflict(_snapshot(store, session))
106
+
107
+
108
+ def list_followups(store, session):
109
+ """Return preparation order/state; this never sends or releases a reservation."""
110
+ with _transaction(store, session):
111
+ return _entries(store, session)
112
+
113
+
114
+ def followup_snapshot(store, session):
115
+ """Read entries and their admission receipt in one SQLite snapshot."""
116
+ with _transaction(store, session):
117
+ return _snapshot(store, session)
118
+
119
+
120
+ def add_followup(store, session, text, mode='native'):
121
+ _preparation(text, mode)
122
+ with _transaction(store, session):
123
+ position = store.db.execute(
124
+ 'SELECT coalesce(max(position),0)+1 FROM followups WHERE session_id=?', (session,)).fetchone()[0]
125
+ identifier = uuid.uuid4().hex
126
+ store.db.execute('INSERT INTO followups VALUES(?,?,?,?,?,?,?)',
127
+ (identifier, session, text, mode, position, 1, 'queued'))
128
+ return _entry(store, session, identifier)
129
+
130
+
131
+ def edit_followup(store, session, identifier, text, mode, expected_revision):
132
+ """Every deliberate edit advances preparation revision, even identical text."""
133
+ _preparation(text, mode)
134
+ _revision(expected_revision)
135
+ with _transaction(store, session):
136
+ current = _entry(store, session, identifier)
137
+ if current['revision'] != expected_revision:
138
+ raise FollowupConflict({'entry': current, 'reservation': _reservation(store, session)})
139
+ store.db.execute('UPDATE followups SET text=?,mode=?,revision=revision+1 WHERE id=?',
140
+ (text, mode, identifier))
141
+ return _entry(store, session, identifier)
142
+
143
+
144
+ def remove_followup(store, session, identifier, expected_revision):
145
+ _revision(expected_revision)
146
+ with _transaction(store, session):
147
+ current = _entry(store, session, identifier)
148
+ if current['revision'] != expected_revision:
149
+ raise FollowupConflict({'entry': current, 'reservation': _reservation(store, session)})
150
+ if current['state'] != 'queued':
151
+ raise ValueError('Review the pending admission receipt before removing this preparation')
152
+ store.db.execute('DELETE FROM followups WHERE id=?', (identifier,))
153
+ _renumber(store, session)
154
+ return {'removed': identifier}
155
+
156
+
157
+ def reorder_followups(store, session, identifiers, expected_order=None):
158
+ """Move reviewed preparations; an already reserved entry keeps its position."""
159
+ _ids(identifiers)
160
+ with _transaction(store, session):
161
+ _expected_order(store, session, expected_order)
162
+ entries = _entries(store, session)
163
+ if set(identifiers) != {entry['id'] for entry in entries}:
164
+ raise ValueError('Include every follow-up in this session exactly once')
165
+ current = {entry['id']: entry for entry in entries}
166
+ for position, identifier in enumerate(identifiers, 1):
167
+ entry = current[identifier]
168
+ if entry['state'] != 'queued' and entry['order'] != position:
169
+ raise ValueError('A pending admission keeps its position until reviewed')
170
+ for position, identifier in enumerate(identifiers, 1):
171
+ if current[identifier]['order'] != position:
172
+ store.db.execute('UPDATE followups SET position=?,revision=revision+1 WHERE id=?',
173
+ (position, identifier))
174
+ return _entries(store, session)
175
+
176
+
177
+ def clear_followups(store, session, expected_order=None):
178
+ """Clear queued preparation only; an unresolved admission remains reviewable."""
179
+ with _transaction(store, session):
180
+ _expected_order(store, session, expected_order)
181
+ removed = [entry['id'] for entry in _entries(store, session) if entry['state'] == 'queued']
182
+ store.db.execute("DELETE FROM followups WHERE session_id=? AND state='queued'", (session,))
183
+ _renumber(store, session)
184
+ return {'removed': removed, 'entries': _entries(store, session),
185
+ 'reservation': _reservation(store, session)}
186
+
187
+
188
+ def pending_followup(store, session):
189
+ """Return an unconfirmed receipt snapshot, including after Store reopen."""
190
+ with _transaction(store, session):
191
+ return _reservation(store, session)
192
+
193
+
194
+ def reserve_followup(store, session, identifier=None, expected_revision=None, *, first_only=False):
195
+ """Explicitly capture one next entry; None means empty or already awaiting review.
196
+
197
+ Passing an entry ID requires its reviewed revision. Omitting both selects
198
+ the current first queued entry. Native turn admission remains the caller's job.
199
+ """
200
+ if (identifier is None) != (expected_revision is None):
201
+ raise ValueError('Select both the entry ID and its reviewed revision')
202
+ if identifier is not None:
203
+ _identifier(identifier)
204
+ _revision(expected_revision)
205
+ with _transaction(store, session):
206
+ if _reservation(store, session) is not None:
207
+ return None
208
+ if identifier is None:
209
+ entries = [entry for entry in _entries(store, session) if entry['state'] == 'queued']
210
+ if not entries:
211
+ return None
212
+ current = entries[0]
213
+ else:
214
+ current = _entry(store, session, identifier)
215
+ if current['revision'] != expected_revision:
216
+ raise FollowupConflict({'entry': current, 'reservation': None})
217
+ if current['state'] != 'queued':
218
+ raise ValueError('Review this entry before reserving it again')
219
+ if first_only and current['id'] != _entries(store, session)[0]['id']:
220
+ raise FollowupConflict(_snapshot(store, session))
221
+ token = uuid.uuid4().hex
222
+ store.db.execute("UPDATE followups SET state='reserved' WHERE id=?", (current['id'],))
223
+ store.db.execute('INSERT INTO followup_reservations VALUES(?,?,?,?,?,?,?)',
224
+ (session, token, current['id'], current['revision'],
225
+ current['text'], current['mode'], 'reserved'))
226
+ return _reservation(store, session)
227
+
228
+
229
+ def record_followup_receipt(store, session, token, identifier, expected_revision, outcome):
230
+ """Resolve the exact captured version; unknown keeps a blocker for explicit review."""
231
+ _identifier(token)
232
+ _identifier(identifier)
233
+ _revision(expected_revision)
234
+ if outcome not in ('accepted', 'rejected', 'unknown'):
235
+ raise ValueError('Record accepted, rejected or unknown admission')
236
+ with _transaction(store, session):
237
+ reservation = _reservation(store, session)
238
+ if (reservation is None or reservation['token'] != token
239
+ or reservation['entry_id'] != identifier or reservation['revision'] != expected_revision):
240
+ raise FollowupConflict(_snapshot(store, session))
241
+ current = _entry(store, session, identifier)
242
+ if outcome == 'unknown':
243
+ store.db.execute("UPDATE followups SET state='needs_review' WHERE id=?", (identifier,))
244
+ store.db.execute("UPDATE followup_reservations SET state='unknown' WHERE session_id=?", (session,))
245
+ return {'outcome': outcome, 'consumed': False, 'entry': _entry(store, session, identifier),
246
+ 'reservation': _reservation(store, session)}
247
+ consumed = outcome == 'accepted' and current['revision'] == expected_revision
248
+ if consumed:
249
+ store.db.execute('DELETE FROM followups WHERE id=?', (identifier,))
250
+ else:
251
+ store.db.execute("UPDATE followups SET state='queued' WHERE id=?", (identifier,))
252
+ store.db.execute('DELETE FROM followup_reservations WHERE session_id=?', (session,))
253
+ _renumber(store, session)
254
+ return {'outcome': outcome, 'consumed': consumed,
255
+ 'entry': None if consumed else _entry(store, session, identifier), 'reservation': None}
codex_desk/handoff.py ADDED
@@ -0,0 +1,68 @@
1
+ """Build an editable handoff from visible native task evidence."""
2
+ from .evidence import collaboration_text, review_json, tool_text
3
+
4
+ def visible_text(item):
5
+ kind = item.get('type')
6
+ if kind == 'userMessage':
7
+ return 'User\n' + '\n'.join(c.get('text', '') for c in item.get('content', []) if c.get('type') == 'text')
8
+ if kind == 'agentMessage':
9
+ return 'Codex\n' + item.get('text', '')
10
+ if kind == 'commandExecution':
11
+ output, exit_code = item.get('aggregatedOutput'), item.get('exitCode')
12
+ return ('Command\n' + item.get('command', '')
13
+ + '\nStatus: ' + (item.get('status') or 'unknown')
14
+ + '\nExit: ' + (str(exit_code) if exit_code is not None else 'not reported')
15
+ + '\n' + (output if isinstance(output, str) else '[No command output reported.]'))
16
+ if kind in ('mcpToolCall', 'dynamicToolCall'):
17
+ return tool_text(item)
18
+ if kind in ('collabAgentToolCall', 'subAgentActivity'):
19
+ return collaboration_text(item)
20
+ if kind == 'fileChange':
21
+ return 'File changes\n' + '\n'.join(c.get('path', '') + '\n' + c.get('diff', '') for c in item.get('changes', []))
22
+ return ''
23
+
24
+
25
+ def turn_text(turn):
26
+ """Keep the reported outcome after a turn's partial messages and tools."""
27
+ status, error = turn.get('status'), turn.get('error')
28
+ fields = {key: error[key] for key in ('message', 'codexErrorInfo', 'additionalDetails')
29
+ if key in error and error[key] is not None} if isinstance(error, dict) else {}
30
+ if not (isinstance(status, str) and status) and not fields:
31
+ return ''
32
+ lines = ['Turn ' + str(turn.get('id') or 'unreported')]
33
+ if isinstance(status, str) and status:
34
+ lines.append('Status: ' + status)
35
+ if fields:
36
+ lines.extend(['Native error:', review_json(fields)])
37
+ return '\n'.join(lines)
38
+
39
+
40
+ def build_handoff(thread, max_chars=24000):
41
+ header = ('Continue the project task using this reviewed handoff. Check the current workspace before making further changes.\n\n'
42
+ + 'Source thread: ' + thread['id'] + '\nWorking directory: ' + thread.get('cwd', '')
43
+ + '\nSource provider: ' + thread.get('modelProvider', '') + '\n\n'
44
+ + 'Goal / current request:\n[Edit this to state what you want completed next.]\n\n'
45
+ + 'Completed:\n[Review the evidence below and record the useful completed work.]\n\n'
46
+ + 'Remaining / constraints:\n[Edit before running.]\n\nVisible task evidence:\n')
47
+ blocks = []
48
+ for turn in thread.get('turns', []):
49
+ for item in turn.get('items', []):
50
+ text = visible_text(item)
51
+ if text:
52
+ blocks.append(('Item ' + item['id'] + '\n' + text))
53
+ outcome = turn_text(turn)
54
+ if outcome:
55
+ blocks.append(outcome)
56
+ kept, size, omitted = [], len(header), 0
57
+ # Keep recent evidence in its original order, with an explicit cutoff.
58
+ for block in reversed(blocks):
59
+ available = max_chars - size - 240
60
+ if available <= 0:
61
+ omitted += 1
62
+ continue
63
+ if len(block) > available:
64
+ block = block[:available] + '\n[This item was shortened at the handoff character limit.]'
65
+ kept.insert(0, block)
66
+ size += len(block) + 8
67
+ cutoff = '\n\nEarlier visible items omitted: ' + str(omitted) + '. Character budget: ' + str(max_chars) + '.\n'
68
+ return header + '\n\n---\n\n'.join(kept) + cutoff