@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.1.r1 → 0.0.0-dpv2.pdkadapt.plugin.0.1.10.r6

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.
package/README.md CHANGED
@@ -2,7 +2,9 @@
2
2
 
3
3
  这是独立 Python distribution,当前提供安装器、REST 控制面和客户端候选。源码与 DPV1 同仓,运行时不导入旧 cli/MCP;没有改动 DPV1 的入口、服务器或客户端。
4
4
 
5
- **尚未具备完整适配能力。** 真实工作站绑定、独立 SDK/EDA worker、旧 check/source-* 动作和四平台实际验收仍属 I01618。不要手工写 admitted=true 绕过未完成的 worker 准入。未配置准入时,业务提交明确返回 503;健康检查通过不表示可执行适配。
5
+ **尚未具备完整适配能力。** 真实工作站绑定、独立 SDK/EDA worker 和四平台实际验收仍属 I01618。不要手工写 admitted=true 绕过未完成的 worker 准入。未配置准入时,业务提交明确返回 503;健康检查通过不表示可执行适配。
6
+
7
+ 旧动作面映射(2026-11-29):`--action check` 映射 `POST /checks`,只查询不启动适配;复用判定只来自本账号自身的 DPV2 交付历史(服务器端跨主体复用保持关闭)。REUSED 必须携带与交付 tree 摘要一致的 `--use-client-revision`;有交付未确认时返回 `CLIENT_CONFIRMATION_REQUIRED`,无历史时按旧语义返回 `ADAPTATION_REQUIRED`/`REUSE_DISABLED`,check 恒以退出码 0 结束。`source-preview/confirm/install/publish` 保留旧参数校验(--vendor-dir、64 位 --options-hash/--revision、--token、--confirmed、--reason、--alias/--run-id),映射 `POST /sources/{previews,confirmations,installations,publications}`;DPV2 未提供公共工艺源复用通道,服务端以结构化 `SOURCE_REUSE_UNAVAILABLE` 应答(退出码 1),不伪造成功也不静默忽略。
6
8
 
7
9
  ## 本地安装与验证
8
10
 
@@ -14,7 +16,7 @@ PYTHONDONTWRITEBYTECODE=1 TED_EDA_MODE=LOCAL python3 -m pytest tests/test_dpv2*.
14
16
 
15
17
  `tools/verify_dpv2_npm.py --help` 提供可复现的 Linux npm 实际安装验收:必须指定新 prefix、协调仓、已有 Verdaccio、固定 Python 组件归档及其 SHA512、实际 vlink 二进制。只对新建的 loopback registry publish/view/download,保留收据并停止本轮服务;不向公共 npm 发布。测试实际私有解释器、runtime cli.sh、vlink REST、热启动与离线校验缓存,不包含 EDA 或 Win/Mac 实机验证。
16
18
 
17
- 服务使用 `python -m tedbrain_plugin_runtime.service --config FILE`,须由该 distribution 的环境运行。配置包括独立 state_root/public_root/releases_root 和账号验证 endpoint/appid/secret_file。账号 secret 必须是私有文件,不能使用现有 DPV1 token;服务签发独立 audience=dpv2 的 token。生产 TLS/资源配方和部署命令尚未交付。开发测试使用临时 loopback 和模拟账号验证源。
19
+ 服务使用 `python -m tedbrain_plugin_runtime.service --config FILE`,须由该 distribution 的环境运行。配置包括独立 state_root/public_root/releases_root 和账号验证 endpoint/appid/secret_file。账号 secret 必须是私有文件,不能使用现有 DPV1 token;服务签发独立 audience=dpv2 的 token。客户端只读复用 V1 vlink 保存的邀请码或 VLINK_INVITE_CODE,使用已有 auth/sessions 验证换取;首次认证与到期自动完成,V1 配置保持原状。生产 TLS/资源配方和部署命令尚未交付。开发测试使用临时 loopback 和模拟账号验证源。
18
20
 
19
21
  ## 安装和任务合同
20
22
 
@@ -26,5 +28,16 @@ PYTHONDONTWRITEBYTECODE=1 TED_EDA_MODE=LOCAL python3 -m pytest tests/test_dpv2*.
26
28
  - SQLite 保留 job/attempt/幂等键/事件。运行中版本固定;恢复必须确认旧执行停止、检查点兼容且原工艺范围一致。
27
29
  - guide.md 和 tedbrain skill 是发布候选文档,不代表其目标公网 URL 已可用。
28
30
 
31
+ ## 服务端工艺通告(I01928)
32
+
33
+ 适配成功(作业 SUCCEEDED 且交付为 INSTALLED)后,装到工作站的那棵结果树同时留在 DPV2 的 run store。worker 把它通告到一个只读的清单目录,供其它 DPV2 plugin(TED 作业 runner,I01920)读取。默认关闭;部署配置设置 `pdk_handoff_root` 后启用。
34
+
35
+ - 清单位置:`<pdk_handoff_root>/<subject>/<alias>.json`,原子写入,目录 0700。每个 (subject, alias) 只保留最新一次成功交付。
36
+ - 清单字段:`schema`、`kind=dpv2-pdk-handoff`、`plugin=pdkadapt`、`subject`、`alias`、`run_id`、`attempt`、`workstation_id`、`plugin_version`、`mode`、`cells`、`completion_sha256`、`tree{path,files,total_size,tree_sha256}`、`published_at`。
37
+ - 发布前重新计算结果树摘要,必须与引擎确认的交付一致。不一致或树缺失时写 `<state_root>/handoff-status.json`,不写清单,也不改变作业结果。
38
+ - 触发时机:worker 启动时全量同步一次;每次消费到成功回执后同步该 (subject, alias)。
39
+ - 清单不复制工艺内容,也不构成授权。使用方在使用前必须按同一规则重新校验 `tree_sha256`:按路径排序的 `{name,size,sha256}` 列表(排除根目录的 `.ted-result.json`,遇到符号链接即拒绝),对 `json.dumps(entries, sort_keys=True, separators=(",", ":"))` 的 UTF-8 字节取 SHA-256。
40
+ - 清单只说明服务端留有这棵树,不表示任何工作站当前安装的内容与它一致。
41
+
29
42
  公开 runtime、服务器独立部署和真实 full 适配必须另取实际证据。发布授权边界以项目规则为准。
30
43
 
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.1.r1"}
1
+ {"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.10.r6"}
@@ -0,0 +1,92 @@
1
+ """Read existing vlink onboarding state without changing the V1 installation."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import re
6
+ import stat
7
+ import time
8
+ from urllib.parse import urlsplit
9
+ from .installer import ContractError, atomic, canonical, loads
10
+
11
+
12
+ def config_root(environ=None, platform=None):
13
+ env=os.environ if environ is None else environ
14
+ if (os.name if platform is None else platform)=='nt':
15
+ profile=env.get('USERPROFILE') or (env.get('HOMEDRIVE','')+env.get('HOMEPATH',''))
16
+ base=Path(env['APPDATA']) if 'APPDATA' in env else Path(profile or '.')/'AppData/Roaming'
17
+ return base/'TED/vlink'
18
+ return Path(env.get('HOME') or '.')/'.config/.vlink'
19
+
20
+
21
+ def normalize(value):
22
+ code=value.strip().upper() if isinstance(value,str) else ''
23
+ if not re.fullmatch(r'TB-[A-Z0-9]{12}',code):
24
+ raise ContractError('V1 vlink credential invalid; use cli.sh login --stdin or repair VLINK_INVITE_CODE')
25
+ return code
26
+
27
+
28
+ def saved_credential():
29
+ # Match V1 precedence: even an empty explicit override must not fall through.
30
+ if 'VLINK_INVITE_CODE' in os.environ:return normalize(os.environ['VLINK_INVITE_CODE'])
31
+ root=config_root()
32
+ for relative in ('mcp/credentials.json','agents/tedbrain.json'):
33
+ path=root/relative
34
+ try:
35
+ info=path.lstat()
36
+ except FileNotFoundError:continue
37
+ except OSError:raise ContractError('Cannot read V1 vlink credential; use cli.sh login --stdin') from None
38
+ if (not stat.S_ISREG(info.st_mode) or info.st_size>65536 or
39
+ (os.name!='nt' and (info.st_uid!=os.geteuid() or info.st_mode & 0o077))):
40
+ raise ContractError('V1 vlink credential must be a private regular file; use cli.sh login --stdin')
41
+ try:
42
+ with path.open('rb') as stream:raw=stream.read(65537)
43
+ if len(raw)>65536:raise ValueError()
44
+ value=json.loads(raw)
45
+ return normalize(value.get('invitation_code') if isinstance(value,dict) else None)
46
+ except (OSError,ValueError):
47
+ raise ContractError('Cannot read V1 vlink credential; use cli.sh login --stdin') from None
48
+ return None
49
+
50
+
51
+ def save_session(root,envelope,origin):
52
+ body=envelope.get('body',{});token=body.get('access_token')
53
+ expires=body.get('expires_at');subject=body.get('subject')
54
+ if (envelope.get('outcome')!='response' or body.get('audience')!='dpv2' or
55
+ not isinstance(token,str) or not re.fullmatch(r'dpv2_[A-Za-z0-9_-]{32,128}',token) or
56
+ not isinstance(expires,(float,int)) or not isinstance(subject,str)):
57
+ raise ContractError('login returned an invalid DPV2 credential')
58
+ directory=root/'credentials';directory.mkdir(parents=True,exist_ok=True,mode=0o700)
59
+ atomic(directory/'token',token.encode())
60
+ metadata={'subject':subject,'expires_at':expires,'origin':origin}
61
+ atomic(directory/'session.json',canonical(metadata))
62
+ return metadata
63
+
64
+
65
+ def ensure_session(root,origin,exchange,force=False,allow_account_change=False):
66
+ token=root/'credentials/token';metadata=root/'credentials/session.json'
67
+ previous=None
68
+ if token.is_file() and metadata.is_file():
69
+ try:session=loads(metadata.read_bytes())
70
+ except (OSError,ContractError):raise ContractError('DPV2 session metadata unreadable; use cli.sh login --stdin') from None
71
+ previous=session.get('subject')
72
+ if session.get('origin')!=origin and not allow_account_change:raise ContractError('DPV2 session origin differs; login explicitly for the selected origin')
73
+ if not force and session.get('expires_at',0)>time.time()+30:return session
74
+ elif token.is_file() and not force:return None # Existing releases renew on a real 401.
75
+ parsed=urlsplit(origin)
76
+ official=origin in ('https://tedbrain.com','https://www.tedbrain.com')
77
+ loopback=(os.environ.get('DPV2_TEST_LOOPBACK')=='1' and parsed.scheme=='http' and
78
+ parsed.hostname in ('127.0.0.1','localhost','::1') and not parsed.username and not parsed.password)
79
+ if not (official or loopback):
80
+ raise ContractError('Automatic V1 login reuse requires the official TedBrain HTTPS origin')
81
+ credential=saved_credential()
82
+ if credential is None:
83
+ raise ContractError('login required: cli.sh login (or login --stdin); no saved V1 vlink credential')
84
+ code,envelope=exchange(credential)
85
+ if code:
86
+ status=envelope.get('status')
87
+ if envelope.get('outcome')=='response' and status in (401,403):
88
+ raise ContractError('Saved V1 vlink credential rejected; use cli.sh login --stdin')
89
+ raise ContractError('DPV2 login service unavailable; retry authentication later; business request was not replayed')
90
+ if previous and not allow_account_change and envelope.get('body',{}).get('subject')!=previous:
91
+ raise ContractError('Saved V1 account differs from the DPV2 session; run cli.sh login explicitly to switch accounts; original request was not retried')
92
+ return save_session(root,envelope,origin)
@@ -14,7 +14,8 @@ def validate(releases):
14
14
  return releases
15
15
 
16
16
 
17
- def render_sh(releases, origin='https://tedbrain.com'):
17
+ def render_sh(releases, origin='https://tedbrain.com', plugin='pdkadapt'):
18
+ if plugin not in ('pdkadapt','ted-runner'):raise ContractError('unregistered plugin')
18
19
  validate(releases); endpoint(origin)
19
20
  cases=[]
20
21
  for target in ('linux-x64','darwin-x64','darwin-arm64'):
@@ -62,10 +63,11 @@ if [ ! -f "$DPV2_BOOT/package/$DPV2_PY" ]; then
62
63
  fi
63
64
  "$DPV2_BOOT/package/$DPV2_PY" -E -s -B "$DPV2_BOOT/package/$DPV2_ENTRY" --root "$DPV2_ROOT" --origin @ORIGIN@ -- "$@"
64
65
  '''
65
- return script.replace('@CASES@','\n'.join(cases)).replace('@ORIGIN@',shell_quote(origin))
66
+ return script.replace('plugins/pdkadapt','plugins/'+plugin).replace('@CASES@','\n'.join(cases)).replace('@ORIGIN@',shell_quote(origin))
66
67
 
67
68
 
68
- def render_ps(releases, origin='https://tedbrain.com'):
69
+ def render_ps(releases, origin='https://tedbrain.com', plugin='pdkadapt'):
70
+ if plugin not in ('pdkadapt','ted-runner'):raise ContractError('unregistered plugin')
69
71
  validate(releases); endpoint(origin)
70
72
  item=releases['win32-x64']
71
73
  script='''$ErrorActionPreference = 'Stop'
@@ -105,4 +107,4 @@ exit $LASTEXITCODE
105
107
  '''
106
108
  values={'SHA':item['sha256'],'URL':item['url'],'PYTHON':'package/'+item['python'],'ENTRY':'package/'+item['entry'],'ORIGIN':origin}
107
109
  for key,value in values.items():script=script.replace('@'+key+'@',ps_quote(value))
108
- return script
110
+ return script.replace('plugins/pdkadapt','plugins/'+plugin)
@@ -4,16 +4,41 @@ import getpass
4
4
  import json
5
5
  import os
6
6
  from pathlib import Path
7
+ import re
7
8
  import secrets
8
9
  import subprocess
9
10
  import sys
10
11
  import tempfile
11
12
  import time
13
+ import unicodedata
12
14
  from .installer import ContractError, atomic, canonical, loads
13
15
  from .service import PREFIX
14
16
 
15
17
 
18
+ def exchange_session(root,credential):
19
+ # Persist only the request identity, never the reusable V1 secret.
20
+ directory=root/'credentials';directory.mkdir(parents=True,exist_ok=True,mode=0o700)
21
+ key=secrets.token_hex(16)
22
+ atomic(directory/'login-request.json',canonical({'path':'/api/dpv2/auth/sessions','request_id':key}))
23
+ return _request('POST','/api/dpv2/auth/sessions',{'credential':credential},key,False)
24
+
25
+
16
26
  def transport(method,path,body=None,key=None,authenticated=True):
27
+ from .auth import ensure_session
28
+ root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
29
+ origin=os.environ.get('DPV2_ORIGIN','https://tedbrain.com')
30
+ exchange=lambda credential:exchange_session(root,credential)
31
+ if authenticated:ensure_session(root,origin,exchange)
32
+ result=_request(method,path,body,key,authenticated)
33
+ # Only an explicit authentication rejection proves business was not run.
34
+ # Keep the original intent/key; never retry a timeout, 5xx or unknown result.
35
+ if authenticated and result[1].get('outcome')=='response' and result[1].get('status')==401:
36
+ ensure_session(root,origin,exchange,force=True)
37
+ result=_request(method,path,body,key,authenticated)
38
+ return result
39
+
40
+
41
+ def _request(method,path,body=None,key=None,authenticated=True):
17
42
  root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
18
43
  root.mkdir(parents=True,exist_ok=True,mode=0o700)
19
44
  vlink=os.environ.get('DPV2_VLINK')
@@ -43,6 +68,55 @@ def show(code,envelope):
43
68
  return code
44
69
 
45
70
 
71
+ SOURCE_ROUTES={'source-preview':'previews','source-confirm':'confirmations',
72
+ 'source-install':'installations','source-publish':'publications'}
73
+
74
+
75
+ def post_request(root,key,path,body):
76
+ """Persist every authenticated POST intent before invoking private vlink."""
77
+ journal=root/'requests';journal.mkdir(parents=True,exist_ok=True,mode=0o700)
78
+ record=journal/(key+'.json');intent={'path':path,'body':body,'request_id':key}
79
+ # Exclusive creation makes a reused key with different input fail before send.
80
+ try:
81
+ descriptor=os.open(record,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
82
+ except FileExistsError:
83
+ if loads(record.read_bytes())!=intent:raise ContractError('request ID belongs to different input')
84
+ else:
85
+ with os.fdopen(descriptor,'wb') as stream:
86
+ stream.write(canonical(intent));stream.flush();os.fsync(stream.fileno())
87
+ code,envelope=transport('POST',path,body,key)
88
+ print(json.dumps({'request_id':key,'request_record':str(record)},ensure_ascii=False),file=sys.stderr)
89
+ return code,envelope
90
+
91
+
92
+ def source_action(args,root,key):
93
+ """Old source-reuse face: DPV1 parameter validation, then the DPV2 REST answer.
94
+
95
+ The shared source channel stays closed on DPV2 (server-side reuse
96
+ boundary), so the service returns the defined structured status; the CLI
97
+ keeps DPV1's exit code for it instead of silently succeeding.
98
+ """
99
+ vendor=args.vendor_dir
100
+ if not vendor:raise ContractError('必须提供厂商 PDK 的绝对目录 --vendor-dir。')
101
+ if args.action=='source-publish':
102
+ reason=args.reason.strip()
103
+ if not 1<=len(reason)<=500 or any(unicodedata.category(char)=='Cc' for char in reason):
104
+ raise ContractError('请提供 1–500 字符的明确任务理由,说明本次源归档上传的用途,不得包含控制字符。')
105
+ if args.action in ('source-confirm','source-install'):
106
+ if not re.fullmatch('[0-9a-f]{64}',args.options_hash) or not re.fullmatch('[0-9a-f]{64}',args.revision) or not args.token:
107
+ raise ContractError('source-confirm/source-install 需要预览回执中的 --options-hash、--revision 和 --token。')
108
+ if not args.confirmed:
109
+ raise ContractError('公共工艺复用必须显式确认:请附加 --confirmed 表示用户已确认该配置。')
110
+ if args.action=='source-install' and (not args.alias or not args.run_id):
111
+ raise ContractError('source-install 需要交付目标 --alias 和本次复用作业的 --run-id。')
112
+ code,envelope=post_request(root,key,PREFIX+'/sources/'+SOURCE_ROUTES[args.action],
113
+ {'action':args.action,'vendor_dir':vendor})
114
+ if not code:
115
+ value=envelope.get('body') if envelope.get('outcome')=='response' else envelope
116
+ if isinstance(value,dict) and value.get('ok') is False:return show(1,envelope)
117
+ return show(code,envelope)
118
+
119
+
46
120
  def main(argv=None):
47
121
  argv=list(sys.argv[1:] if argv is None else argv)
48
122
  root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
@@ -90,15 +164,19 @@ def main(argv=None):
90
164
  return show(code,envelope)
91
165
  if argv and argv[0]=='login':
92
166
  p=argparse.ArgumentParser();p.add_argument('login');p.add_argument('--stdin',action='store_true');a=p.parse_args(argv)
167
+ from .auth import ensure_session,save_session
168
+ origin=os.environ.get('DPV2_ORIGIN','https://tedbrain.com')
169
+ if not a.stdin:
170
+ from .auth import saved_credential
171
+ if saved_credential() is not None:
172
+ session=ensure_session(root,origin,lambda credential:exchange_session(root,credential),force=True,allow_account_change=True)
173
+ print(json.dumps(dict(session,ok=True,reused_v1=True)));return 0
174
+ if not sys.stdin.isatty():raise ContractError('login required: no saved V1 vlink credential; use login --stdin')
93
175
  credential=sys.stdin.readline().strip() if a.stdin else getpass.getpass('TedBrain invitation code: ')
94
- code,envelope=transport('POST','/api/dpv2/auth/sessions',{'credential':credential},secrets.token_hex(16),authenticated=False)
176
+ code,envelope=exchange_session(root,credential)
95
177
  if code:return show(code,envelope)
96
- body=envelope['body'];token=body.get('access_token')
97
- if body.get('audience')!='dpv2' or not isinstance(token,str) or not token.startswith('dpv2_'):
98
- raise ContractError('login returned an invalid DPV2 credential')
99
- directory=root/'credentials';directory.mkdir(parents=True,exist_ok=True,mode=0o700)
100
- atomic(directory/'token',token.encode())
101
- print(json.dumps({'ok':True,'subject':body['subject'],'expires_at':body['expires_at']}));return 0
178
+ session=save_session(root,envelope,origin)
179
+ print(json.dumps(dict(session,ok=True)));return 0
102
180
  p=argparse.ArgumentParser(description='DPV2 pdkadapt plugin: asynchronous REST jobs')
103
181
  p.add_argument('--version',action='version',version='pdkadapt plugin '+os.environ.get('DPV2_RELEASE_VERSION','0.1.0'))
104
182
  p.add_argument('--action',choices=['check','start','status','resume','cancel','logs','source-preview','source-confirm','source-install','source-publish'],default='start')
@@ -123,6 +201,12 @@ def main(argv=None):
123
201
  if not __import__('re').fullmatch(r'[A-Za-z0-9._-]{1,128}',key):p.error('invalid --request-id')
124
202
  fields=['action','mode','vendor_dir','alias','foundry','arch','cells','run_id','from_step','layer_decision','layer_rule_decision','source_package','use_client_revision']
125
203
  request={name:getattr(args,name) for name in fields}
204
+ if args.action=='check':
205
+ # Old check face: pure reuse/prerequisite query; DPV1 answers it with
206
+ # exit 0 regardless of the reuse verdict, and so does DPV2.
207
+ code,envelope=post_request(root,key,PREFIX+'/checks',request)
208
+ return show(0 if not code else code,envelope)
209
+ if args.action in SOURCE_ROUTES:return source_action(args,root,key)
126
210
  if args.action=='start':
127
211
  if not args.workstation_id:p.error('start requires --workstation-id')
128
212
  path=PREFIX+'/jobs';body={'workstation_id':args.workstation_id,'request':request}
@@ -133,19 +217,8 @@ def main(argv=None):
133
217
  if not args.run_id:p.error('cancel requires --run-id')
134
218
  path=PREFIX+'/jobs/'+args.run_id+'/cancellations';body={}
135
219
  else:
136
- raise ContractError('This action has not been admitted on DPV2; it will not run through DPV1')
137
- journal=root/'requests';journal.mkdir(parents=True,exist_ok=True,mode=0o700)
138
- record=journal/(key+'.json');intent={'path':path,'body':body,'request_id':key}
139
- # Exclusive creation makes a reused key with different input fail before send.
140
- try:
141
- descriptor=os.open(record,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
142
- except FileExistsError:
143
- if loads(record.read_bytes())!=intent:raise ContractError('request ID belongs to different input')
144
- else:
145
- with os.fdopen(descriptor,'wb') as stream:
146
- stream.write(canonical(intent));stream.flush();os.fsync(stream.fileno())
147
- code,envelope=transport('POST',path,body,key)
148
- print(json.dumps({'request_id':key,'request_record':str(record)},ensure_ascii=False),file=sys.stderr)
220
+ raise ContractError('unsupported action for this request path')
221
+ code,envelope=post_request(root,key,path,body)
149
222
  if code or not args.wait:return show(code,envelope)
150
223
  body=envelope['body'];job=body['job_id']
151
224
  print(json.dumps(body,ensure_ascii=False),flush=True)
@@ -6,7 +6,20 @@ from pathlib import Path
6
6
  import sys
7
7
  import traceback
8
8
  from .installer import atomic,canonical,loads,ContractError
9
- from .jobs import Jobs
9
+ from .jobs import Conflict,Jobs
10
+
11
+ # Matches the transport's own DEFAULT_REQUEST_TIMEOUT_SECONDS: a single remote
12
+ # call can never silently outlast its request budget, so the supervisor's
13
+ # lease stays strictly above the longest honest silent window.
14
+ LEASE_FLOOR=600
15
+
16
+
17
+ def call_floor():
18
+ """The engine's per-call budget; the supervisor multiplies it for the lease."""
19
+ raw=os.environ.get('TED_ELINK_TIMEOUT','')
20
+ try:floor=int(raw)
21
+ except ValueError:floor=0
22
+ return floor if 0<floor<=24*3600 else LEASE_FLOOR
10
23
 
11
24
 
12
25
  class Cancelled(Exception):
@@ -17,6 +30,14 @@ def run(path):
17
30
  path=Path(path);spec=loads(path.read_bytes());row=spec['job'];config=spec['config'];station=spec['workstation']
18
31
  jobs=Jobs(Path(config['state_root'])/'jobs.sqlite3')
19
32
  request=loads(row['request']);directory=path.parent
33
+ # I01900 heartbeat lease: the engine renews at every tool boundary and
34
+ # every progress checkpoint. Renewal is best-effort against a supervisor
35
+ # that may have already reaped or cancelled this attempt; losing that race
36
+ # must not mask the original outcome.
37
+ floor=call_floor()
38
+ def beat():
39
+ try:jobs.beat(row['id'],row['attempt'],floor=floor)
40
+ except (Conflict,ContractError):pass
20
41
  # Only server-pinned inventories can bind the runtime. Remote home and
21
42
  # connection come from the authenticated enrollment, never job parameters.
22
43
  executor=config['executor_contracts'][station['release_sha256']]
@@ -41,8 +62,9 @@ def run(path):
41
62
 
42
63
  class Session(PdkAdaptSession):
43
64
  def send_tool(self,*args,**kwargs):
44
- cancelled()
45
- result=super().send_tool(*args,**kwargs)
65
+ cancelled();beat()
66
+ try:result=super().send_tool(*args,**kwargs)
67
+ finally:beat()
46
68
  cancelled()
47
69
  return result
48
70
  def publish_server_result(self):
@@ -72,8 +94,10 @@ def run(path):
72
94
  atomic(pointer,canonical({'path':str(session.root),'attempt':row['attempt']}))
73
95
  session.workflow=PdkWorkflow(session,request)
74
96
  os.environ['TED_PDK_PROGRESS_FILE']=str(session.root/'extraction-progress.json')
97
+ beat()
75
98
  def progress(state):
76
99
  jobs.append(row['id'],row['attempt'],{'event':'checkpoint','step':state.step,'phase':state.status})
100
+ beat()
77
101
  cancelled()
78
102
  result=None;stopped=False
79
103
  try:
@@ -21,6 +21,12 @@ def environment(home, proxy, python, runtime):
21
21
  home=Path(home)
22
22
  # Remove inherited V1 routes and execution state. Retain explicitly supplied
23
23
  # EDA installation/license environment and the user's ordinary executable PATH.
24
+ # I01998: the executor's inbound-liveness window is the one variable the
25
+ # workstation operator may tune; step 7 netlist exports legitimately exceed
26
+ # the 45s default when the busy serve stalls pong replies, and the executor
27
+ # must not self-disconnect mid-execution. Honor an explicit override,
28
+ # otherwise lift the floor to 300s (20 ping misses).
29
+ liveness=os.environ.get('VLINK_REMOTE_LIVENESS_TIMEOUT_SECS','')
24
30
  env={k:v for k,v in os.environ.items() if not k.startswith(('ELINK_', 'VLINK_', 'DPV2_', 'TED_', 'TEDBRAIN_', 'PDK', 'PYTHON', 'XDG_'))}
25
31
  for key,relative in [('HOME','.'),('XDG_CONFIG_HOME','config'),('XDG_CACHE_HOME','cache'),
26
32
  ('XDG_STATE_HOME','state'),('XDG_RUNTIME_DIR','run'),('TMPDIR','tmp'),
@@ -28,6 +34,7 @@ def environment(home, proxy, python, runtime):
28
34
  ('TED_DATA','data'),('PDKS_FOLDER','assets/pdks')]:
29
35
  path=home/relative;path.mkdir(parents=True,exist_ok=True,mode=0o700);env[key]=str(path)
30
36
  env.update(ELINK_PROXY_URL=proxy,TEDMIND_SKIP_VLINK_UPDATE='1',VLINK_REMOTE_MAX_CONCURRENT='2',
37
+ VLINK_REMOTE_LIVENESS_TIMEOUT_SECS=liveness if re.fullmatch('[1-9][0-9]*',liveness) else '300',
31
38
  PYTHONNOUSERSITE='1',PYTHONDONTWRITEBYTECODE='1',TED_PATH=str(runtime),
32
39
  PATH=str(Path(python).parent)+os.pathsep+env.get('PATH',''),
33
40
  PYTHONPATH=str(runtime),LC_ALL='C',LANG='C')
@@ -0,0 +1,188 @@
1
+ """Server-side PDK handoff to other DPV2 plugins (I01928, parent I01920).
2
+
3
+ pdkadapt is the only producer of adapted PDK trees. When an attempt ends in a
4
+ confirmed INSTALLED delivery, the tree that was installed on the workstation
5
+ also stays in the DPV2 run store. This module announces that tree in a small
6
+ manifest area that another plugin (the TED job runner) reads. It never opens
7
+ the job database or the run store to consumers and never copies PDK content:
8
+ a manifest names one finished tree by run id and digest, and the consumer must
9
+ verify the digest again before it uses the tree.
10
+
11
+ The feature is off until the deployment sets ``pdk_handoff_root``.
12
+ """
13
+ import hashlib
14
+ import json
15
+ from pathlib import Path
16
+ import re
17
+ import time
18
+
19
+ from .installer import ContractError, atomic, canonical, loads
20
+
21
+ SCHEMA = 1
22
+ KIND = "dpv2-pdk-handoff"
23
+ SUBJECT = re.compile(r"tedbrain-(?:user|invite)-[a-f0-9]{24}")
24
+ IDENTIFIER = re.compile(r"[a-f0-9]{32}")
25
+ # Aliases are produced by request_contract: alphanumerics plus ``._-``, never
26
+ # starting with a dot, so a manifest path can never escape its directory.
27
+ ALIAS = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
28
+ # Same bounds as ted_eda_tools.pdk.readiness.tree_receipt.
29
+ MAX_FILE_BYTES = 16 * 1024 * 1024
30
+ MAX_TOTAL_BYTES = 128 * 1024 * 1024
31
+ MAX_ENTRIES = 50000
32
+
33
+
34
+ def root(config):
35
+ """The handoff directory, or None when the deployment did not enable it."""
36
+ value = config.get("pdk_handoff_root")
37
+ return Path(value).absolute() if value else None
38
+
39
+
40
+ def tree_path(state_root, subject, workstation, run_id, alias):
41
+ """Location of the retained tree in the DPV2 run store (the engine's layout)."""
42
+ for name, value, pattern in (
43
+ ("subject", subject, SUBJECT),
44
+ ("workstation", workstation, IDENTIFIER),
45
+ ("run_id", run_id, IDENTIFIER),
46
+ ("alias", alias, ALIAS),
47
+ ):
48
+ if not isinstance(value, str) or not pattern.fullmatch(value):
49
+ raise ContractError("unsafe " + name)
50
+ return (
51
+ Path(state_root).absolute() / "engine" / "dpv2" / "clients" / subject
52
+ / "machines" / workstation / "runs" / run_id / "pdks" / alias
53
+ )
54
+
55
+
56
+ def _file_digest(path):
57
+ value = hashlib.sha256()
58
+ with path.open("rb") as stream:
59
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
60
+ value.update(chunk)
61
+ return value.hexdigest()
62
+
63
+
64
+ def tree_receipt(tree):
65
+ """The engine's delivery digest: sorted entries of relative name, size and file digest.
66
+
67
+ The archive marker ``.ted-result.json`` belongs to the installed copy only
68
+ and is excluded exactly as in the engine's own receipt.
69
+ """
70
+ tree = Path(tree)
71
+ if tree.is_symlink() or not tree.is_dir():
72
+ raise ContractError("retained adapted tree is missing")
73
+ entries = []
74
+ total = 0
75
+ for path in sorted(tree.rglob("*")):
76
+ if path.is_symlink():
77
+ raise ContractError("retained adapted tree contains a symlink")
78
+ if path.name == ".ted-result.json" and path.parent == tree:
79
+ continue
80
+ if path.is_file():
81
+ size = path.stat().st_size
82
+ total += size
83
+ if size > MAX_FILE_BYTES or total > MAX_TOTAL_BYTES or len(entries) >= MAX_ENTRIES:
84
+ raise ContractError("retained adapted tree exceeds handoff limits")
85
+ entries.append({"name": path.relative_to(tree).as_posix(), "size": size, "sha256": _file_digest(path)})
86
+ if not entries:
87
+ raise ContractError("retained adapted tree is empty")
88
+ payload = json.dumps(entries, sort_keys=True, separators=(",", ":")).encode()
89
+ return {"files": len(entries), "total_size": total, "tree_sha256": hashlib.sha256(payload).hexdigest()}
90
+
91
+
92
+ def delivery_of(row):
93
+ """The confirmed delivery of a SUCCEEDED job row, or None."""
94
+ if row["state"] != "SUCCEEDED" or not row["result"]:
95
+ return None
96
+ delivery = (json.loads(row["result"]) or {}).get("delivery")
97
+ if not isinstance(delivery, dict) or delivery.get("status") != "INSTALLED":
98
+ return None
99
+ return delivery
100
+
101
+
102
+ def manifest(row, state_root):
103
+ """The handoff manifest for one SUCCEEDED job, or None when it has no delivery.
104
+
105
+ The retained tree is hashed again and must equal the delivery that the
106
+ engine confirmed; a tree that drifted is refused, not announced.
107
+ """
108
+ delivery = delivery_of(row)
109
+ if delivery is None:
110
+ return None
111
+ request = json.loads(row["request"])
112
+ alias = request.get("alias")
113
+ if delivery.get("alias") != alias:
114
+ raise ContractError("delivery alias differs from the request")
115
+ tree = tree_path(state_root, row["subject"], row["workstation"], row["id"], alias)
116
+ receipt = tree_receipt(tree)
117
+ for key in ("files", "total_size", "tree_sha256"):
118
+ if receipt[key] != delivery.get(key):
119
+ raise ContractError("retained tree differs from the confirmed delivery")
120
+ return {
121
+ "schema": SCHEMA, "kind": KIND, "plugin": "pdkadapt",
122
+ "subject": row["subject"], "alias": alias,
123
+ "run_id": row["id"], "attempt": row["attempt"], "workstation_id": row["workstation"],
124
+ "plugin_version": row["version"], "mode": request.get("mode", ""), "cells": request.get("cells", ""),
125
+ "completion_sha256": delivery.get("completion_sha256"),
126
+ "tree": dict(receipt, path=str(tree)), "published_at": time.time(),
127
+ }
128
+
129
+
130
+ def target(handoff, subject, alias):
131
+ """Where the manifest of one (subject, alias) pair lives."""
132
+ for value, pattern in ((subject, SUBJECT), (alias, ALIAS)):
133
+ if not isinstance(value, str) or not pattern.fullmatch(value):
134
+ raise ContractError("unsafe handoff path")
135
+ return Path(handoff) / subject / (alias + ".json")
136
+
137
+
138
+ def stored(path):
139
+ """The manifest already stored at ``path``, or None."""
140
+ if path.is_symlink() or not path.is_file():
141
+ return None
142
+ value = loads(path.read_bytes())
143
+ if isinstance(value, dict) and value.get("kind") == KIND and value.get("schema") == SCHEMA:
144
+ return value
145
+ return None
146
+
147
+
148
+ def sync(config, jobs, *, only=None):
149
+ """Announce the newest confirmed delivery of each (subject, alias) pair.
150
+
151
+ ``only`` limits the pass to one pair after a completion. A manifest whose
152
+ run id and digest already equal the job row is left untouched, so a
153
+ restart only hashes trees that changed. Failures are reported, never
154
+ raised: announcing a delivery must not change the outcome of an adaptation.
155
+ """
156
+ report = {"enabled": False, "published": [], "unchanged": 0, "failed": []}
157
+ handoff = root(config)
158
+ if handoff is None:
159
+ return report
160
+ report["enabled"] = True
161
+ with jobs.connection() as db:
162
+ rows = db.execute("SELECT * FROM jobs WHERE state='SUCCEEDED' ORDER BY updated DESC, id").fetchall()
163
+ newest = {}
164
+ for row in rows:
165
+ delivery = delivery_of(row)
166
+ if delivery is None:
167
+ continue
168
+ pair = (row["subject"], json.loads(row["request"]).get("alias"))
169
+ if only is not None and pair != only:
170
+ continue
171
+ newest.setdefault(pair, (row, delivery))
172
+ for (subject, alias), (row, delivery) in sorted(newest.items()):
173
+ try:
174
+ path = target(handoff, subject, alias)
175
+ previous = stored(path)
176
+ if previous is not None and previous.get("run_id") == row["id"] \
177
+ and (previous.get("tree") or {}).get("tree_sha256") == delivery.get("tree_sha256"):
178
+ report["unchanged"] += 1
179
+ continue
180
+ value = manifest(row, config["state_root"])
181
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
182
+ atomic(path, canonical(value))
183
+ report["published"].append({"subject": subject, "alias": alias, "run_id": row["id"],
184
+ "tree_sha256": value["tree"]["tree_sha256"]})
185
+ except (ContractError, ValueError, TypeError, KeyError, OSError) as error:
186
+ report["failed"].append({"subject": subject, "alias": alias, "run_id": row["id"],
187
+ "error": "%s: %s" % (type(error).__name__, error)})
188
+ return report
@@ -29,7 +29,7 @@ MAX_UNPACKED = 4 * MAX_ARCHIVE
29
29
  ID = re.compile(r"[a-z][a-z0-9-]{0,63}\Z")
30
30
  SHA = re.compile(r"[a-f0-9]{64}\Z")
31
31
  TARGETS = {"linux-x64", "darwin-x64", "darwin-arm64", "win32-x64"}
32
- VLINK_DPV2_VERSION = re.compile(r'0\.0\.0-dpv2\.pdkadapt\.(?:plugin|executor-linux-x64|(?:python|vlink|bootstrap)-(?:linux-x64|darwin-x64|darwin-arm64|win32-x64))\.[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?\.r[1-9][0-9]*')
32
+ VLINK_DPV2_VERSION = re.compile(r'0\.0\.0-dpv2\.(?:pdkadapt|ted-runner)\.(?:plugin|executor-linux-x64|(?:python|vlink|bootstrap)-(?:linux-x64|darwin-x64|darwin-arm64|win32-x64))\.[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?\.r[1-9][0-9]*')
33
33
 
34
34
 
35
35
  def package_identity(package, version):