ChatTask 0.1.2__tar.gz → 0.1.5__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 (46) hide show
  1. {chattask-0.1.2/src/ChatTask.egg-info → chattask-0.1.5}/PKG-INFO +13 -1
  2. {chattask-0.1.2 → chattask-0.1.5}/README.md +10 -0
  3. {chattask-0.1.2 → chattask-0.1.5}/pyproject.toml +2 -2
  4. {chattask-0.1.2 → chattask-0.1.5/src/ChatTask.egg-info}/PKG-INFO +13 -1
  5. {chattask-0.1.2 → chattask-0.1.5}/src/ChatTask.egg-info/SOURCES.txt +8 -0
  6. {chattask-0.1.2 → chattask-0.1.5}/src/ChatTask.egg-info/requires.txt +2 -0
  7. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/__init__.py +3 -3
  8. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/agent_tasks.py +8 -3
  9. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/auth.py +5 -1
  10. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/broker.py +36 -10
  11. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/cli.py +133 -0
  12. chattask-0.1.5/src/chattask/codex_tasks.py +390 -0
  13. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/config.py +6 -1
  14. chattask-0.1.5/src/chattask/durable.py +808 -0
  15. chattask-0.1.5/src/chattask/durable_archive.py +90 -0
  16. chattask-0.1.5/src/chattask/durable_research.py +67 -0
  17. chattask-0.1.5/src/chattask/overleaf_native.mjs +279 -0
  18. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/package_publication.py +154 -40
  19. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/package_service.py +106 -2
  20. chattask-0.1.5/src/chattask/research.py +631 -0
  21. chattask-0.1.5/src/chattask/research_compiler.py +161 -0
  22. chattask-0.1.5/src/chattask/research_discovery.py +76 -0
  23. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/service.py +45 -2
  24. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/settings.py +47 -2
  25. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/web.py +225 -11
  26. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/web_static/app.js +275 -5
  27. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/web_static/index.html +64 -0
  28. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/web_static/style.css +1 -0
  29. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/workflow.py +1 -1
  30. chattask-0.1.5/src/chattask/workspace_analysis.py +579 -0
  31. {chattask-0.1.2 → chattask-0.1.5}/tests/test_version.py +1 -1
  32. chattask-0.1.2/src/chattask/codex_tasks.py +0 -239
  33. {chattask-0.1.2 → chattask-0.1.5}/LICENSE +0 -0
  34. {chattask-0.1.2 → chattask-0.1.5}/setup.cfg +0 -0
  35. {chattask-0.1.2 → chattask-0.1.5}/src/ChatTask.egg-info/dependency_links.txt +0 -0
  36. {chattask-0.1.2 → chattask-0.1.5}/src/ChatTask.egg-info/entry_points.txt +0 -0
  37. {chattask-0.1.2 → chattask-0.1.5}/src/ChatTask.egg-info/top_level.txt +0 -0
  38. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/executor.py +0 -0
  39. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/package_plan.py +0 -0
  40. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/package_template.py +0 -0
  41. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/package_validation.py +0 -0
  42. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/release.py +0 -0
  43. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/source.py +0 -0
  44. {chattask-0.1.2 → chattask-0.1.5}/src/chattask/tool_client.py +0 -0
  45. {chattask-0.1.2 → chattask-0.1.5}/tests/test_cli.py +0 -0
  46. {chattask-0.1.2 → chattask-0.1.5}/tests/test_docs_deployment.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ChatTask
3
- Version: 0.1.2
3
+ Version: 0.1.5
4
4
  Summary: ChatTask: a ChatArch Python package.
5
5
  Author-email: ChatArch <rex@chatarch.org>
6
6
  License-Expression: MIT
@@ -23,6 +23,8 @@ Requires-Dist: packaging<27,>=24
23
23
  Requires-Dist: tomli<3,>=2; python_version < "3.11"
24
24
  Provides-Extra: dev
25
25
  Requires-Dist: build; extra == "dev"
26
+ Requires-Dist: setuptools>=61.0; extra == "dev"
27
+ Requires-Dist: wheel; extra == "dev"
26
28
  Requires-Dist: pytest; extra == "dev"
27
29
  Requires-Dist: twine; extra == "dev"
28
30
  Provides-Extra: web
@@ -53,8 +55,18 @@ ChatTask 从 0.1.0 版本起提供可复用的任务模板、受信 Git 源码
53
55
 
54
56
  ChatTask 的主模型是 **任务 → Codex + Sandbox → 结果**。任务说明和所选镜像决定工作内容;发包只是示例,不是执行器的固定步骤。当前源码提供 `chattask run` 和受站点登录保护的 `/api/agent/tasks`,结果保存原生事件、产物摘要和 Sandbox 回收证据。镜像预装 infra,运行时 env 只注入服务端选择的模型/工具凭据;优先使用短期受限网关,不把原始 GitHub/PyPI 凭据交给 guest。参见[通用任务、Python 发包模板与网关边界](docs/tasks.md)。源码能力不等于 PyPI 或线上已更新。
55
57
 
58
+ ### 长期任务候选
59
+
60
+ “长期任务”视图和 `chattask task` 命令保存稳定 Task 与逐轮 Run;独立 `chattask worker --env-profile site --operator operator` 处理队列。每轮保存受限的工作区与原生 Codex 会话检查点,后续轮次在新 Sandbox 原生接续。暂停是排队前或本轮结束时的协作式操作。生产部署须单独核验真实镜像、网关、原服务和浏览器;详见[长期任务合约](docs/tasks.md#长期任务候选)。
61
+
62
+ 显式选择 `research` 时,可提交已核对来源记录,也可通过受限的 arXiv 摘要自动检索创建;后者只保存摘要,不代表读过论文全文。受信 worker 在本轮原生执行及清理通过后,将 `result/research/main.tex` 等文件发布到配置的原 Overleaf 工程并核对源码;PDF 由独立隔离容器使用原服务镜像和只读公共 TeX 工具链编译,PDF/源码回读归入本轮产物。未知外部写入或编译清理结果保持阻塞,需显式同操作核对。普通开发任务不依赖 Overleaf 配置。
63
+
56
64
  ## 从源码使用
57
65
 
66
+ ### Workspace 材料分析
67
+
68
+ 从 0.1.4 起,受信 Workspace 可创建资料快照、单独确认运行,并回读真实模型生成的摘要校验报告。Task 页面「材料分析」显示任务来源与 Run 历史。这是只读材料执行器,不调用工具或读取宿主文件,也不会把报告完成标成原建议完成;配置、认证与 HTTP 合约见[材料分析接入](docs/workspace.md)。
69
+
58
70
  ```bash
59
71
  python -m pip install -e '.[web,dev]'
60
72
  chattask --tree
@@ -13,8 +13,18 @@ ChatTask 从 0.1.0 版本起提供可复用的任务模板、受信 Git 源码
13
13
 
14
14
  ChatTask 的主模型是 **任务 → Codex + Sandbox → 结果**。任务说明和所选镜像决定工作内容;发包只是示例,不是执行器的固定步骤。当前源码提供 `chattask run` 和受站点登录保护的 `/api/agent/tasks`,结果保存原生事件、产物摘要和 Sandbox 回收证据。镜像预装 infra,运行时 env 只注入服务端选择的模型/工具凭据;优先使用短期受限网关,不把原始 GitHub/PyPI 凭据交给 guest。参见[通用任务、Python 发包模板与网关边界](docs/tasks.md)。源码能力不等于 PyPI 或线上已更新。
15
15
 
16
+ ### 长期任务候选
17
+
18
+ “长期任务”视图和 `chattask task` 命令保存稳定 Task 与逐轮 Run;独立 `chattask worker --env-profile site --operator operator` 处理队列。每轮保存受限的工作区与原生 Codex 会话检查点,后续轮次在新 Sandbox 原生接续。暂停是排队前或本轮结束时的协作式操作。生产部署须单独核验真实镜像、网关、原服务和浏览器;详见[长期任务合约](docs/tasks.md#长期任务候选)。
19
+
20
+ 显式选择 `research` 时,可提交已核对来源记录,也可通过受限的 arXiv 摘要自动检索创建;后者只保存摘要,不代表读过论文全文。受信 worker 在本轮原生执行及清理通过后,将 `result/research/main.tex` 等文件发布到配置的原 Overleaf 工程并核对源码;PDF 由独立隔离容器使用原服务镜像和只读公共 TeX 工具链编译,PDF/源码回读归入本轮产物。未知外部写入或编译清理结果保持阻塞,需显式同操作核对。普通开发任务不依赖 Overleaf 配置。
21
+
16
22
  ## 从源码使用
17
23
 
24
+ ### Workspace 材料分析
25
+
26
+ 从 0.1.4 起,受信 Workspace 可创建资料快照、单独确认运行,并回读真实模型生成的摘要校验报告。Task 页面「材料分析」显示任务来源与 Run 历史。这是只读材料执行器,不调用工具或读取宿主文件,也不会把报告完成标成原建议完成;配置、认证与 HTTP 合约见[材料分析接入](docs/workspace.md)。
27
+
18
28
  ```bash
19
29
  python -m pip install -e '.[web,dev]'
20
30
  chattask --tree
@@ -26,7 +26,7 @@ Documentation = "https://arch.gh.wzhecnu.cn/ChatTask/"
26
26
  chattask = "chattask.cli:main"
27
27
 
28
28
  [project.optional-dependencies]
29
- dev = ["build", "pytest", "twine"]
29
+ dev = ["build", "setuptools>=61.0", "wheel", "pytest", "twine"]
30
30
  web = ["fastapi>=0.133,<0.143", "uvicorn>=0.41,<0.55", "ChatLogin[web]>=0.2.0,<0.3.0", "ChatPyPI>=0.2.14,<0.3.0", "ChatGH>=0.2.14,<0.3.0"]
31
31
  docs = ["mkdocs>=1.6,<2.0", "mkdocs-material>=9.5,<9.7", "mkdocs-static-i18n>=1.2,<2.0", "mike>=2.0,<3.0"]
32
32
 
@@ -43,4 +43,4 @@ where = ["src"]
43
43
  include-package-data = true
44
44
 
45
45
  [tool.setuptools.package-data]
46
- chattask = ["web_static/*.html", "web_static/*.css", "web_static/*.js"]
46
+ chattask = ["web_static/*.html", "web_static/*.css", "web_static/*.js", "overleaf_native.mjs"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ChatTask
3
- Version: 0.1.2
3
+ Version: 0.1.5
4
4
  Summary: ChatTask: a ChatArch Python package.
5
5
  Author-email: ChatArch <rex@chatarch.org>
6
6
  License-Expression: MIT
@@ -23,6 +23,8 @@ Requires-Dist: packaging<27,>=24
23
23
  Requires-Dist: tomli<3,>=2; python_version < "3.11"
24
24
  Provides-Extra: dev
25
25
  Requires-Dist: build; extra == "dev"
26
+ Requires-Dist: setuptools>=61.0; extra == "dev"
27
+ Requires-Dist: wheel; extra == "dev"
26
28
  Requires-Dist: pytest; extra == "dev"
27
29
  Requires-Dist: twine; extra == "dev"
28
30
  Provides-Extra: web
@@ -53,8 +55,18 @@ ChatTask 从 0.1.0 版本起提供可复用的任务模板、受信 Git 源码
53
55
 
54
56
  ChatTask 的主模型是 **任务 → Codex + Sandbox → 结果**。任务说明和所选镜像决定工作内容;发包只是示例,不是执行器的固定步骤。当前源码提供 `chattask run` 和受站点登录保护的 `/api/agent/tasks`,结果保存原生事件、产物摘要和 Sandbox 回收证据。镜像预装 infra,运行时 env 只注入服务端选择的模型/工具凭据;优先使用短期受限网关,不把原始 GitHub/PyPI 凭据交给 guest。参见[通用任务、Python 发包模板与网关边界](docs/tasks.md)。源码能力不等于 PyPI 或线上已更新。
55
57
 
58
+ ### 长期任务候选
59
+
60
+ “长期任务”视图和 `chattask task` 命令保存稳定 Task 与逐轮 Run;独立 `chattask worker --env-profile site --operator operator` 处理队列。每轮保存受限的工作区与原生 Codex 会话检查点,后续轮次在新 Sandbox 原生接续。暂停是排队前或本轮结束时的协作式操作。生产部署须单独核验真实镜像、网关、原服务和浏览器;详见[长期任务合约](docs/tasks.md#长期任务候选)。
61
+
62
+ 显式选择 `research` 时,可提交已核对来源记录,也可通过受限的 arXiv 摘要自动检索创建;后者只保存摘要,不代表读过论文全文。受信 worker 在本轮原生执行及清理通过后,将 `result/research/main.tex` 等文件发布到配置的原 Overleaf 工程并核对源码;PDF 由独立隔离容器使用原服务镜像和只读公共 TeX 工具链编译,PDF/源码回读归入本轮产物。未知外部写入或编译清理结果保持阻塞,需显式同操作核对。普通开发任务不依赖 Overleaf 配置。
63
+
56
64
  ## 从源码使用
57
65
 
66
+ ### Workspace 材料分析
67
+
68
+ 从 0.1.4 起,受信 Workspace 可创建资料快照、单独确认运行,并回读真实模型生成的摘要校验报告。Task 页面「材料分析」显示任务来源与 Run 历史。这是只读材料执行器,不调用工具或读取宿主文件,也不会把报告完成标成原建议完成;配置、认证与 HTTP 合约见[材料分析接入](docs/workspace.md)。
69
+
58
70
  ```bash
59
71
  python -m pip install -e '.[web,dev]'
60
72
  chattask --tree
@@ -14,19 +14,27 @@ src/chattask/broker.py
14
14
  src/chattask/cli.py
15
15
  src/chattask/codex_tasks.py
16
16
  src/chattask/config.py
17
+ src/chattask/durable.py
18
+ src/chattask/durable_archive.py
19
+ src/chattask/durable_research.py
17
20
  src/chattask/executor.py
21
+ src/chattask/overleaf_native.mjs
18
22
  src/chattask/package_plan.py
19
23
  src/chattask/package_publication.py
20
24
  src/chattask/package_service.py
21
25
  src/chattask/package_template.py
22
26
  src/chattask/package_validation.py
23
27
  src/chattask/release.py
28
+ src/chattask/research.py
29
+ src/chattask/research_compiler.py
30
+ src/chattask/research_discovery.py
24
31
  src/chattask/service.py
25
32
  src/chattask/settings.py
26
33
  src/chattask/source.py
27
34
  src/chattask/tool_client.py
28
35
  src/chattask/web.py
29
36
  src/chattask/workflow.py
37
+ src/chattask/workspace_analysis.py
30
38
  src/chattask/web_static/app.js
31
39
  src/chattask/web_static/index.html
32
40
  src/chattask/web_static/style.css
@@ -11,6 +11,8 @@ tomli<3,>=2
11
11
 
12
12
  [dev]
13
13
  build
14
+ setuptools>=61.0
15
+ wheel
14
16
  pytest
15
17
  twine
16
18
 
@@ -1,6 +1,6 @@
1
1
  """ChatTask: explicit task execution, sessions and an optional browser adapter."""
2
2
 
3
- __version__ = "0.1.2"
3
+ __version__ = "0.1.5"
4
4
  __all__ = ["__version__", "TaskService", "TaskSettings", "create_app", "state_paths", "WorkflowService", "TaskStore"]
5
5
 
6
6
 
@@ -17,9 +17,9 @@ def __getattr__(name):
17
17
  raise AttributeError(name)
18
18
 
19
19
 
20
- def create_app(settings=None, *, service=None, workflow=None, agent_tasks=None):
20
+ def create_app(settings=None, *, service=None, workflow=None, agent_tasks=None, analysis=None, auth_adapter=None, durable_tasks=None):
21
21
  from .web import create_app as factory
22
- return factory(settings, service=service, workflow=workflow, agent_tasks=agent_tasks)
22
+ return factory(settings, service=service, workflow=workflow, agent_tasks=agent_tasks, analysis=analysis, auth_adapter=auth_adapter, durable_tasks=durable_tasks)
23
23
 
24
24
 
25
25
  def state_paths(*, home=None):
@@ -37,10 +37,15 @@ class AgentTaskService:
37
37
  return await self._create(owner,body,None)
38
38
 
39
39
  async def create_internal(self,owner,body,capability):
40
- if not isinstance(capability,dict) or capability.get('mode') not in ('prepare','publish') or not isinstance(capability.get('plan'),dict):
40
+ if not isinstance(capability,dict) or capability.get('mode') not in ('prepare','publish','verify') or not isinstance(capability.get('plan'),dict):
41
41
  raise ValueError('invalid internal capability')
42
42
  if capability['mode']=='prepare' and set(capability)!={'mode','plan'} or capability['mode']=='publish' and (set(capability)!={'mode','plan','spec','plan_sha256'} or not isinstance(capability['spec'],dict) or not isinstance(capability['plan_sha256'],str) or not re.fullmatch('[0-9a-f]{64}',capability['plan_sha256'])):
43
43
  raise ValueError('invalid internal capability')
44
+ if capability['mode']=='verify' and (set(capability)!={'mode','plan','spec','plan_sha256','source_task_id'} or
45
+ not isinstance(capability['spec'],dict) or not isinstance(capability['plan_sha256'],str) or
46
+ not re.fullmatch('[0-9a-f]{64}',capability['plan_sha256']) or
47
+ not isinstance(capability['source_task_id'],str) or not re.fullmatch('[a-f0-9]{32}',capability['source_task_id'])):
48
+ raise ValueError('invalid internal verify capability')
44
49
  return await self._create(owner,body,capability)
45
50
 
46
51
  async def _create(self,owner,body,capability):
@@ -67,7 +72,7 @@ class AgentTaskService:
67
72
  task={'id':ident,'owner':owner,'engine':'codex','template_id':'codex-task','template_revision':1,
68
73
  'request_id':request_id,'request_fingerprint':digest,'instructions':instructions,
69
74
  'image_profile':image,'status':'queued','created_at':now(),'updated_at':now(),
70
- 'steps':[{'kind':kind,'status':'pending'} for kind in ['prepare','codex','collect']],
75
+ 'steps':[{'kind':kind,'status':'pending'} for kind in (['sandbox','trusted_validation'] if capability and capability['mode']=='verify' else ['prepare','codex','collect'])],
71
76
  'result':None,'artifacts':[],'cleanup':None,'input_task_id':input_task_id,'capability':capability}
72
77
  self.store.put('runs',ident,task)
73
78
  self.tasks[ident]=asyncio.create_task(self._execute(ident))
@@ -96,7 +101,7 @@ class AgentTaskService:
96
101
  for item in result.get('artifacts',[]):
97
102
  clean={k:v for k,v in item.items() if k!='data'}
98
103
  self.store.put_artifact(ident,item['name'],item['data']);current['artifacts'].append(clean)
99
- for key in ['sandbox_id','runtime','codex_session_id','cleanup','error','diagnostic']:
104
+ for key in ['sandbox_id','runtime','codex_session_id','cleanup','credential_closure','error','diagnostic']:
100
105
  if key in result:current[key]=result[key]
101
106
  current['result']=result.get('final')
102
107
  cancelled=current['status']=='cancel_requested'
@@ -1,4 +1,5 @@
1
1
  """Optional shared ChatLogin adapter; no second authentication protocol."""
2
+ import json
2
3
  from urllib.parse import urlsplit
3
4
  from chatlogin import PasswordBackend,Principal,SessionManager,MemorySessionStore,hash_password
4
5
  from chatlogin.fastapi import CookieSettings,FastAPIAuth
@@ -8,7 +9,10 @@ from chatlogin.ui import LoginUI
8
9
  def create_auth(settings):
9
10
  if not settings.username or not settings.password:
10
11
  raise ValueError('Web serving requires CHATTASK_LOGIN_USERNAME and CHATTASK_LOGIN_PASSWORD')
11
- backend=PasswordBackend({settings.username:(Principal('site-operator','站点管理员'),hash_password(settings.password))})
12
+ users={settings.username:(Principal('site-operator','站点管理员'),hash_password(settings.password))}
13
+ for entry in json.loads(settings.login_users_json or '[]'):
14
+ users[entry['username']]=(Principal(entry['principal_id'],entry['display_name']),hash_password(entry['password']))
15
+ backend=PasswordBackend(users)
12
16
  return FastAPIAuth(backend,SessionManager(MemorySessionStore(max_sessions=128),instance='chattask',ttl=86400),
13
17
  origin=settings.origin,cookie=CookieSettings(name='sandbox_site_session',secure=urlsplit(settings.origin).scheme=='https'),
14
18
  ui=LoginUI(title='Sandbox',subtitle='任务实验台 · 使用统一站点账号登录后,运行任务或继续一个环境。',
@@ -67,7 +67,7 @@ class GatewayClient:
67
67
  def create(self,request_id,mode,plan):
68
68
  if not isinstance(request_id,str) or not re.fullmatch(r'[a-f0-9]{32}',request_id):
69
69
  raise ValueError('task ID required')
70
- if mode not in ('generic','prepare','publish') or (mode=='generic') != (plan is None):
70
+ if mode not in ('generic','prepare','publish','verify') or (mode=='generic') != (plan is None):
71
71
  raise ValueError('invalid gateway session mode/policy')
72
72
  payload=json.dumps({'request_id':request_id,'mode':mode,'plan':plan},sort_keys=True,separators=(',',':')).encode()
73
73
  request=urllib.request.Request(self.origin+'/control/sessions',data=payload,method='POST',
@@ -100,18 +100,23 @@ class GatewayClient:
100
100
  ident=value['id']
101
101
  if ident!=request_id:
102
102
  raise ValueError()
103
- model=_https(value['model_base_url'])
104
103
  expected=self.origin+'/sessions/'+ident
105
- if value['model_base_url']!=expected+'/v1' or model!=expected+'/v1':
106
- raise ValueError()
107
104
  tool=value['tool_base_url']
108
- if mode=='generic':
109
- if tool or value['tool_access_token']:
105
+ if mode=='verify':
106
+ if value['model_base_url'] or value['model_access_token'] or tool!=expected or not isinstance(value['tool_access_token'],str) or not value['tool_access_token']:
107
+ raise ValueError()
108
+ model=''
109
+ else:
110
+ model=_https(value['model_base_url'])
111
+ if value['model_base_url']!=expected+'/v1' or model!=expected+'/v1':
112
+ raise ValueError()
113
+ if mode=='generic':
114
+ if tool or value['tool_access_token']:
115
+ raise ValueError()
116
+ elif tool!=expected or not value['tool_access_token']:
117
+ raise ValueError()
118
+ if not value['model_access_token'] or not isinstance(value['model_access_token'],str):
110
119
  raise ValueError()
111
- elif tool!=expected or not value['tool_access_token']:
112
- raise ValueError()
113
- if not value['model_access_token'] or not isinstance(value['model_access_token'],str):
114
- raise ValueError()
115
120
  raw_expiry=value['expires_at']
116
121
  expires=(datetime.fromtimestamp(raw_expiry,timezone.utc) if isinstance(raw_expiry,(int,float)) and not isinstance(raw_expiry,bool)
117
122
  else datetime.fromisoformat(raw_expiry.replace('Z','+00:00')))
@@ -120,3 +125,24 @@ class GatewayClient:
120
125
  return GatewaySession(ident,model,value['model_access_token'],tool,value['tool_access_token'],value['expires_at'])
121
126
  except (KeyError,TypeError,ValueError,OverflowError,AttributeError):
122
127
  raise GatewayUnknown('invalid gateway session response; retry same task ID') from None
128
+
129
+ def close(self,request_id):
130
+ if not isinstance(request_id,str) or not re.fullmatch(r'[a-f0-9]{32}',request_id):
131
+ raise ValueError('task ID required')
132
+ request=urllib.request.Request(self.origin+'/control/sessions/'+request_id+'/close',
133
+ data=b'',method='POST',headers={'Authorization':'Bearer '+self._token,
134
+ 'Content-Type':'application/json','Accept':'application/json'})
135
+ try:
136
+ with self._open(request,timeout=8) as response:
137
+ if response.status!=200 or int(response.headers.get('content-length','0'))>4096:
138
+ raise GatewayUnknown('gateway lease closure outcome unknown')
139
+ raw=response.read(4097)
140
+ if len(raw)>4096 or json.loads(raw)!={'closed':True}:
141
+ raise GatewayUnknown('gateway lease closure outcome unknown')
142
+ return {'closed':True}
143
+ except urllib.error.HTTPError as exc:
144
+ if 400<=exc.code<500:
145
+ raise RuntimeError('gateway lease closure denied') from None
146
+ raise GatewayUnknown('gateway lease closure outcome unknown') from None
147
+ except (urllib.error.URLError,TimeoutError,OSError,ValueError,TypeError):
148
+ raise GatewayUnknown('gateway lease closure outcome unknown') from None
@@ -98,6 +98,139 @@ def run_command(instructions,instructions_file,image_profile,request_id,input_ta
98
98
  if result['status']!='completed':raise click.exceptions.Exit(1)
99
99
 
100
100
 
101
+ def _durable_service(env_profile):
102
+ from .settings import load_settings
103
+ from .durable import configured_service
104
+ return configured_service(load_settings(profile=env_profile))
105
+
106
+
107
+ def _durable_call(operation, env_profile, owner, *args):
108
+ import json
109
+ from .durable import DurableConflict
110
+ try:
111
+ result = getattr(_durable_service(env_profile), operation)(owner, *args)
112
+ except (KeyError, ValueError, OSError, DurableConflict) as exc:
113
+ raise click.ClickException(str(exc)) from exc
114
+ click.echo(json.dumps(result, ensure_ascii=False))
115
+
116
+
117
+ @main.group(name='task')
118
+ def task_group():
119
+ """Control private long-term Tasks; rounds execute in a separate worker."""
120
+
121
+
122
+ @task_group.command(name='create')
123
+ @click.argument('instructions')
124
+ @click.option('--image-profile', required=True)
125
+ @click.option('--workflow', type=click.Choice(['development','research']), default='development', show_default=True)
126
+ @click.option('--sources-file', type=click.Path(exists=True, dir_okay=False, path_type=str), help='JSON array of caller-verified research source records.')
127
+ @click.option('--request-id', required=True)
128
+ @click.option('--owner', required=True, help='Trusted local principal identity.')
129
+ @click.option('-e', '--env-profile', default=None)
130
+ def durable_create(instructions, image_profile, workflow, sources_file, request_id, owner, env_profile):
131
+ """Queue the first round of a long-term Task."""
132
+ import json
133
+ from pathlib import Path
134
+ body={'instructions': instructions, 'image_profile': image_profile, 'request_id': request_id, 'workflow': workflow}
135
+ if sources_file:
136
+ try:body['source_records']=json.loads(Path(sources_file).read_text(encoding='utf-8'))
137
+ except (OSError,ValueError) as exc:raise click.ClickException('invalid research sources JSON file') from exc
138
+ _durable_call('create', env_profile, owner, body)
139
+
140
+
141
+ @task_group.command(name='list')
142
+ @click.option('--owner', required=True)
143
+ @click.option('-e', '--env-profile', default=None)
144
+ def durable_list(owner, env_profile):
145
+ """List Tasks visible to a trusted local principal."""
146
+ _durable_call('list', env_profile, owner)
147
+
148
+
149
+ @task_group.command(name='show')
150
+ @click.argument('task_id')
151
+ @click.option('--owner', required=True)
152
+ @click.option('-e', '--env-profile', default=None)
153
+ def durable_show(task_id, owner, env_profile):
154
+ """Show a Task and its immutable round history."""
155
+ import json
156
+ try:
157
+ service = _durable_service(env_profile)
158
+ click.echo(json.dumps({'task': service.get(owner, task_id), 'runs': service.runs(owner, task_id)}, ensure_ascii=False))
159
+ except (KeyError, ValueError, OSError) as exc:
160
+ raise click.ClickException(str(exc)) from exc
161
+
162
+
163
+ @task_group.command(name='resume')
164
+ @click.argument('task_id')
165
+ @click.argument('instructions')
166
+ @click.option('--request-id', required=True)
167
+ @click.option('--acknowledge-unknown', is_flag=True, help='Confirm inspection of interrupted round and external side effects.')
168
+ @click.option('--sources-file', type=click.Path(exists=True, dir_okay=False, path_type=str), help='Optional new caller-verified research source records.')
169
+ @click.option('--owner', required=True)
170
+ @click.option('-e', '--env-profile', default=None)
171
+ def durable_resume(task_id, instructions, request_id, acknowledge_unknown, sources_file, owner, env_profile):
172
+ """Queue an explicit new native Codex round from a verified checkpoint."""
173
+ import json
174
+ from pathlib import Path
175
+ body={'request_id': request_id, 'instructions': instructions, 'acknowledge_unknown': acknowledge_unknown}
176
+ if sources_file:
177
+ try:body['source_records']=json.loads(Path(sources_file).read_text(encoding='utf-8'))
178
+ except (OSError,ValueError) as exc:raise click.ClickException('invalid research sources JSON file') from exc
179
+ _durable_call('resume', env_profile, owner, task_id, body)
180
+
181
+
182
+ @task_group.command(name='pause')
183
+ @click.argument('task_id')
184
+ @click.option('--request-id', required=True)
185
+ @click.option('--owner', required=True)
186
+ @click.option('-e', '--env-profile', default=None)
187
+ def durable_pause(task_id, request_id, owner, env_profile):
188
+ """Pause queued work now or request a cooperative end-of-round pause."""
189
+ _durable_call('pause', env_profile, owner, task_id, {'request_id': request_id})
190
+
191
+
192
+ @task_group.command(name='complete')
193
+ @click.argument('task_id')
194
+ @click.option('--request-id', required=True)
195
+ @click.option('--owner', required=True)
196
+ @click.option('-e', '--env-profile', default=None)
197
+ def durable_complete(task_id, request_id, owner, env_profile):
198
+ """Mark an inactive long-term Task complete; history remains available."""
199
+ _durable_call('complete', env_profile, owner, task_id, {'request_id': request_id})
200
+
201
+
202
+ @task_group.command(name='reconcile-research')
203
+ @click.argument('task_id')
204
+ @click.option('--request-id', required=True)
205
+ @click.option('--acknowledge-unknown', is_flag=True,
206
+ help='Confirm inspection of the original project before retrying the same operation identity.')
207
+ @click.option('--owner', required=True)
208
+ @click.option('-e', '--env-profile', default=None)
209
+ def durable_reconcile_research(task_id, request_id, acknowledge_unknown, owner, env_profile):
210
+ """Queue explicit same-round Research readback/reconciliation."""
211
+ _durable_call('reconcile_research', env_profile, owner, task_id,
212
+ {'request_id': request_id, 'acknowledge_unknown': acknowledge_unknown})
213
+
214
+
215
+ @main.command(name='worker')
216
+ @click.option('--once', is_flag=True, help='Claim at most one queued round, then exit.')
217
+ @click.option('--operator', required=True, help='Trusted local operator starting this single writer.')
218
+ @click.option('-e', '--env-profile', required=True, help='Named ChatEnv runtime configuration.')
219
+ def durable_worker(once, operator, env_profile):
220
+ """Run the independent durable queue executor under a process-held lock."""
221
+ import asyncio, json
222
+ from .settings import load_settings
223
+ from .durable import run_worker
224
+ if not operator.strip():
225
+ raise click.UsageError('nonempty --operator required')
226
+ try:
227
+ result = asyncio.run(run_worker(load_settings(profile=env_profile), once=once))
228
+ except (ValueError, OSError, RuntimeError) as exc:
229
+ raise click.ClickException(str(exc)) from exc
230
+ if once:
231
+ click.echo(json.dumps(result, ensure_ascii=False))
232
+
233
+
101
234
 
102
235
  @main.group(name='package')
103
236
  def package_group():