taskcarry 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. taskcarry/__init__.py +3 -0
  2. taskcarry/__main__.py +4 -0
  3. taskcarry/adapter_contracts.py +166 -0
  4. taskcarry/agy_turns.py +282 -0
  5. taskcarry/api.py +111 -0
  6. taskcarry/board.py +313 -0
  7. taskcarry/board_assets/board.css +1087 -0
  8. taskcarry/board_assets/board.js +1187 -0
  9. taskcarry/board_assets/browse.js +214 -0
  10. taskcarry/board_assets/index.html +43 -0
  11. taskcarry/board_assets/taskcarry-icon.ico +0 -0
  12. taskcarry/board_assets/taskcarry-mark.svg +28 -0
  13. taskcarry/board_data.py +466 -0
  14. taskcarry/chat_joins.py +157 -0
  15. taskcarry/cli.py +119 -0
  16. taskcarry/codex_capture.py +184 -0
  17. taskcarry/codex_host.py +293 -0
  18. taskcarry/collaboration_exchange.py +316 -0
  19. taskcarry/connection.py +159 -0
  20. taskcarry/continuity.py +300 -0
  21. taskcarry/contracts.py +165 -0
  22. taskcarry/conversation_capture.py +669 -0
  23. taskcarry/core.py +896 -0
  24. taskcarry/cycle_contracts.py +73 -0
  25. taskcarry/discovery.py +434 -0
  26. taskcarry/discovery_contracts.py +52 -0
  27. taskcarry/exchange_contracts.py +67 -0
  28. taskcarry/exchange_endpoint.py +377 -0
  29. taskcarry/exchange_packets.py +142 -0
  30. taskcarry/experience_contracts.py +129 -0
  31. taskcarry/experience_exchange.py +214 -0
  32. taskcarry/experience_notes.py +433 -0
  33. taskcarry/experience_storage.py +125 -0
  34. taskcarry/experience_tools.py +26 -0
  35. taskcarry/feishu/__init__.py +1 -0
  36. taskcarry/feishu/display.py +122 -0
  37. taskcarry/feishu/project_watch.py +145 -0
  38. taskcarry/feishu/review_sets.py +80 -0
  39. taskcarry/feishu/sender.py +42 -0
  40. taskcarry/feishu/subscription.py +193 -0
  41. taskcarry/feishu/windows_agent.py +287 -0
  42. taskcarry/feishu/windows_secret.py +34 -0
  43. taskcarry/gitops.py +170 -0
  44. taskcarry/governance.py +88 -0
  45. taskcarry/governance_cycle.py +775 -0
  46. taskcarry/identification.py +82 -0
  47. taskcarry/integration.py +663 -0
  48. taskcarry/maintenance.py +118 -0
  49. taskcarry/mcp.py +183 -0
  50. taskcarry/member_join.py +184 -0
  51. taskcarry/member_routing.py +145 -0
  52. taskcarry/onboarding.py +272 -0
  53. taskcarry/onboarding_complete.py +252 -0
  54. taskcarry/path_batches.py +19 -0
  55. taskcarry/preservation.py +257 -0
  56. taskcarry/project_collaboration.py +453 -0
  57. taskcarry/project_history.py +166 -0
  58. taskcarry/project_identity.py +51 -0
  59. taskcarry/project_recovery.py +824 -0
  60. taskcarry/recovery_contracts.py +25 -0
  61. taskcarry/recovery_files.py +153 -0
  62. taskcarry/recovery_git.py +234 -0
  63. taskcarry/remote_capture.py +89 -0
  64. taskcarry/remote_transfer.py +356 -0
  65. taskcarry/role_connection.py +215 -0
  66. taskcarry/setup.py +597 -0
  67. taskcarry/shared_workbench.py +480 -0
  68. taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
  69. taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
  70. taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
  71. taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
  72. taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
  73. taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
  74. taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
  75. taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
  76. taskcarry/source_review_set.py +80 -0
  77. taskcarry/state_format.py +47 -0
  78. taskcarry/store.py +472 -0
  79. taskcarry/task_context.py +141 -0
  80. taskcarry/text_handback.py +98 -0
  81. taskcarry/transfer_contracts.py +18 -0
  82. taskcarry/updates.py +351 -0
  83. taskcarry/workbench.py +625 -0
  84. taskcarry/workbench_contracts.py +32 -0
  85. taskcarry/workbuddy_capture.py +451 -0
  86. taskcarry/workbuddy_setup.py +212 -0
  87. taskcarry/worker_channel.py +859 -0
  88. taskcarry/worker_contracts.py +190 -0
  89. taskcarry/worker_storage.py +60 -0
  90. taskcarry/worker_tools.py +111 -0
  91. taskcarry-0.3.2.dist-info/METADATA +203 -0
  92. taskcarry-0.3.2.dist-info/RECORD +105 -0
  93. taskcarry-0.3.2.dist-info/WHEEL +5 -0
  94. taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
  95. taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
  96. taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
  97. taskcarry-0.3.2.dist-info/top_level.txt +2 -0
  98. taskcarry_https/__init__.py +1 -0
  99. taskcarry_https/consent.py +207 -0
  100. taskcarry_https/reader.py +132 -0
  101. taskcarry_https/review.py +116 -0
  102. taskcarry_https/server.py +163 -0
  103. taskcarry_https/team.py +335 -0
  104. taskcarry_https/team_host.py +109 -0
  105. taskcarry_https/web_host.py +82 -0
@@ -0,0 +1,163 @@
1
+ """Bounded HTTPS reader surface. The public address and TLS terminator are replaceable."""
2
+ import json
3
+ from urllib.parse import parse_qs, urlsplit
4
+
5
+ from mcp.server.auth.middleware.auth_context import get_access_token
6
+ from mcp.server.auth.settings import AuthSettings, ClientRegistrationOptions, RevocationOptions
7
+ from mcp.server.fastmcp import FastMCP
8
+ from mcp.server.transport_security import TransportSecuritySettings
9
+ from mcp.types import ToolAnnotations
10
+ from starlette.requests import Request
11
+ from starlette.responses import JSONResponse
12
+
13
+ from .consent import InvitationOAuth
14
+ from .reader import InvitationUnavailable
15
+ from .review import ReviewInvitation
16
+
17
+
18
+ MAX_BODY = 32 * 1024
19
+
20
+
21
+ def create_app(origin, invitation, owner_code, *, audit=None, test_redirect=None):
22
+ """Create one temporary invitation. The default surface grants two read-only tools."""
23
+ oauth = InvitationOAuth(origin, invitation, owner_code, test_redirect)
24
+ invitation.check_member()
25
+ audit = audit or (lambda event, **fields: None)
26
+ authority = urlsplit(origin).netloc
27
+ server = FastMCP(
28
+ invitation.service_name, auth_server_provider=oauth,
29
+ auth=AuthSettings(issuer_url=origin, resource_server_url=oauth.resource, validate_token_resource=True,
30
+ required_scopes=[oauth.scope], revocation_options=RevocationOptions(enabled=True),
31
+ client_registration_options=ClientRegistrationOptions(enabled=True, valid_scopes=[oauth.scope],
32
+ default_scopes=[oauth.scope])),
33
+ stateless_http=True, json_response=True, max_request_body_size=MAX_BODY,
34
+ transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=True,
35
+ allowed_hosts=[authority], allowed_origins=[origin, "https://gemini.google.com"]),
36
+ )
37
+ checks = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
38
+
39
+ def check_subject():
40
+ token = get_access_token()
41
+ if (token is None or token.resource != oauth.resource or token.subject != invitation.binding_id
42
+ or oauth.scope not in token.scopes):
43
+ raise InvitationUnavailable("This invitation is unavailable.")
44
+
45
+ @server.tool(annotations=checks)
46
+ def taskcarry_assignment() -> dict[str, object]:
47
+ """Read your project, assignment and the exact source references in this invitation."""
48
+ check_subject()
49
+ result = invitation.assignment()
50
+ audit("assignment_read")
51
+ return result
52
+
53
+ @server.tool(annotations=checks)
54
+ def taskcarry_read_source(reference_id: str, cursor: str | None = None) -> dict[str, object]:
55
+ """Read one page of an invited source. Use its exact reference ID and the returned cursor."""
56
+ check_subject()
57
+ result = invitation.read(reference_id, cursor)
58
+ audit("source_page_read", revision=result["revision"], complete=result["complete"])
59
+ return result
60
+
61
+ if isinstance(invitation, ReviewInvitation):
62
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=True,
63
+ openWorldHint=False))
64
+ def taskcarry_submit_draft(text: str, expected_revision: int, task_version: str,
65
+ display_title: str | None = None) -> dict[str, object]:
66
+ """Submit your Markdown for review with a short group-facing title. Use the assigned task version and current revision (0 for new work). Identical retries return the same receipt."""
67
+ check_subject()
68
+ result = invitation.submit(text, expected_revision, task_version, display_title)
69
+ audit("draft_submitted", revision=result["revision"])
70
+ return result
71
+
72
+ @server.tool(annotations=checks)
73
+ def taskcarry_submission_status() -> dict[str, object]:
74
+ """Read your latest submitted revision and any governor review for the identified revision."""
75
+ check_subject()
76
+ return invitation.submission_status()
77
+
78
+ if invitation.include_project_map:
79
+ @server.tool(annotations=checks)
80
+ def taskcarry_project_overview(cursor: str | None = None) -> dict[str, object]:
81
+ """Read the governor-selected project workstreams, responsibilities and recorded current states. A separate project has no local status. Follow next_cursor if present."""
82
+ check_subject()
83
+ result = invitation.project_map(cursor)
84
+ audit("project_overview_read", count=len(result["workstreams"]), complete=result["next_cursor"] is None)
85
+ return result
86
+
87
+ app = server.streamable_http_app()
88
+ app.add_route("/consent/{ticket}", oauth.consent, methods=["GET", "POST"])
89
+
90
+ async def bounded_app(scope, receive, send):
91
+ if scope["type"] != "http":
92
+ return await app(scope, receive, send)
93
+ request = Request(scope, receive)
94
+ route = request.url.path
95
+ category = "consent" if route.startswith("/consent/") else route.lstrip("/")
96
+ downstream_send = send
97
+
98
+ async def send_status(message):
99
+ if category in {"register", "authorize", "consent", "token", "revoke"} and message["type"] == "http.response.start":
100
+ audit("oauth_step", step=category, status=message["status"])
101
+ await downstream_send(message)
102
+
103
+ send = send_status
104
+ if request.headers.getlist("host") != [authority]:
105
+ return await JSONResponse({"error": "invalid_host"}, status_code=400)(scope, receive, send)
106
+ if request.method != "POST":
107
+ return await app(scope, receive, send)
108
+ data = bytearray()
109
+ async for part in request.stream():
110
+ if len(data) + len(part) > MAX_BODY:
111
+ return await JSONResponse({"error": "request_too_large"}, status_code=413)(scope, receive, send)
112
+ data.extend(part)
113
+ if request.url.path == "/token":
114
+ try:
115
+ resource = parse_qs(data.decode("utf-8"), keep_blank_values=True, max_num_fields=24).get("resource")
116
+ except (UnicodeError, ValueError):
117
+ resource = []
118
+ if resource is not None and resource != [oauth.resource]:
119
+ return await JSONResponse({"error": "invalid_target"}, status_code=400)(scope, receive, send)
120
+ if (request.url.path == "/revoke" and
121
+ request.headers.get("content-type", "").split(";")[0] == "application/x-www-form-urlencoded"):
122
+ # SDK 1.30's RFC 7009 form requires a nullable key even for public clients.
123
+ # SDK client authentication still validates confidential-client credentials.
124
+ try:
125
+ form = parse_qs(data.decode("utf-8"), keep_blank_values=True, max_num_fields=24)
126
+ except (UnicodeError, ValueError):
127
+ return await JSONResponse({"error": "invalid_request"}, status_code=400)(scope, receive, send)
128
+ if "client_secret" not in form:
129
+ data.extend(b"&client_secret=")
130
+ initialization = False
131
+ if request.url.path == "/mcp":
132
+ try:
133
+ message = json.loads(data)
134
+ initialization = isinstance(message, dict) and message.get("method") == "initialize"
135
+ except (ValueError, RecursionError):
136
+ pass
137
+
138
+ consumed = False
139
+
140
+ async def replay():
141
+ nonlocal consumed
142
+ if consumed:
143
+ return await receive()
144
+ consumed = True
145
+ return {"type": "http.request", "body": bytes(data), "more_body": False}
146
+
147
+ async def note_response(message):
148
+ if initialization and message["type"] == "http.response.body" and message.get("body"):
149
+ try:
150
+ reply = json.loads(message["body"])
151
+ version = reply.get("result", {}).get("protocolVersion")
152
+ if isinstance(version, str) and len(version) == 10:
153
+ audit("mcp_initialized", protocol=version, encoding="json")
154
+ except (ValueError, AttributeError):
155
+ pass
156
+ await send(message)
157
+
158
+ if request.url.path == "/register":
159
+ response = await oauth.register(Request(scope, replay))
160
+ return await response(scope, replay, send)
161
+ return await app(scope, replay, note_response)
162
+
163
+ return bounded_app
@@ -0,0 +1,335 @@
1
+ """A team member's private HTTPS entry, backed by the usual project worker binding."""
2
+ import hashlib
3
+ import json
4
+ import secrets
5
+ import time
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from typing import Literal
9
+ from urllib.parse import urlsplit
10
+
11
+ from mcp.server.fastmcp import FastMCP
12
+ from mcp.server.transport_security import TransportSecuritySettings
13
+ from mcp.types import ToolAnnotations
14
+ from starlette.concurrency import run_in_threadpool
15
+ from starlette.requests import Request
16
+ from starlette.responses import JSONResponse
17
+
18
+ from taskcarry.member_join import fingerprint
19
+ from taskcarry.remote_capture import PROTOCOL as CAPTURE_PROTOCOL, device_request
20
+ from taskcarry.store import GovernanceError
21
+ from taskcarry.worker_tools import DESCRIPTIONS as MEMBER_DESCRIPTIONS, SCHEMAS as MEMBER_SCHEMAS
22
+ from taskcarry_https.reader import InvitationUnavailable, MembershipInactive, ReaderInvitation
23
+ from taskcarry_https.review import ReviewInvitation
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ServePeer:
28
+ """Validate a private Tailscale Serve request at a loopback-only origin."""
29
+ node_id: str
30
+ user_id: str
31
+ addresses: frozenset[str]
32
+ whois: Callable[[str], dict]
33
+
34
+ def __call__(self, scope, headers):
35
+ client = scope.get("client")
36
+ if not client or client[0] not in {"127.0.0.1", "::1"}:
37
+ return False
38
+ if (headers.getlist("tailscale-funnel-request") or headers.getlist("x-forwarded-proto") != ["https"]
39
+ or headers.getlist("x-forwarded-host") != headers.getlist("host")):
40
+ return False
41
+ forwarded = headers.getlist("x-forwarded-for")
42
+ login = headers.getlist("tailscale-user-login")
43
+ if len(forwarded) != 1 or forwarded[0] not in self.addresses or len(login) != 1 or not login[0]:
44
+ return False
45
+ try:
46
+ identity = self.whois(forwarded[0])
47
+ return (identity["Node"]["StableID"] == self.node_id and str(identity["UserProfile"]["ID"]) == self.user_id
48
+ and identity["UserProfile"]["LoginName"] == login[0] and not identity["Node"].get("Tags"))
49
+ except (KeyError, TypeError, ValueError, OSError):
50
+ return False
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class TeamInvitation(ReviewInvitation):
55
+ service_name = "TaskCarry Team Worker"
56
+ # In a team profile expires_at governs work already authorized. Older
57
+ # profiles use that same date for enrollment.
58
+ expires_at: int | None
59
+ workbench_id: str = ""
60
+ join_expires_at: int | None = None
61
+
62
+ def access_active(self):
63
+ return self.expires_at is None or super().access_active()
64
+
65
+ @property
66
+ def join_deadline(self):
67
+ if self.join_expires_at is None:
68
+ return self.expires_at
69
+ if self.expires_at is None:
70
+ return self.join_expires_at
71
+ return min(self.join_expires_at, self.expires_at)
72
+
73
+ def join_open(self):
74
+ deadline = self.join_deadline
75
+ return deadline is None or time.time() < deadline
76
+
77
+ def _matches_role(self, role):
78
+ return ReaderInvitation._matches_role(self, role) and "source_scope" not in role
79
+
80
+ def directory(self, section, cursor=None):
81
+ self.check_member()
82
+ args = {"section": section, "limit": 8}
83
+ if cursor:
84
+ args["cursor"] = cursor
85
+ return self._call("worker_brief", args)
86
+
87
+ def current_reference(self, reference_id):
88
+ current = self._call("source_share", {"mode": "get", "reference_id": reference_id})
89
+ return {key: current[key] for key in ("reference_id", "revision", "content_sha256")}
90
+
91
+ def assignment(self):
92
+ result = super().assignment()
93
+ result.update(project_id=self.project_id, binding_id=self.binding_id, binding_revision=self.binding_revision)
94
+ result["membership"] = {
95
+ "state": "active", "term": "until_revoked" if self.expires_at is None else "until_date",
96
+ "membership_expires_at": self.expires_at, "join_expires_at": self.join_deadline,
97
+ }
98
+ if self.workbench_id:
99
+ result["current_workbench"] = self.current_reference(self.workbench_id)
100
+ return result
101
+
102
+ def offer(self, origin):
103
+ deadline = self.join_deadline
104
+ offer = {"schema": "taskcarry.worker-invite.v1", "project": self.project_name, "project_id": self.project_id,
105
+ "role": self.role_ceiling, "role_label": self.role_label, "binding_id": self.binding_id,
106
+ "binding_revision": self.binding_revision, "task_id": self.task_id, "expires_at": deadline,
107
+ "endpoint": origin + "/mcp"}
108
+ if self.expires_at is None or deadline != self.expires_at:
109
+ offer.update(schema="taskcarry.worker-invite.v2", membership_expires_at=self.expires_at)
110
+ return offer
111
+
112
+ def shared_page(self, reference_id, revision=None, content_sha256=None, cursor=None):
113
+ self.check_member()
114
+ ref = self.current_reference(reference_id)
115
+ if revision is not None or content_sha256 is not None or cursor is not None:
116
+ if revision is None or not content_sha256:
117
+ raise InvitationUnavailable("Include the revision and hash when continuing an exact source.")
118
+ requested = {"reference_id": reference_id, "revision": revision, "content_sha256": content_sha256}
119
+ ref = requested
120
+ args = {"reference": ref, "max_bytes": 4096}
121
+ if cursor:
122
+ args["cursor"] = cursor
123
+ return self._call("source_read", args)
124
+
125
+
126
+ def create_team_app(origin, invitation, token_digest, trusted_peer, *, audit=None, enrollment_token=None):
127
+ """The TLS front end authenticates a device. The independent bearer identifies the job."""
128
+ url = urlsplit(origin)
129
+ if url.scheme != "https" or not url.hostname or url.path or url.query or url.fragment or url.username is not None:
130
+ raise ValueError("Set the private HTTPS origin.")
131
+ if len(token_digest) != 32 or not callable(trusted_peer):
132
+ raise ValueError("Configure the job token digest and authenticated peer verifier.")
133
+ if enrollment_token is not None and not secrets.compare_digest(hashlib.sha256(enrollment_token.encode("ascii")).digest(), token_digest):
134
+ raise ValueError("The invitation must match the active job credential.")
135
+ invitation.check_member()
136
+ audit = audit or (lambda event, **fields: None)
137
+ server = FastMCP(invitation.service_name, stateless_http=True, json_response=True, max_request_body_size=32 * 1024,
138
+ instructions=("When the user returns to this project's work in chat, call taskcarry_assignment "
139
+ "and compare current_workbench to the revision already read. Open relevant updates "
140
+ "with taskcarry_read_source before continuing. Use the current service's membership "
141
+ "term. The user's ordinary project request is sufficient; keep idle chats idle."),
142
+ transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=True,
143
+ allowed_hosts=[url.netloc], allowed_origins=[origin]))
144
+ read = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
145
+
146
+ @server.tool(annotations=read)
147
+ def taskcarry_assignment() -> dict[str, object]:
148
+ """On a project work turn, read your current membership term, latest workbench and assigned task."""
149
+ result = invitation.assignment()
150
+ audit("assignment_read", **result["membership"])
151
+ return result
152
+
153
+ @server.tool(annotations=read)
154
+ def taskcarry_team_directory(section: Literal["project_map", "tasks", "sources"] = "project_map",
155
+ cursor: str | None = None) -> dict[str, object]:
156
+ """Read current project roles, task states or the project-shared source directory. Follow next_cursor."""
157
+ result = invitation.directory(section, cursor)
158
+ audit("directory_read", section=section, count=result["returned"], complete=result["next_cursor"] is None)
159
+ return result
160
+
161
+ def team_call(action, arguments):
162
+ invitation.check_member()
163
+ fields = MEMBER_SCHEMAS[action]["properties"]
164
+ return invitation._call(action, {key: value for key, value in arguments.items() if key in fields and value is not None})
165
+
166
+ @server.tool(annotations=read)
167
+ def taskcarry_member_lookup(query: str, cursor: str | None = None, limit: int = 8) -> dict[str, object]:
168
+ """Resolve a visible teammate's board name or role code to a binding ID for discussion or turn reads."""
169
+ return team_call("member_lookup", locals())
170
+
171
+ @server.tool(annotations=read)
172
+ def taskcarry_project_history(kind: str | None = None, key: str | None = None, sha256: str | None = None,
173
+ task_id: str | None = None, query: str | None = None, cursor: str | None = None,
174
+ limit: int = 8, offset: int = 0) -> dict[str, object]:
175
+ """Find team-authorized historical decisions and work. Open an exact kind/key/hash for the original."""
176
+ return team_call("project_history", locals())
177
+
178
+ @server.tool(annotations=read)
179
+ def taskcarry_project_overview(revision: int | None = None, entry_id: str | None = None,
180
+ cursor: str | None = None, limit: int = 8) -> dict[str, object]:
181
+ """Read the governor's current snapshot and follow a workline to its exact sources."""
182
+ return team_call("project_overview", locals())
183
+
184
+ @server.tool(annotations=read, description=MEMBER_DESCRIPTIONS["experience_query"])
185
+ def taskcarry_experience_query(
186
+ section: Literal["notes", "feedback", "history", "get", "feedback_get", "feedback_history"] = "notes",
187
+ experience_id: str | None = None, feedback_id: str | None = None, revision: int | None = None,
188
+ task_id: str | None = None, state: Literal["proposed", "active", "paused", "retired"] = "active",
189
+ context: list[dict] | None = None, previous_fingerprint: str | None = None,
190
+ limit: int = 5, cursor: str | None = None,
191
+ ) -> dict[str, object]:
192
+ return team_call("experience_query", locals())
193
+
194
+ write = ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=True, openWorldHint=False)
195
+
196
+ @server.tool(annotations=write, description=MEMBER_DESCRIPTIONS["experience_note"])
197
+ def taskcarry_experience_note(
198
+ mode: Literal["plan", "execute", "get"], record: dict | None = None,
199
+ expected_revision: int | None = None, plan_id: str | None = None, experience_id: str | None = None,
200
+ ) -> dict[str, object]:
201
+ return team_call("experience_note", locals())
202
+
203
+ @server.tool(annotations=write, description=MEMBER_DESCRIPTIONS["experience_feedback"])
204
+ def taskcarry_experience_feedback(
205
+ mode: Literal["plan", "execute", "get"], record: dict | None = None,
206
+ expected_revision: int | None = None, plan_id: str | None = None, feedback_id: str | None = None,
207
+ ) -> dict[str, object]:
208
+ return team_call("experience_feedback", locals())
209
+
210
+ @server.tool(annotations=read)
211
+ def taskcarry_discussion(topic_id: str | None = None, revision: int | None = None,
212
+ participant: str | None = None, task_id: str | None = None,
213
+ query: str | None = None, state: str | None = None, since: str | None = None,
214
+ until: str | None = None, cursor: str | None = None, limit: int = 8,
215
+ offset: int | None = None) -> dict[str, object]:
216
+ """Find a topic. For a teammate's name, use taskcarry_member_lookup for the participant filter."""
217
+ return team_call("discussion", locals())
218
+
219
+ @server.tool(annotations=read)
220
+ def taskcarry_turn_read(conversation_id: str | None = None, turn_id: str | None = None, revision: int | None = None,
221
+ cursor: str | None = None, limit: int = 8, offset: int = 0,
222
+ owner: str | None = None) -> dict[str, object]:
223
+ """Use taskcarry_member_lookup to find an owner's ID, list the last 8 exchanges or read an exact original."""
224
+ return team_call("turn_read", locals())
225
+
226
+ @server.tool(annotations=write)
227
+ def taskcarry_discussion_update(mode: Literal["plan","execute"], topic_id: str | None = None,
228
+ expected_revision: int | None = None, record: dict | None = None,
229
+ plan_id: str | None = None) -> dict[str, object]:
230
+ """Plan a concise team discussion or reply using your assigned role, then execute the returned plan ID."""
231
+ args = {"mode":mode, "plan_id":plan_id, "topic_id":topic_id, "expected_revision":expected_revision, "record":record}
232
+ if mode == "plan":
233
+ args.update(task_id=invitation.task_id, workspace_id=invitation.workspace_id)
234
+ return team_call("discussion_update", args)
235
+
236
+ @server.tool(annotations=read)
237
+ def taskcarry_read_source(reference_id: str, revision: int | None = None, content_sha256: str | None = None,
238
+ cursor: str | None = None) -> dict[str, object]:
239
+ """Read a current shared document or an exact pinned source. For more pages send its revision, hash and cursor."""
240
+ result = invitation.shared_page(reference_id, revision, content_sha256, cursor)
241
+ ref = result["reference"]
242
+ audit("source_read", reference_id=ref["reference_id"], revision=ref["revision"],
243
+ complete=result.get("complete", False))
244
+ return result
245
+
246
+ @server.tool(annotations=write)
247
+ def taskcarry_submit_draft(text: str, expected_revision: int, task_version: str,
248
+ display_title: str | None = None) -> dict[str, object]:
249
+ """Share your Markdown in your assigned slot, with an optional group-facing title. Use 0 for the first revision."""
250
+ result = invitation.submit(text, expected_revision, task_version, display_title)
251
+ audit("draft_submitted", revision=result["revision"])
252
+ return result
253
+
254
+ @server.tool(annotations=read)
255
+ def taskcarry_submission_status() -> dict[str, object]:
256
+ """Read your own exact submission and its latest review."""
257
+ result = invitation.submission_status()
258
+ decision = result.get("last_review") or {}
259
+ audit("submission_status_read", revision=result["revision"], review_revision=decision.get("handback_revision"),
260
+ verdict=decision.get("verdict"))
261
+ return result
262
+
263
+ app = server.streamable_http_app()
264
+
265
+ async def protected(scope, receive, send):
266
+ if scope["type"] != "http":
267
+ return await app(scope, receive, send)
268
+ headers = Request(scope).headers
269
+ def deny():
270
+ return JSONResponse({"error": "access_denied"}, status_code=403, headers={"Cache-Control": "no-store"})
271
+ enrollment = enrollment_token is not None and scope["path"] == "/join" and scope["method"] in {"GET", "POST"}
272
+ capture = scope["path"] == "/member-capture" and scope["method"] == "POST"
273
+ if ((scope["path"] != "/mcp" and not enrollment and not capture) or headers.getlist("host") != [url.netloc]
274
+ or headers.getlist("origin") not in ([], [origin]) or not invitation.access_active()):
275
+ return await deny()(scope, receive, send)
276
+ if not enrollment:
277
+ values = headers.getlist("authorization")
278
+ if len(values) != 1:
279
+ return await deny()(scope, receive, send)
280
+ scheme, _, token = values[0].partition(" ")
281
+ if (scheme.lower() != "bearer" or not token.isascii() or not 32 <= len(token) <= 128
282
+ or not secrets.compare_digest(hashlib.sha256(token.encode("ascii")).digest(), token_digest)):
283
+ return await deny()(scope, receive, send)
284
+ if not await run_in_threadpool(trusted_peer, scope, headers):
285
+ return await deny()(scope, receive, send)
286
+ try:
287
+ member_role = await run_in_threadpool(invitation.check_member)
288
+ except MembershipInactive:
289
+ if enrollment:
290
+ return await deny()(scope, receive, send)
291
+ audit("membership_inactive")
292
+ return await JSONResponse({"error": "membership_inactive"}, status_code=403,
293
+ headers={"Cache-Control": "no-store"})(scope, receive, send)
294
+ except InvitationUnavailable:
295
+ return await deny()(scope, receive, send)
296
+ if capture:
297
+ # The device helper uses the member's existing HTTPS origin, peer
298
+ # and bearer. This ingress is intentionally absent from model tools.
299
+ maximum = 1024 * 1024
300
+ data = bytearray()
301
+ if headers.get('content-type', '').split(';')[0].strip().lower() != 'application/json':
302
+ return await deny()(scope, receive, send)
303
+ async for chunk in Request(scope, receive).stream():
304
+ if len(data) + len(chunk) > maximum:
305
+ return await JSONResponse({'error': 'too_large'}, status_code=413)(scope, receive, send)
306
+ data.extend(chunk)
307
+ try:
308
+ result = await run_in_threadpool(device_request, invitation, json.loads(data))
309
+ response = JSONResponse(result, headers={'Cache-Control': 'no-store'})
310
+ except (ValueError, UnicodeError, RecursionError):
311
+ response = JSONResponse({'error': 'invalid_request'}, status_code=400)
312
+ except GovernanceError as exc:
313
+ status = 503 if exc.code == 'BUSY' else 400 if exc.code == 'INVALID_ARGUMENT' else 403
314
+ response = JSONResponse({'error': exc.code}, status_code=status, headers={'Cache-Control':'no-store'})
315
+ return await response(scope, receive, send)
316
+ if enrollment:
317
+ if not invitation.join_open():
318
+ return await deny()(scope, receive, send)
319
+ offer = invitation.offer(origin)
320
+ offer_id = fingerprint(offer)
321
+ if scope["method"] == "GET":
322
+ body = {"offer": offer, "offer_id": offer_id}
323
+ if any(row['task_id'] == invitation.task_id and row['workspace_id'] == invitation.workspace_id
324
+ and 'progress' in row['write_actions'] for row in member_role['items']):
325
+ body['chat_sharing'] = CAPTURE_PROTOCOL
326
+ audit("invitation_previewed", binding_revision=invitation.binding_revision)
327
+ else:
328
+ if headers.getlist("taskcarry-confirm") != [offer_id]:
329
+ return await deny()(scope, receive, send)
330
+ body = {"offer_id": offer_id, "access_token": enrollment_token}
331
+ audit("invitation_claimed", binding_revision=invitation.binding_revision)
332
+ return await JSONResponse(body, headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"})(scope, receive, send)
333
+ return await app(scope, receive, send)
334
+
335
+ return protected
@@ -0,0 +1,109 @@
1
+ """Start the optional loopback application for an approved private team worker."""
2
+ import argparse
3
+ import base64
4
+ import hashlib
5
+ import hmac
6
+ import json
7
+ import os
8
+ import secrets
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ from .reader import SharedText
14
+ from .team import ServePeer, TeamInvitation, create_team_app
15
+
16
+
17
+ def profile_key(profile_path):
18
+ """Keep the key next to the manager's private profile across service restarts."""
19
+ path = profile_path.with_suffix(profile_path.suffix + ".key")
20
+ if not path.exists():
21
+ fd, temporary = tempfile.mkstemp(dir=path.parent)
22
+ try:
23
+ with os.fdopen(fd, "wb") as stream:
24
+ stream.write(secrets.token_bytes(32))
25
+ stream.flush()
26
+ os.fsync(stream.fileno())
27
+ try:
28
+ os.link(temporary, path)
29
+ except FileExistsError: # A concurrent start already installed a complete key.
30
+ pass
31
+ finally:
32
+ os.unlink(temporary)
33
+ key = path.read_bytes()
34
+ if len(key) != 32:
35
+ raise ValueError("The local invitation key is invalid. Review the private profile.")
36
+ return key
37
+
38
+
39
+ def make_team_app(profile, origin, whois, *, audit=None, key=None):
40
+ if "expires_at" in profile:
41
+ if "join_expires_at" in profile or type(profile["expires_at"]) is not int:
42
+ raise ValueError("Provide one enrollment deadline for the existing grant.")
43
+ join_by = profile["expires_at"]
44
+ work_until = profile.get("membership_expires_at", join_by)
45
+ else:
46
+ join_by = profile.get("join_expires_at")
47
+ work_until = profile.get("membership_expires_at")
48
+ if any(t is not None and (type(t) is not int or t <= 0) for t in (join_by, work_until)):
49
+ raise ValueError("Use a positive Unix timestamp or null for each team deadline.")
50
+ member = TeamInvitation(
51
+ Path(profile["control"]), profile["project_id"], profile["project_name"], profile["binding_id"],
52
+ profile["binding_revision"], profile["role_label"], profile["task_id"], profile["workspace_id"],
53
+ work_until, tuple(SharedText(**item) for item in profile["sources"]),
54
+ profile["reference_id"], profile["handback_id"], profile["instructions"], True, profile["workbench_id"],
55
+ join_expires_at=join_by)
56
+ if not member.control.is_absolute() or not member.access_active():
57
+ raise ValueError("Choose an active worker grant for the original project.")
58
+ peer = ServePeer(profile["target_node"], str(profile["target_owner"]), frozenset(profile["target_ips"]), whois)
59
+ if not peer.addresses:
60
+ raise ValueError("Select the intended tailnet device before opening the invitation.")
61
+ # The same private grant survives a restart; a change of recipient, origin
62
+ # or role grant derives a different credential. The client cannot choose it.
63
+ token = None
64
+ if key is not None:
65
+ if len(key) != 32:
66
+ raise ValueError("Configure the invitation's private key.")
67
+ grant = member.offer(origin)
68
+ if "expires_at" in profile:
69
+ # A manager may extend an already-enrolled worker's term. Keep
70
+ # checking the original device, role and previously issued secret.
71
+ grant.pop("membership_expires_at", None)
72
+ grant.update(schema="taskcarry.worker-invite.v1", expires_at=profile["expires_at"])
73
+ else:
74
+ # The service enforces the current terms independently of the
75
+ # installed member credential.
76
+ grant.pop("expires_at")
77
+ grant.pop("membership_expires_at", None)
78
+ grant["schema"] = "taskcarry.team-grant.v2"
79
+ basis = [grant, peer.node_id, peer.user_id, member.workspace_id, member.draft_reference_id,
80
+ member.handback_id, [item.reference() for item in member.sources]]
81
+ signed = hmac.digest(key, json.dumps(basis, sort_keys=True, separators=(",", ":")).encode(), "sha256")
82
+ token = base64.urlsafe_b64encode(signed).decode("ascii").rstrip("=")
83
+ digest = hashlib.sha256(token.encode("ascii")).digest() if token else bytes.fromhex(profile["token_digest"])
84
+ return create_team_app(origin, member, digest, peer, audit=audit, enrollment_token=token)
85
+
86
+
87
+ def main():
88
+ import uvicorn
89
+
90
+ parser = argparse.ArgumentParser(description="Serve an existing worker's device-bound project invitation.")
91
+ parser.add_argument("--profile", type=Path, required=True, help="Local profile prepared by the existing project manager")
92
+ parser.add_argument("--origin", required=True, help="The private Tailscale Serve HTTPS origin, including its port")
93
+ parser.add_argument("--port", required=True, type=int, help="Local loopback port for Tailscale Serve")
94
+ args = parser.parse_args()
95
+ profile = json.loads(args.profile.read_text(encoding="utf-8-sig"))
96
+
97
+ def whois(address):
98
+ try:
99
+ result = subprocess.run(["tailscale", "whois", "--json", address], capture_output=True, check=True, timeout=5)
100
+ return json.loads(result.stdout)
101
+ except (ValueError, OSError, subprocess.SubprocessError):
102
+ return {}
103
+
104
+ app = make_team_app(profile, args.origin, whois, key=profile_key(args.profile))
105
+ uvicorn.run(app, host="127.0.0.1", port=args.port, proxy_headers=False, access_log=False, server_header=False)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()