@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.2.r2 → 0.0.0-dpv2.pdkadapt.plugin.0.1.4.r2
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
|
@@ -16,7 +16,7 @@ PYTHONDONTWRITEBYTECODE=1 TED_EDA_MODE=LOCAL python3 -m pytest tests/test_dpv2*.
|
|
|
16
16
|
|
|
17
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 实机验证。
|
|
18
18
|
|
|
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
|
|
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 和模拟账号验证源。
|
|
20
20
|
|
|
21
21
|
## 安装和任务合同
|
|
22
22
|
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.
|
|
1
|
+
{"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.4.r2"}
|
|
@@ -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)
|
|
@@ -15,7 +15,30 @@ from .installer import ContractError, atomic, canonical, loads
|
|
|
15
15
|
from .service import PREFIX
|
|
16
16
|
|
|
17
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
|
+
|
|
18
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):
|
|
19
42
|
root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
|
|
20
43
|
root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
21
44
|
vlink=os.environ.get('DPV2_VLINK')
|
|
@@ -141,15 +164,19 @@ def main(argv=None):
|
|
|
141
164
|
return show(code,envelope)
|
|
142
165
|
if argv and argv[0]=='login':
|
|
143
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')
|
|
144
175
|
credential=sys.stdin.readline().strip() if a.stdin else getpass.getpass('TedBrain invitation code: ')
|
|
145
|
-
code,envelope=
|
|
176
|
+
code,envelope=exchange_session(root,credential)
|
|
146
177
|
if code:return show(code,envelope)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
raise ContractError('login returned an invalid DPV2 credential')
|
|
150
|
-
directory=root/'credentials';directory.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
151
|
-
atomic(directory/'token',token.encode())
|
|
152
|
-
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
|
|
153
180
|
p=argparse.ArgumentParser(description='DPV2 pdkadapt plugin: asynchronous REST jobs')
|
|
154
181
|
p.add_argument('--version',action='version',version='pdkadapt plugin '+os.environ.get('DPV2_RELEASE_VERSION','0.1.0'))
|
|
155
182
|
p.add_argument('--action',choices=['check','start','status','resume','cancel','logs','source-preview','source-confirm','source-install','source-publish'],default='start')
|
|
@@ -9,6 +9,7 @@ import fcntl
|
|
|
9
9
|
import json
|
|
10
10
|
import os
|
|
11
11
|
from pathlib import Path
|
|
12
|
+
import signal
|
|
12
13
|
import subprocess
|
|
13
14
|
import sys
|
|
14
15
|
import time
|
|
@@ -44,11 +45,49 @@ class Worker:
|
|
|
44
45
|
checkpoint_schema=result.get('checkpoint_schema'))
|
|
45
46
|
atomic(observed,canonical({'sha256':digest}))
|
|
46
47
|
return
|
|
47
|
-
if process.is_file() and live(loads(process.read_bytes())):
|
|
48
|
+
if process.is_file() and live(loads(process.read_bytes())):
|
|
49
|
+
if row['state']=='CANCELLING':
|
|
50
|
+
# Cooperative cancellation only fires between synchronous
|
|
51
|
+
# engine operations; a long EDA call never reaches those
|
|
52
|
+
# checks, so the supervisor escalates after the grace (I01769).
|
|
53
|
+
self._escalate_cancel(row,loads(process.read_bytes()))
|
|
54
|
+
return
|
|
48
55
|
if row['state']!='UNKNOWN':
|
|
49
56
|
self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'UNKNOWN',
|
|
50
57
|
'error':{'code':'WORKER_OUTCOME_UNKNOWN','message':'Execution receipt unavailable; reconcile the original attempt'}},stopped=False)
|
|
51
58
|
|
|
59
|
+
def _escalate_cancel(self,row,process_row):
|
|
60
|
+
"""Terminate a CANCELLING engine group once the grace elapses.
|
|
61
|
+
|
|
62
|
+
``jobs.cancel`` timestamps the state change in ``updated``; the engine
|
|
63
|
+
keeps its cooperative window until then. SIGTERM, then SIGKILL the
|
|
64
|
+
whole session group (the engine owns its EDA children), and confirm
|
|
65
|
+
death before recording the receipt: the execution tree stopping is
|
|
66
|
+
the worker's own observation, never an assumption. A killed engine
|
|
67
|
+
leaves no trustworthy checkpoint, so the receipt carries
|
|
68
|
+
``checkpoint_schema=None`` and this attempt cannot be resumed.
|
|
69
|
+
"""
|
|
70
|
+
grace=float(self.config.get('cancel_grace_seconds',30))
|
|
71
|
+
if time.time()<row['updated']+grace:return
|
|
72
|
+
pid=process_row['pid']
|
|
73
|
+
self.jobs.append(row['id'],row['attempt'],{'event':'worker_cancel_escalation','pid':pid})
|
|
74
|
+
for name,delay in (('SIGTERM',float(self.config.get('cancel_term_seconds',10))),
|
|
75
|
+
('SIGKILL',5.0)):
|
|
76
|
+
try:os.killpg(pid,getattr(signal,name))
|
|
77
|
+
except ProcessLookupError:break
|
|
78
|
+
deadline=time.time()+delay
|
|
79
|
+
while time.time()<deadline and live(process_row):time.sleep(0.2)
|
|
80
|
+
if not live(process_row):break
|
|
81
|
+
if live(process_row):
|
|
82
|
+
# Termination unconfirmed: stay CANCELLING and retry on the next tick.
|
|
83
|
+
return
|
|
84
|
+
atomic(self.path(row)/'result.json',canonical({
|
|
85
|
+
'job_id':row['id'],'attempt':row['attempt'],'version':row['version'],
|
|
86
|
+
'result':{'ok':False,'job_status':'CANCELLED',
|
|
87
|
+
'error':{'code':'WORKER_CANCEL_TERMINATED',
|
|
88
|
+
'message':'Engine process group terminated after the cancellation grace; the local execution tree is confirmed stopped'}},
|
|
89
|
+
'remote_stop_confirmed':True,'checkpoint_schema':None}))
|
|
90
|
+
|
|
52
91
|
def launch(self, row):
|
|
53
92
|
directory=self.path(row)
|
|
54
93
|
# Exclusive creation is a second guard after the DB claim. Existing
|