coder-agent 0.1.0__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 (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,32 @@
1
+ ---
2
+ name: office-pptx
3
+ description: Build a slide deck (.pptx) out of an outline - one message per slide, speaker notes under every slide, and a title that says the message.
4
+ ---
5
+
6
+ # Slide decks
7
+
8
+ A deck is not a document cut into pieces. It is a sequence of messages, and
9
+ the audience sees all of them at once.
10
+
11
+ ## Steps
12
+
13
+ 1. **Write the spine.** One sentence per slide, in order, before any
14
+ layout. If the spine does not read as a story, the deck is not ready.
15
+ 2. **Build the slides.** Use `python-pptx` when it is installed
16
+ (`python -c "import pptx"`). Otherwise write the deck as Markdown with
17
+ `---` between the slides and convert it with
18
+ `pandoc slides.md -o slides.pptx`; when that is not there either, hand
19
+ over the Markdown and say what it is.
20
+ 3. **One message per slide.** A title that states the message ("Costs grew
21
+ 40% in Q3"), not the topic ("Costs").
22
+ 4. **Notes.** Every slide gets speaker notes: what to say, in two or three
23
+ sentences, and what to skip when the time is short.
24
+ 5. **Check.** Read the slides back and ask: does the title alone tell the
25
+ story? Does any slide hold two messages?
26
+
27
+ ## Rules
28
+
29
+ - Six to ten words on a slide, twelve at the very most.
30
+ - A chart beats a table of numbers; a table beats a paragraph of numbers.
31
+ - The deck ends with the decision that was asked for, not with a summary of
32
+ what was just said.
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: office-xlsx
3
+ description: Read and write Excel workbooks - formulas, tables and summaries of many rows. Also handles CSV and TSV.
4
+ ---
5
+
6
+ # Spreadsheets
7
+
8
+ ## Steps
9
+
10
+ 1. **Look before writing.** Run `scripts/xlsx_text.py FILE.xlsx` (the script is
11
+ in the directory of the skill) to see the sheets, the columns and the
12
+ types. For a CSV, read the first rows and the header line with the `read`
13
+ tool.
14
+ 2. **Learn the shape.** Name the columns you will use and the unit of each
15
+ of them. A column of dates is not a column of strings, and a percentage
16
+ is not a number between 0 and 1 without saying so.
17
+ 3. **Compute in the workbook.** Put the formula in the cell, not the value:
18
+ `=SUM(C2:C500)`, `=AVERAGEIF(...)`, `=VLOOKUP(...)`. Use
19
+ `openpyxl` when it is installed; otherwise write the CSV that goes with
20
+ the workbook and say so.
21
+ 4. **Summarize.** A sheet of results ends with a small table: the figure,
22
+ the period it covers, and how it was computed. Say which rows were left
23
+ out and why.
24
+ 5. **Check.** Read the workbook back with the script and confirm the totals
25
+ and the formulas are there.
26
+
27
+ ## Rules
28
+
29
+ - Never overwrite a workbook with a guess: work on a copy and say which
30
+ copy.
31
+ - Formulas over values, so the reader can follow the number.
32
+ - One table per sheet. A second table on the same sheet is a second sheet.
33
+ - The units, the currency and the time zone are written in the header or
34
+ next to the number.
@@ -0,0 +1,72 @@
1
+ """The sheets of an Excel file, as text: the name of the sheet, then its rows."""
2
+
3
+ import sys
4
+ import zipfile
5
+ from xml.etree import ElementTree
6
+
7
+ MAIN = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
8
+ DOCUMENT = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}"
9
+ PACKAGE = "{http://schemas.openxmlformats.org/package/2006/relationships}"
10
+
11
+
12
+ def shared_strings(archive: zipfile.ZipFile) -> list[str]:
13
+ """The strings of the file: the cells that hold one point at them."""
14
+ if "xl/sharedStrings.xml" not in archive.namelist():
15
+ return []
16
+ root = ElementTree.fromstring(archive.read("xl/sharedStrings.xml"))
17
+ return ["".join(part.text or "" for part in item.iter(f"{MAIN}t")) for item in root.findall(f"{MAIN}si")]
18
+
19
+
20
+ def column_of(reference: str) -> int:
21
+ """The number of the column a cell sits in, from its name."""
22
+ index = 0
23
+ for letter in "".join(character for character in reference if character.isalpha()):
24
+ index = index * 26 + ord(letter.upper()) - 64
25
+ return index - 1
26
+
27
+
28
+ def text_of(cell, shared: list[str]) -> str:
29
+ """The text of a cell."""
30
+ if cell.get("t") == "s":
31
+ return shared[int(cell.findtext(f"{MAIN}v", default="0"))]
32
+ if cell.get("t") == "inlineStr":
33
+ return "".join(part.text or "" for part in cell.iter(f"{MAIN}t"))
34
+ return cell.findtext(f"{MAIN}v", default="")
35
+
36
+
37
+ def sheets_of(archive: zipfile.ZipFile) -> list[tuple[str, str]]:
38
+ """The name of every sheet and the file that holds it."""
39
+ book = ElementTree.fromstring(archive.read("xl/workbook.xml"))
40
+ relations = ElementTree.fromstring(archive.read("xl/_rels/workbook.xml.rels"))
41
+ targets = {item.get("Id"): item.get("Target", "") for item in relations.findall(f"{PACKAGE}Relationship")}
42
+ sheets = []
43
+ for sheet in book.iter(f"{MAIN}sheet"):
44
+ target = targets.get(sheet.get(f"{DOCUMENT}id"), "")
45
+ path = target.lstrip("/") if target.startswith("/") else f"xl/{target}"
46
+ sheets.append((sheet.get("name", ""), path))
47
+ return sheets
48
+
49
+
50
+ def rows_of(archive: zipfile.ZipFile, path: str, shared: list[str]) -> list[str]:
51
+ """The rows of a sheet, one per line, the cells separated by tabs."""
52
+ root = ElementTree.fromstring(archive.read(path))
53
+ lines = []
54
+ for row in root.iter(f"{MAIN}row"):
55
+ cells: list[str] = []
56
+ for cell in row.findall(f"{MAIN}c"):
57
+ text = text_of(cell, shared).replace("\t", " ").replace("\n", " ")
58
+ while len(cells) < column_of(cell.get("r", "")):
59
+ cells.append("")
60
+ cells.append(text)
61
+ lines.append("\t".join(cells).rstrip("\t"))
62
+ return lines
63
+
64
+
65
+ if __name__ == "__main__":
66
+ if len(sys.argv) != 2:
67
+ raise SystemExit("usage: xlsx_text.py FILE.xlsx")
68
+ with zipfile.ZipFile(sys.argv[1]) as archive:
69
+ shared = shared_strings(archive)
70
+ for name, path in sheets_of(archive):
71
+ print(f"# {name}")
72
+ print("\n".join(rows_of(archive, path, shared)))
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: writing
3
+ description: Write or rewrite prose - an article, a post, an announcement, a summary - in the voice, the length and the tone the user asks for.
4
+ ---
5
+
6
+ # Writing
7
+
8
+ ## Steps
9
+
10
+ 1. **Find the brief.** Who reads it, what they should do after reading it,
11
+ how long it may be, what tone is wanted. When the user gives an example
12
+ of the voice they want, that example is the brief.
13
+ 2. **Find the shape.** An article: a hook, a promise, three to five points,
14
+ a close. A post: one idea, short paragraphs, a line that sticks.
15
+ An announcement: what changed, who is affected, what to do, when.
16
+ 3. **Draft.** Write the whole thing before polishing it. Keep the numbers
17
+ and the names exact; a draft is where the order gets fixed.
18
+ 4. **Cut.** A third of the words are usually not needed. Cut the hedges,
19
+ the throat-clearing and the sentence that repeats the last one.
20
+ 5. **Polish.** Read it aloud. Fix what sounds wrong. Check the numbers, the
21
+ names and the links one last time.
22
+
23
+ ## Rules
24
+
25
+ - Say the thing in the first paragraph. Nobody has to guess what the text
26
+ is about.
27
+ - Concrete beats abstract: "the export took four minutes" beats "the
28
+ export was slow".
29
+ - No invented facts, no invented quotes, no invented numbers. A gap in the
30
+ facts is marked as a gap.
31
+ - Keep the voice of the user, not the voice of a manual.
@@ -0,0 +1,269 @@
1
+ """The boundaries of a downloaded skill: how big, how deep, and where.
2
+
3
+ A skill comes from the network, so nothing in it may be taken for granted: a
4
+ path may leave the directory it should stay in, a file may be enormous, and a
5
+ link may point anywhere. Everything is checked here, before a byte lands in
6
+ the directory of the user.
7
+ """
8
+
9
+ import hashlib
10
+ import os
11
+ import re
12
+ import shutil
13
+ import tarfile
14
+ from dataclasses import dataclass
15
+ from pathlib import Path, PurePosixPath
16
+
17
+ from coderagent.skills.errors import SkillError
18
+
19
+ SKILL_NAME = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
20
+ """The names a skill may have. The name is a directory name, so it has to be safe."""
21
+
22
+ RESERVED = {"CON", "PRN", "AUX", "NUL"} | {f"COM{i}" for i in range(1, 10)} | {f"LPT{i}" for i in range(1, 10)}
23
+ """The names Windows does not allow. A skill that has one is no use there."""
24
+
25
+ CHUNK = 64 * 1024
26
+ """How many bytes are read at a time when a file is written."""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Policy:
31
+ """What a download may do and how big a skill may be."""
32
+
33
+ max_bytes: int = 8 * 1024 * 1024
34
+ """How many bytes a download may take."""
35
+ max_file_bytes: int = 1024 * 1024
36
+ """How many bytes one file of a skill may have."""
37
+ max_files: int = 2000
38
+ """How many files a skill may have."""
39
+ max_depth: int = 16
40
+ """How deep the directories of a skill may go."""
41
+ timeout: int = 30
42
+ """The seconds a download may take."""
43
+ allow_insecure: bool = False
44
+ """Whether `http://` may be fetched. `https://` is the rule."""
45
+ allowed_hosts: tuple[str, ...] = ()
46
+ """The hosts that may point inside the network."""
47
+
48
+ @classmethod
49
+ def from_config(cls, config) -> "Policy":
50
+ """The policy of a section of the configuration."""
51
+ return cls(
52
+ max_bytes=config.max_bytes,
53
+ max_file_bytes=config.max_file_bytes,
54
+ max_files=config.max_files,
55
+ max_depth=config.max_depth,
56
+ timeout=config.timeout,
57
+ allow_insecure=config.allow_insecure,
58
+ allowed_hosts=tuple(config.allowed_hosts),
59
+ )
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class FileEntry:
64
+ """One file of a skill."""
65
+
66
+ path: str
67
+ """The path of the file, relative to the directory of the skill."""
68
+ size: int
69
+ sha256: str
70
+
71
+
72
+ def digest(files: list[FileEntry]) -> str:
73
+ """One digest of a whole skill, the same whatever the order of the files."""
74
+ joined = "\n".join(f"{entry.path}:{entry.sha256}" for entry in sorted(files, key=lambda entry: entry.path))
75
+ return hashlib.sha256(joined.encode("utf-8")).hexdigest()
76
+
77
+
78
+ def sha256_of(path: Path) -> str:
79
+ """The digest of a file."""
80
+ sha = hashlib.sha256()
81
+ with path.open("rb") as handle:
82
+ for chunk in iter(lambda: handle.read(CHUNK), b""):
83
+ sha.update(chunk)
84
+ return sha.hexdigest()
85
+
86
+
87
+ def check_name(name: str) -> str:
88
+ """The name of a skill, when it is one a skill may have."""
89
+ if not SKILL_NAME.match(name):
90
+ raise SkillError(f"'{name}' is not a name a skill can have")
91
+ return name
92
+
93
+
94
+ def sanitize(text: str) -> str:
95
+ """A name a skill may have, made out of anything.
96
+
97
+ The name of a skill is a directory name: it is turned into lower case and
98
+ the characters that do not belong are replaced.
99
+ """
100
+ cleaned = re.sub(r"[^a-z0-9._-]+", "-", text.lower()).strip("-.")
101
+ return cleaned[:64]
102
+
103
+
104
+ def check_path(root: Path, relative: str) -> Path:
105
+ """The path of a file inside the root, or an error when it would leave.
106
+
107
+ The check is on the resolved path, not on the text: `a/../../b` and a
108
+ directory that is a link to somewhere else both leave the root.
109
+ """
110
+ parts = PurePosixPath(relative).parts
111
+ if not parts or any(part in ("", ".", "..") for part in parts):
112
+ raise SkillError(f"'{relative}' is not a path inside the skill")
113
+ for part in parts:
114
+ if ":" in part:
115
+ raise SkillError(f"'{relative}' has a name that is not allowed")
116
+ if part.split(".")[0].upper() in RESERVED:
117
+ raise SkillError(f"'{relative}' has a name that Windows does not allow")
118
+ target = root.joinpath(*parts)
119
+ if not target.resolve().is_relative_to(root.resolve()):
120
+ raise SkillError(f"'{relative}' points outside the skill")
121
+ return target
122
+
123
+
124
+ def unpack_tar(archive: Path, dest: Path, policy: Policy, prefix: str = "") -> list[FileEntry]:
125
+ """Unpack a tarball into a directory, refusing what does not belong there.
126
+
127
+ The members are checked one by one: only plain files and directories are
128
+ taken, the paths may not leave the directory, and the sizes may not pass
129
+ the policy. The first directory of the archive is dropped: it is the name
130
+ GitHub gives it, not a part of the skill.
131
+
132
+ With `prefix` only the part of the archive under that directory is taken:
133
+ a repository may be big, but a skill is small.
134
+ """
135
+ entries: list[FileEntry] = []
136
+ total = 0
137
+ dest.mkdir(parents=True, exist_ok=True)
138
+ prefix = prefix.strip("/")
139
+ try:
140
+ with tarfile.open(archive, "r:*") as tar:
141
+ members = tar.getmembers()
142
+ root = _root_of(members)
143
+ for member in members:
144
+ if member.name.startswith("/"):
145
+ raise SkillError(f"'{member.name}' is not a path inside the skill")
146
+ relative = _relative(member.name, root)
147
+ if prefix:
148
+ if relative == prefix:
149
+ continue
150
+ if not relative.startswith(f"{prefix}/"):
151
+ continue
152
+ relative = relative[len(prefix) + 1 :]
153
+ if not relative:
154
+ continue
155
+ if not (member.isfile() or member.isdir()):
156
+ raise SkillError(f"'{member.name}' is not a plain file")
157
+ if len(PurePosixPath(relative).parts) > policy.max_depth:
158
+ raise SkillError(f"'{relative}' is deeper than {policy.max_depth} levels")
159
+ target = check_path(dest, relative)
160
+ if member.isdir():
161
+ target.mkdir(parents=True, exist_ok=True)
162
+ continue
163
+ if len(entries) >= policy.max_files:
164
+ raise SkillError(f"the skill has more than {policy.max_files} files")
165
+ if member.size > policy.max_file_bytes:
166
+ raise SkillError(f"'{relative}' is bigger than {policy.max_file_bytes} bytes")
167
+ total += member.size
168
+ if total > policy.max_bytes:
169
+ raise SkillError(f"the skill is bigger than {policy.max_bytes} bytes")
170
+ handle = tar.extractfile(member)
171
+ if handle is None:
172
+ raise SkillError(f"'{relative}' cannot be read")
173
+ target.parent.mkdir(parents=True, exist_ok=True)
174
+ with target.open("wb") as output:
175
+ shutil.copyfileobj(handle, output, CHUNK)
176
+ entries.append(FileEntry(relative, member.size, sha256_of(target)))
177
+ except tarfile.TarError as error:
178
+ raise SkillError(f"the archive cannot be read: {error}") from None
179
+ return entries
180
+
181
+
182
+ def copy_tree(source: Path, dest: Path, policy: Policy) -> list[FileEntry]:
183
+ """Copy a directory of a repository into the directory of a skill.
184
+
185
+ A repository is not an archive: it may hold links, and it may hold
186
+ anything. The same checks as for an archive are made here.
187
+ """
188
+ entries: list[FileEntry] = []
189
+ total = 0
190
+ for directory, dirnames, filenames in os.walk(source, followlinks=False):
191
+ base = Path(directory)
192
+ for name in dirnames:
193
+ if (base / name).is_symlink():
194
+ raise SkillError(f"'{name}' is a link, it is not allowed")
195
+ for name in filenames:
196
+ path = base / name
197
+ relative = path.relative_to(source).as_posix()
198
+ if path.is_symlink():
199
+ raise SkillError(f"'{relative}' is a link, it is not allowed")
200
+ if not path.is_file():
201
+ raise SkillError(f"'{relative}' is not a plain file")
202
+ if len(PurePosixPath(relative).parts) > policy.max_depth:
203
+ raise SkillError(f"'{relative}' is deeper than {policy.max_depth} levels")
204
+ if len(entries) >= policy.max_files:
205
+ raise SkillError(f"the skill has more than {policy.max_files} files")
206
+ size = path.stat().st_size
207
+ if size > policy.max_file_bytes:
208
+ raise SkillError(f"'{relative}' is bigger than {policy.max_file_bytes} bytes")
209
+ total += size
210
+ if total > policy.max_bytes:
211
+ raise SkillError(f"the skill is bigger than {policy.max_bytes} bytes")
212
+ target = check_path(dest, relative)
213
+ target.parent.mkdir(parents=True, exist_ok=True)
214
+ shutil.copyfile(path, target)
215
+ entries.append(FileEntry(relative, size, sha256_of(target)))
216
+ return entries
217
+
218
+
219
+ def entries_of(directory: Path) -> list[FileEntry]:
220
+ """The files of a directory, with their size and their digest."""
221
+ entries = []
222
+ for path in sorted(directory.rglob("*")):
223
+ if path.is_symlink() or not path.is_file():
224
+ continue
225
+ entries.append(FileEntry(path.relative_to(directory).as_posix(), path.stat().st_size, sha256_of(path)))
226
+ return entries
227
+
228
+
229
+ def _root_of(members: list[tarfile.TarInfo]) -> str:
230
+ """The directory every member of the archive is under, when there is one.
231
+
232
+ The archive of GitHub holds the directory of the repository as a member of
233
+ its own: that member names the root, but it is not a part of the skill.
234
+ A plain file at the top says there is no root at all.
235
+ """
236
+ roots = set()
237
+ for member in members:
238
+ parts = PurePosixPath(member.name).parts
239
+ if not parts:
240
+ return ""
241
+ if len(parts) == 1 and not member.isdir():
242
+ return ""
243
+ roots.add(parts[0])
244
+ return roots.pop() if len(roots) == 1 else ""
245
+
246
+
247
+ def _relative(name: str, root: str) -> str:
248
+ """The path of a member, without the directory the archive is under."""
249
+ parts = list(PurePosixPath(name).parts)
250
+ if root and parts and parts[0] == root:
251
+ parts = parts[1:]
252
+ return "/".join(parts)
253
+
254
+
255
+ __all__ = [
256
+ "CHUNK",
257
+ "FileEntry",
258
+ "Policy",
259
+ "RESERVED",
260
+ "SKILL_NAME",
261
+ "check_name",
262
+ "check_path",
263
+ "copy_tree",
264
+ "digest",
265
+ "entries_of",
266
+ "sanitize",
267
+ "sha256_of",
268
+ "unpack_tar",
269
+ ]
@@ -0,0 +1,177 @@
1
+ """The sites of skills: the repositories that hold them.
2
+
3
+ The three sites below are the ones the Chinese community knows best among the
4
+ repositories that really hold skills. Their skills are read from a clone of the
5
+ repository and not from an API: the API of GitHub is quick with its quota and
6
+ the API of Gitee lets anonymous callers in for a while and then refuses them,
7
+ but a clone always works. The clone is kept in the cache for a while, so the
8
+ second tab is not a second wait.
9
+ """
10
+
11
+ import shutil
12
+ import time
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from coderagent.paths import config_home
17
+ from coderagent.skills import SKILL_FILE, parse_skill
18
+ from coderagent.skills.errors import SkillError
19
+ from coderagent.skills.sandbox import Policy
20
+ from coderagent.skills.source import GITEE, GITHUB, clone_repository
21
+
22
+ CACHE = "cache/skills/sites"
23
+ """Where the clones of the sites wait."""
24
+
25
+ LIFE = 12 * 60 * 60
26
+ """The seconds a clone of a site is used before the site is fetched again."""
27
+
28
+ ROWS = 6
29
+ """How many skills a site shows at a time."""
30
+
31
+ HOSTS = {"github": GITHUB, "gitee": GITEE}
32
+ """Where the repositories of a kind of host are cloned from."""
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Site:
37
+ """A site of skills."""
38
+
39
+ id: str
40
+ """The name of the site in the address of the page."""
41
+
42
+ repo: str
43
+ """The repository of the site: `owner/name`."""
44
+
45
+ path: str = ""
46
+ """The directory of the skills inside the repository."""
47
+
48
+ accent: str = "#6aa9ff"
49
+ """The colour of the site in the page, so that the tabs differ."""
50
+
51
+ kind: str = "github"
52
+ """The host of the repository: `github` or `gitee`."""
53
+
54
+ @property
55
+ def url(self) -> str:
56
+ """The address of the site."""
57
+ return f"{HOSTS[self.kind]}/{self.repo}"
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class SiteSkill:
62
+ """One skill of a site."""
63
+
64
+ name: str
65
+ description: str
66
+ path: str
67
+ """The directory of the skill inside the repository."""
68
+
69
+
70
+ SITES = (
71
+ Site(id="official", repo="oschina/gitee-agent-skills", accent="#ef7059", kind="gitee"),
72
+ Site(id="personal", repo="yang_huai_qiang1/agent-skills", accent="#4fb0f5", kind="gitee"),
73
+ Site(id="tools", repo="jianchaoteng/agent-skills", accent="#a98bff", kind="gitee"),
74
+ )
75
+ """The sites of the tabs, in the order they are shown.
76
+
77
+ The three are the ones the Chinese community knows best: the repository of
78
+ Gitee itself, a collection of everyday skills and a small one of tools. The
79
+ stars of Gitee tell little about them, so the ranking is the one of the
80
+ community: who keeps them, how many skills they hold and how often they are
81
+ touched.
82
+ """
83
+
84
+
85
+ def site_of(id: str) -> Site:
86
+ """The site of an id."""
87
+ for site in SITES:
88
+ if site.id == id:
89
+ return site
90
+ raise SkillError(f"there is no site with the name {id}")
91
+
92
+
93
+ def list_skills(site: Site, policy: Policy, refresh: bool = False) -> list[SiteSkill]:
94
+ """Every skill of a site.
95
+
96
+ With `refresh` the clone is thrown away and fetched again: the page asks
97
+ for that when the user wants to see what the site looks like now.
98
+ """
99
+ return skills_of(_checkout(site, policy, refresh), site)
100
+
101
+
102
+ def skills_of(root: Path, site: Site) -> list[SiteSkill]:
103
+ """The skills of a clone of the repository of a site.
104
+
105
+ A skill may sit anywhere in the directory of the site: the collections
106
+ put them into folders of their own. The directories whose name begins
107
+ with a dot are left out: they hold the machinery of the repository, not
108
+ skills for the agent.
109
+ """
110
+ base = root / site.path if site.path else root
111
+ if not base.is_dir():
112
+ raise SkillError(f"there is no '{site.path}' in {site.repo}")
113
+ skills = []
114
+ for path in sorted(base.glob(f"**/{SKILL_FILE}")):
115
+ if any(part.startswith(".") for part in path.relative_to(base).parts[:-1]):
116
+ continue
117
+ skill = _parse(path)
118
+ if skill is None:
119
+ """A directory without a front matter is not a skill."""
120
+ continue
121
+ skills.append(
122
+ SiteSkill(
123
+ name=skill.name,
124
+ description=skill.description,
125
+ path=path.parent.relative_to(root).as_posix(),
126
+ )
127
+ )
128
+ return skills
129
+
130
+
131
+ def _parse(path: Path):
132
+ """The skill of a file, when the file is one."""
133
+ try:
134
+ return parse_skill(path)
135
+ except (OSError, UnicodeDecodeError):
136
+ return None
137
+
138
+
139
+ def _checkout(site: Site, policy: Policy, refresh: bool = False) -> Path:
140
+ """The clone of a site, fresh enough to be used."""
141
+ directory = config_home() / CACHE / site.id
142
+ if not refresh and _is_fresh(directory):
143
+ return directory
144
+ shutil.rmtree(directory, ignore_errors=True)
145
+ directory.parent.mkdir(parents=True, exist_ok=True)
146
+ try:
147
+ clone_repository(f"{site.url}.git", directory, policy)
148
+ except SkillError:
149
+ shutil.rmtree(directory, ignore_errors=True)
150
+ raise
151
+ (directory / ".fetched").write_text(str(time.time()), encoding="utf-8")
152
+ return directory
153
+
154
+
155
+ def _is_fresh(directory: Path) -> bool:
156
+ """Whether the clone of a site may still be used."""
157
+ marker = directory / ".fetched"
158
+ if not (directory / ".git").is_dir() or not marker.exists():
159
+ return False
160
+ try:
161
+ return time.time() - float(marker.read_text(encoding="utf-8")) < LIFE
162
+ except ValueError:
163
+ return False
164
+
165
+
166
+ __all__ = [
167
+ "CACHE",
168
+ "HOSTS",
169
+ "LIFE",
170
+ "ROWS",
171
+ "SITES",
172
+ "Site",
173
+ "SiteSkill",
174
+ "list_skills",
175
+ "site_of",
176
+ "skills_of",
177
+ ]